This repository has been archived by the owner on Jun 11, 2019. It is now read-only.
/
misc.py
542 lines (450 loc) · 19.4 KB
/
misc.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla-specific Buildbot steps.
#
# The Initial Developer of the Original Code is
# Mozilla Corporation.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Ben Hearsum <bhearsum@mozilla.com>
# Rob Campbell <rcampbell@mozilla.com>
# Chris Cooper <ccooper@mozilla.com>
# ***** END LICENSE BLOCK *****
from twisted.python.failure import Failure, DefaultException
from twisted.internet import reactor
from twisted.spread.pb import PBConnectionLost
from twisted.python import log
from twisted.internet.defer import Deferred, TimeoutError
import os
import re
from buildbot.process.buildstep import LoggedRemoteCommand, BuildStep
from buildbot.steps.shell import WithProperties
from buildbot.status.builder import FAILURE, SUCCESS, SKIPPED, worst_status
from buildbot.status.builder import STDOUT, STDERR # MockProperty
from buildbotcustom.steps.base import LoggingBuildStep, ShellCommand, \
addRetryEvaluateCommand, RetryingShellCommand
from buildbotcustom.common import genBuildID, genBuildUID
from buildbotcustom.try_parser import processMessage
class TinderboxShellCommand(ShellCommand):
haltOnFailure = False
"""This step is really just a 'do not care' buildstep for executing a
slave command and ignoring the results. If ignoreCodes is passed,
only exit codes listed in it will be ignored. If ignoreCodes is not
passed, all exit codes will be ignored.
"""
def __init__(self, ignoreCodes=None, **kwargs):
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
self.addFactoryArguments(ignoreCodes=ignoreCodes)
self.ignoreCodes = ignoreCodes
def evaluateCommand(self, cmd):
# Ignore all return codes
if not self.ignoreCodes:
return SUCCESS
else:
# Ignore any of the return codes we're told to
if cmd.rc in self.ignoreCodes:
return SUCCESS
# If the return code is something else, fail
else:
return FAILURE
class SendChangeStep(ShellCommand):
warnOnFailure = True
flunkOnFailure = False
name = "sendchange"
description = ["sendchange"]
def __init__(self, master, branch, files, revision=None, user=None,
comments="", sendchange_props=None, timeout=1800, retries=5, **kwargs):
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
self.addFactoryArguments(master=master, branch=branch, files=files,
revision=revision, user=user,
comments=comments, timeout=timeout,
sendchange_props=sendchange_props, retries=retries)
self.master = master
self.branch = branch
self.files = files
self.revision = revision
self.user = user
self.comments = comments
self.sendchange_props = sendchange_props or {}
self.timeout = timeout
self.retries = retries
self.name = 'sendchange'
self.sleepTime = 5
def start(self):
try:
props = self.build.getProperties()
branch = props.render(self.branch)
revision = props.render(self.revision)
comments = props.render(self.comments)
files = props.render(self.files)
user = props.render(self.user)
sendchange_props = []
for key, value in self.sendchange_props.iteritems():
sendchange_props.append((key, props.render(value)))
self.addCompleteLog("sendchange", """\
master: %s
branch: %s
revision: %s
comments: %s
user: %s
files: %s
properties: %s""" % (self.master, branch, revision, comments,
user, files, sendchange_props))
bb_cmd = ['buildbot', 'sendchange', '--master', self.master,
'--username', user, '--branch', branch,
'--revision', revision]
if isinstance(comments, basestring):
if re.search('try: ', comments, re.MULTILINE):
comments = 'try: ' + ' '.join(processMessage(comments))
else:
try:
comments = comments.splitlines()[0]
except IndexError:
comments = ''
comments = re.sub(r'[\r\n^<>|;&"\'%$]', '_', comments)
comments = comments.encode('ascii', 'replace')
if comments:
bb_cmd.extend(['--comments', comments])
for key, value in sendchange_props:
bb_cmd.extend(['--property', '%s:%s' % (key, value)])
if files:
bb_cmd.extend(self.files)
cmd = ['python',
WithProperties("%(toolsdir)s/buildfarm/utils/retry.py"),
'-s', str(self.sleepTime), '-t', str(self.timeout),
'-r', str(self.retries), '--stdout-regexp', 'change sent successfully']
cmd.extend(bb_cmd)
self.setCommand(cmd)
self.super_class.start(self)
except KeyError:
self.addCompleteLog("errors", str(Failure()))
return self.finished(FAILURE)
class DownloadFile(ShellCommand):
haltOnFailure = True
name = "download"
description = ["download"]
retries = 5
waitRetry = 120
def __init__(
self, url_fn=None, url=None, url_property=None, filename_property=None,
ignore_certs=False, wget_args=None, **kwargs):
self.url = url
self.url_fn = url_fn
self.url_property = url_property
self.filename_property = filename_property
self.ignore_certs = ignore_certs
assert bool(self.url) ^ bool(self.url_fn), \
"One of url_fn or url must be set, not both (%s %s)"
if wget_args:
self.wget_args = wget_args[:]
else:
self.wget_args = ['--progress=dot:mega']
self.wget_args += ["--tries=%d" % self.retries,
"--waitretry=%d" % self.waitRetry]
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
self.addFactoryArguments(url_fn=url_fn, url=url,
url_property=url_property, filename_property=filename_property,
ignore_certs=ignore_certs, wget_args=wget_args)
def start(self):
try:
if self.url_fn:
url = self.url_fn(self.build)
else:
url = self.url
except Exception, e:
self.addCompleteLog("errors", "Automation Error: %s" % str(e))
return self.finished(FAILURE)
renderedUrl = self.build.getProperties().render(url)
if self.url_property:
self.setProperty(self.url_property, renderedUrl, "DownloadFile")
if self.filename_property:
self.setProperty(self.filename_property,
os.path.basename(renderedUrl), "DownloadFile")
if self.ignore_certs:
self.setCommand(["wget"] + self.wget_args + ["-N",
"--no-check-certificate", url])
else:
self.setCommand(["wget"] + self.wget_args + ["-N", url])
self.super_class.start(self)
def evaluateCommand(self, cmd):
superResult = self.super_class.evaluateCommand(self, cmd)
if SUCCESS != superResult:
return superResult
if None != re.search('ERROR', cmd.logs['stdio'].getText()):
return FAILURE
return SUCCESS
class UnpackFile(ShellCommand):
description = ["unpack"]
def __init__(self, filename, scripts_dir=".", **kwargs):
self.filename = filename
self.scripts_dir = scripts_dir
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
self.addFactoryArguments(filename=filename, scripts_dir=scripts_dir)
def start(self):
filename = self.build.getProperties().render(self.filename)
self.filename = filename
if filename.endswith(".zip") or filename.endswith(".apk"):
self.setCommand(['unzip', '-oq', filename])
elif filename.endswith(".tar.gz"):
self.setCommand(['tar', '-zxf', filename])
elif filename.endswith(".tar.bz2"):
self.setCommand(['tar', '-jxf', filename])
elif filename.endswith(".dmg"):
self.setCommand(['bash',
'%s/installdmg.sh' % self.scripts_dir,
filename]
)
else:
raise ValueError("Don't know how to handle %s" % filename)
self.super_class.start(self)
def evaluateCommand(self, cmd):
superResult = self.super_class.evaluateCommand(self, cmd)
if SUCCESS != superResult:
return superResult
if None != re.search('^Usage:', cmd.logs['stdio'].getText()):
return FAILURE
return SUCCESS
class FindFile(ShellCommand):
def __init__(self, filename, directory, max_depth, property_name, filetype=None, **kwargs):
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
self.addFactoryArguments(filename=filename, directory=directory,
max_depth=max_depth, property_name=property_name,
filetype=filetype)
self.property_name = property_name
if filetype == "file":
filetype = "-type f"
elif filetype == "dir":
filetype = "-type d"
else:
filetype = ""
self.setCommand(['bash', '-c', 'find %(directory)s -maxdepth %(max_depth)s %(filetype)s -name %(filename)s' % locals()])
def evaluateCommand(self, cmd):
worst = self.super_class.evaluateCommand(self, cmd)
try:
output = cmd.logs['stdio'].getText().strip()
if output:
self.setProperty(self.property_name, output)
worst = worst_status(worst, SUCCESS)
else:
worst = worst_status(worst, FAILURE)
except:
pass
return worst
class MozillaClobberer(ShellCommand):
flunkOnFailure = False
description = ['checking', 'clobber', 'times']
def __init__(self, branch, clobber_url, clobberer_path, clobberTime=None,
timeout=3600, workdir='..', command=[], **kwargs):
command = ['python', clobberer_path, '-s', 'tools']
if clobberTime:
command.extend(['-t', str(clobberTime)])
command.extend([
clobber_url,
branch,
WithProperties("%(buildername)s"),
WithProperties("%(slavebuilddir)s"),
WithProperties("%(slavename)s"),
WithProperties("%(master)s"),
])
self.super_class = ShellCommand
self.super_class.__init__(self, command=command, timeout=timeout,
workdir=workdir, **kwargs)
self.addFactoryArguments(branch=branch, clobber_url=clobber_url,
clobberer_path=clobberer_path,
clobberTime=clobberTime)
def setBuild(self, build):
self.super_class.setBuild(self, build)
# Set the "master" property
master = build.builder.botmaster.parent.buildbotURL
self.setProperty('master', master)
def createSummary(self, log):
clobberTypeRE = re.compile(r"TinderboxPrint: (\w+) clobber")
clobberTypePerformed = None
for line in log.readlines():
m = clobberTypeRE.match(line)
if m:
clobberTypePerformed = m.group(1)
break
for clobberType in ('forced', 'periodic', 'purged'):
wasPerformed = clobberType == clobberTypePerformed
self.setProperty('%s_clobber' % clobberType, wasPerformed, 'MozillaClobberer')
class SetBuildProperty(BuildStep):
name = "set build property"
def __init__(self, property_name, value, **kwargs):
self.property_name = property_name
self.value = value
BuildStep.__init__(self, **kwargs)
self.addFactoryArguments(property_name=property_name, value=value)
def start(self):
if callable(self.value):
value = self.value(self.build)
else:
value = self.value
self.setProperty(self.property_name, value)
self.step_status.setText(['set props:', self.property_name])
self.addCompleteLog(
"property changes", "%s: %s" % (self.property_name, value))
return self.finished(SUCCESS)
class OutputStep(BuildStep):
"""Simply logs some output"""
name = "output"
def __init__(self, data, log='output', **kwargs):
self.data = data
self.log = log
BuildStep.__init__(self, **kwargs)
self.addFactoryArguments(data=data, log=log)
def start(self):
properties = self.build.getProperties()
if callable(self.data):
data = properties.render(self.data(self.build))
else:
data = properties.render(self.data)
if not isinstance(data, (str, unicode)):
try:
data = " ".join(data)
except:
data = str(data)
self.addCompleteLog(self.log, data)
self.step_status.setText([self.name])
return self.finished(SUCCESS)
class DisconnectStep(ShellCommand):
"""This step is used when a command is expected to cause the slave to
disconnect from the master. It will handle connection lost errors as
expected.
Optionally it will also forcibly disconnect the slave from the master by
calling the remote 'shutdown' command, in effect doing a graceful
shutdown. If force_disconnect is True, then the slave will always be
disconnected after the command completes. If force_disconnect is a
function, it will be called with the command object, and the return value
will be used to determine if the slave should be disconnected."""
name = "disconnect"
def __init__(self, force_disconnect=None, **kwargs):
self.force_disconnect = force_disconnect
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
self.addFactoryArguments(force_disconnect=force_disconnect)
self._disconnected = False
self._deferred_death = None
def interrupt(self, reason):
# Called when the slave command is interrupted, e.g. by rebooting
# We assume this is expected
self._disconnected = True
return self.finished(SUCCESS)
def start(self):
# If a graceful shutdown was requested it doesn't make sense to reboot
# the slave - so let's not do anything!
if self.build.slavebuilder.slave is None:
# bug 1136765 - The slave isn't connected and there's no benefit
# from trying to disconnect it.
return SKIPPED
if self.build.slavebuilder.slave.slave_status.getGraceful():
return SKIPPED
# Give the machine 60 seconds to go away on its own
def die():
self._deferred_death = None
log.msg("Forcibly disconnecting %s" % self.getSlaveName())
self.buildslave.disconnect()
try:
# Try to close the socket too
self.buildslave.slave.broker.transport._closeSocket()
except:
log.err()
self._deferred_death = reactor.callLater(60, die)
return self.super_class.start(self)
def checkDisconnect(self, f):
# This is called if there's a problem executing the command because the connection was disconnected.
# Again, we assume this is the expected behaviour
f.trap(PBConnectionLost)
self._disconnected = True
return self.finished(SUCCESS)
def commandComplete(self, cmd):
# The command has completed normally. If force_disconnect is set, then
# tell the slave to shutdown
if self.force_disconnect:
if not callable(self.force_disconnect) or self.force_disconnect(cmd):
try:
d = self.remote.callRemote('shutdown')
d.addErrback(self._disconnected_cb)
d.addCallback(self._disconnected_cb)
return d
except:
log.err()
return
# Otherwise, cancel our execution
if self._deferred_death and self._deferred_death.active:
self._deferred_death.cancel()
self._deferred_death = None
def _disconnected_cb(self, res):
# Successfully disconnected
self._disconnected = True
return True
def finished(self, res):
if self._disconnected:
self.step_status.setText(self.describe(True) + ["slave", "lost"])
self.step_status.setText2(['slave', 'lost'])
if self._deferred_death and self._deferred_death.active:
self._deferred_death.cancel()
self._deferred_death = None
return self.super_class.finished(self, res)
class RepackPartners(ShellCommand):
'''This step allows a regular ShellCommand to be optionally extended
based on provided properties. This is useful for tweaking the command
to be run based on, e.g., properties supplied by the user in the
force builds web interface.
'''
def __init__(self, **kwargs):
self.super_class = ShellCommand
self.super_class.__init__(self, **kwargs)
def start(self):
try:
properties = self.build.getProperties()
if 'partner' in properties:
partner = properties['partner']
self.command.extend(['-p', partner])
except:
# No partner was specified, so repacking all partners.
pass
self.super_class.start(self)
class FunctionalStep(BuildStep):
name = "functional_step"
def __init__(self, func, **kwargs):
self.func = func
BuildStep.__init__(self, **kwargs)
self.addFactoryArguments(func=func)
def start(self):
result = self.func(self, self.build)
return self.finished(result)
def setBuildIDProps(step, build):
"""Sets buildid and builduid properties.
On a rebuild we willl re-generate the builduid. Otherwise, we normally get
them from the scheduler.
If either of buildid or builduid doesn't exist, it will be created."""
if build.reason.startswith("The web-page 'rebuild'"):
# Override builduid since this is a manually triggered
# rebuild
build.setProperty("builduid", genBuildUID(), "setBuildProps")
# Make sure we have required properties
props = build.getProperties()
if "buildid" not in props:
build.setProperty("buildid", genBuildID(), "setBuildProps")
if "builduid" not in props:
build.setProperty("builduid", genBuildUID(), "setBuildProps")
return SUCCESS