This repository has been archived by the owner on Apr 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
setup-master.py
executable file
·422 lines (385 loc) · 16.8 KB
/
setup-master.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/env python
"""
setup-master.py master_dir master_name
setup-master.py -t [masters...]
setup-master.py -l [--tested-only] [masters...]
Sets up mozilla buildbot master in master_dir."""
import os
import glob
import shutil
import subprocess
import urllib
import tempfile
import sys
import logging
try:
import simplejson as json
assert json
except ImportError:
import json
class MasterConfig:
def __init__(self, name=None, config_dir=None, globs=None, renames=None,
local_links=None, extras=None, log=None):
self.name = name or None
self.config_dir = config_dir
self.globs = globs or []
self.renames = renames or []
self.local_links = local_links or []
self.extras = extras or []
self.log = log or None
def __add__(self, o):
retval = MasterConfig(
name=self.name or o.name,
config_dir=self.config_dir or o.config_dir,
globs=self.globs + o.globs,
renames=self.renames + o.renames,
local_links=self.local_links + o.local_links,
extras=self.extras + o.extras,
)
return retval
def createMaster(self, master_dir, buildbot, logfile=None):
# The following is needed to maintain exisitng behaviour
# of printing stderr of buildbot
if logfile:
self.log.debug('opening "%s" for buildbot create master stdout '
'and stderr' % logfile)
s_out = open(logfile, 'w+')
s_err = subprocess.STDOUT
else:
s_out = open(os.devnull, 'w+')
s_err = sys.stderr
subprocess.check_call([buildbot, 'create-master', master_dir],
stdout=s_out, stderr=s_err)
s_out.close()
if not os.path.exists(master_dir):
self.log.debug('mkdir -p %s' % master_dir)
os.makedirs(master_dir)
for g in self.globs:
for f in glob.glob(os.path.join(self.config_dir, g)):
dst = os.path.join(master_dir, os.path.basename(f))
if os.path.lexists(dst):
self.log.debug('rm -f %s' % dst)
os.unlink(dst)
src = os.path.abspath(f)
self.log.debug('ln -s %s %s' % (src, dst))
os.symlink(src, dst)
for src, dst in self.local_links:
dst = os.path.join(master_dir, dst)
if os.path.lexists(dst):
self.log.debug('rm -f %s' % dst)
os.unlink(dst)
self.log.debug('ln -s %s %s' % (src, dst))
os.symlink(src, dst)
for src, dst in self.renames:
dst = os.path.join(master_dir, dst)
if os.path.lexists(dst):
self.log.debug('rm -f %s' % dst)
os.unlink(dst)
self.log.debug(
'cp %s %s' % (os.path.join(self.config_dir, src), dst))
shutil.copy(os.path.join(self.config_dir, src), dst)
for extra_filename, extra_data in self.extras:
self.log.debug('writing %s to %s' % (
extra_data.replace('\n', '\\n'), extra_filename))
f = open(os.path.join(
master_dir, extra_filename), 'w').write(extra_data)
# Remove leftover files
for f in "Makefile.sample", "master.cfg.sample":
dst = os.path.join(master_dir, f)
if os.path.exists(dst):
os.unlink(dst)
def logFile(self, filename):
self.log.info("starting to print log file '%s'" % filename)
f = open(filename)
data = f.readline()
while data != '':
self.log.info(data.rstrip('\n'))
data = f.readline()
f.close()
self.log.info("finished printing log file '%s'" % filename)
def testMaster(self, buildbot, universal=False, error_logs=False):
test_output_dir = os.environ.get('TEMP', 'test-output')
if not os.path.isdir(test_output_dir):
os.mkdir(test_output_dir)
test_dir = tempfile.mkdtemp(prefix='%s-' % self.name, dir=os.path.join(
os.getcwd(), test_output_dir))
test_log_filename = test_dir + '-checkconfig.log'
create_log_filename = test_dir + '-create-master.log'
test_log = open(test_log_filename, 'w')
self.log.info('creating "%s" master' % self.name)
try:
self.createMaster(test_dir, buildbot, logfile=create_log_filename)
self.log.info(
'created "%s" master, running checkconfig' % self.name)
except (OSError, subprocess.CalledProcessError):
self.log.error('TEST-FAIL failed to create "%s"' % self.name)
if error_logs:
self.logFile(create_log_filename)
return (300, create_log_filename, None)
rc = subprocess.call([buildbot, 'checkconfig'],
cwd=test_dir, stdout=test_log,
stderr=subprocess.STDOUT)
test_log.close()
log = open(test_log_filename)
log_size = os.path.getsize(test_log_filename)
# We expect that the reconfig done message is before the last K of
# output
if log_size > 1024:
log.seek(log_size - 1024)
log_tail = log.readlines()
if 'Config file is good!' in [x.strip() for x in log_tail] and rc == 0:
self.log.info("TEST-PASS checkconfig OK for %s" % self.name)
shutil.rmtree(test_dir)
os.remove(test_log_filename)
return (0, None, None)
else:
if error_logs:
self.logFile(test_log_filename)
if rc == 0:
self.log.warn('checkconfig returned 0 for %s but didn\'t '
'print "Config file is good!"' % self.name)
else:
self.log.error(
"TEST-FAIL %s failed to run checkconfig" % self.name)
self.log.info(
'log for "%s" is "%s"' % (self.name, test_log_filename))
return (rc, test_log_filename, test_dir)
def load_masters_json(masters_json, role=None, universal=False, log=None,
dedupe=True, ignored_roles=[]):
if 'http' in masters_json:
masters = json.load(urllib.urlopen(masters_json))
else:
masters = json.load(open(masters_json))
if dedupe:
# Remove masters that are pretty much identical
# Mapping of unique master representatoin to the first master of that
# type
unique_masters = {}
# List of master instances
new_masters = []
for m in masters:
m0 = m.copy()
# Remove unimportant stuff
for k in ("basedir", "bbcustom_dir", "buildbot_bin",
"buildbot_python", "buildbot_setup", "datacentre",
"db_name", "hostname", "http_port", "master_dir", "name",
"pb_port", "ssh_port", "tools_dir"):
if k in m0:
del m0[k]
k = json.dumps(m0, sort_keys=True)
if k not in unique_masters:
unique_masters[k] = m
new_masters.append(m)
else:
log.debug("Skipping %s; same as %s", m['name'],
unique_masters[k]['name'])
masters = new_masters
retval = []
for m in masters:
# Sometimes we only want masters of a specific role to be loaded
if role and m['role'] != role:
continue
if ignored_roles and m['role'] in ignored_roles:
continue
if m['environment'] == 'production':
environment_config = 'production_config.py'
elif m['environment'] == 'staging':
environment_config = 'staging_config.py'
c = MasterConfig(
name=m['name'],
globs=['config.py', 'thunderbird_config.py', '*_config.py',
'*_common.py', '*_project_branches.py',
'project_branches.py', 'gecko_versions.json'],
renames=[('BuildSlaves.py.template', 'BuildSlaves.py'),
('passwords.py.template', 'passwords.py')],
local_links=[(environment_config, 'localconfig.py'),
('thunderbird_' + environment_config,
'thunderbird_localconfig.py'),
('b2g_' + environment_config, 'b2g_localconfig.py')],
extras=[('master_config.json',
json.dumps(m, indent=2, sort_keys=True))],
log=log
)
if universal:
c.name += '-universal'
mastercfg = 'universal_master_sqlite.cfg'
else:
if m['role'] == 'tests':
mastercfg = 'tests_master.cfg'
elif m['role'] == 'build' or m['role'] == 'try':
mastercfg = 'builder_master.cfg'
elif m['role'] == 'scheduler':
mastercfg = 'scheduler_master.cfg'
else:
raise AssertionError("What is a %s role?" % m['role'])
if m['role'] == 'build':
c.config_dir = 'mozilla'
c.globs.append('l10n-changesets*')
c.globs.append('release_templates')
if m['environment'] == 'staging':
c.globs.append('staging_release-*-*.py')
# release-*.py -> staging_release-*.py symlinks
c.local_links.extend(
[('staging_release-firefox-mozilla-%s.py' % v,
'release-firefox-mozilla-%s.py' % v)
for v in ['beta', 'release', 'esr38', 'esr45']
] +
[('staging_release-fennec-mozilla-%s.py' % v,
'release-fennec-mozilla-%s.py' % v)
for v in ['beta', 'release']
] +
[('staging_release-thunderbird-comm-%s.py' % v,
'release-thunderbird-comm-%s.py' % v)
for v in ['beta', 'esr38', 'esr45']
]
)
else:
c.globs.append('release-firefox*.py')
c.globs.append('release-fennec*.py')
c.globs.append('release-thunderbird*.py')
c.globs.append(mastercfg)
c.globs.append('build_localconfig.py')
c.local_links.append((mastercfg, 'master.cfg'))
c.local_links.append(
('build_localconfig.py', 'master_localconfig.py'))
elif m['role'] == 'try':
c.config_dir = 'mozilla'
c.local_links.append((mastercfg, 'master.cfg'))
c.local_links.append(
('try_localconfig.py', 'master_localconfig.py'))
c.globs.append(mastercfg)
c.globs.append('try_localconfig.py')
elif m['role'] == 'tests':
c.config_dir = 'mozilla-tests'
c.local_links.append((mastercfg, 'master.cfg'))
c.local_links.append(
('tests_localconfig.py', 'master_localconfig.py'))
c.globs.append('tests_localconfig.py')
c.globs.append('config_seta.py')
c.globs.append(mastercfg)
elif m['role'] == 'scheduler':
if 'build_scheduler' in m['name']:
c.config_dir = 'mozilla'
c.globs.append('release-firefox*.py')
c.globs.append('release-fennec*.py')
c.globs.append('release-thunderbird*.py')
c.globs.append('release_templates')
elif 'tests_scheduler' in m['name']:
c.config_dir = 'mozilla-tests'
c.globs.append(mastercfg)
c.globs.append('scheduler_localconfig.py')
c.local_links.append((mastercfg, 'master.cfg'))
c.local_links.append(
('scheduler_localconfig.py', 'master_localconfig.py'))
c.globs.append('config_seta.py')
retval.append(c)
return retval
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser(__doc__)
parser.set_defaults(action=None, masters_json=None)
parser.add_option("-l", "--list", action="store_true", dest="list")
parser.add_option("-t", "--test", action="store_true", dest="test")
parser.add_option(
"-8", action="store_true", dest="buildbot08", default=False)
parser.add_option("-b", "--buildbot", dest="buildbot", default="buildbot")
parser.add_option("-j", "--masters-json", dest="masters_json",
default="https://hg.mozilla.org/build/tools/raw-file/"
"default/buildfarm/maintenance/production-masters.json")
parser.add_option("-R", "--role", dest="role", default=None,
help="Filter by given comma-separated role(s), eg try,"
"build, tests, scheduler")
parser.add_option(
"-u", "--universal", dest="universal", action="store_true",
help="Set up a universal master")
parser.add_option("-q", "--quiet", dest="quiet", action="store_true")
parser.add_option(
"-e", "--error-logs", dest="error_logs", action="store_true")
parser.add_option("-d", "--debug", dest="debug", action="store_true")
parser.add_option(
"--tested-only", dest="tested_only", action="store_true",
help="Restrict to the set of masters that would be used with -t")
parser.add_option(
"--ignore-role", dest="ignored_roles", action="append", default=[],
help="Ignore masters with this role. May be passed multiple times.")
options, args = parser.parse_args()
if options.debug:
loglvl = logging.DEBUG
elif options.quiet:
loglvl = logging.ERROR
else:
loglvl = logging.INFO
ignored_roles = options.ignored_roles
log = logging.getLogger('setup-master')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(loglvl)
cf = logging.Formatter('%(levelname)-5s - %(message)s')
ch.setFormatter(cf)
log.addHandler(ch)
log.debug('using master json file from "%s"' % options.masters_json)
if options.role:
log.info('filtering by "%s" roles' % options.role)
if options.test:
options.tested_only = True
master_list = load_masters_json(options.masters_json, role=options.role,
log=log, universal=options.universal,
dedupe=options.tested_only,
ignored_roles=ignored_roles)
if options.tested_only:
log.debug('adding universal builders because we are testing')
# a universal scheduler master doesn't make any sense
ignored_roles += ['scheduler']
uni_masters = load_masters_json(
options.masters_json, role=options.role,
universal=not options.universal, log=log,
ignored_roles=ignored_roles)
master_list.extend(uni_masters)
# Make sure we don't have duplicate names
master_map = dict((m.name, m) for m in master_list)
assert len(
master_map.values()) == len(master_list), "Duplicate master names"
assert len(master_list) > 0, "No masters specified. Bad role?"
if options.list or options.test:
if len(args) > 0:
wanted = set(args)
available = set([m.name for m in master_list])
unknown = wanted - available
assert len(unknown) == 0, \
"%d unknown masters requested: %s" % (len(unknown),
" ".join(unknown))
masters = [m for m in master_list if m.name in wanted]
else:
masters = master_list
if options.list:
for m in masters:
print m.name
elif options.test:
failing_masters = []
# Test the masters, once normally and onces as a universal master
for m in masters:
rc, logfile, dir = m.testMaster(
options.buildbot, error_logs=options.error_logs)
if rc != 0:
failing_masters.append((m.name, logfile, dir))
# Print a summary including a list of useful output
log.info("TEST-SUMMARY: %s tested, %s failed" % (len(
master_list), len(failing_masters)))
for rc, logfile, dir in failing_masters:
def s(n):
if n is not None:
return n[len(os.getcwd()) + 1:]
log.info("FAILED-MASTER %s, log: '%s', dir: '%s'" %
(rc, s(logfile), s(dir)))
exit(len(failing_masters))
elif len(args) == 2:
master_dir, master_name = args[:2]
if options.universal:
master_name = master_name + '-universal'
if master_name not in master_map:
log.error("Unknown master %s" % master_name)
m = master_map[master_name]
m.createMaster(master_dir, options.buildbot)
else:
parser.print_usage()
parser.exit()