2 # run tests on all Samba subprojects and push to a git tree on success
3 # Copyright Andrew Tridgell 2010
4 # Copyright Jelmer Vernooij 2010
5 # released under GNU GPL v3 or later
7 from cStringIO import StringIO
9 from subprocess import call, check_call, Popen, PIPE
10 import os, tarfile, sys, time
11 from optparse import OptionParser
13 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../selftest"))
14 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../lib/testtools"))
15 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../lib/subunit/python"))
19 from email.mime.application import MIMEApplication
20 from email.mime.text import MIMEText
21 from email.mime.multipart import MIMEMultipart
23 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
24 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
28 os.putenv('CC', "ccache gcc")
31 "source3" : [ ("autogen", "./autogen.sh", "text/plain"),
32 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
33 ("make basics", "make basics", "text/plain"),
34 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
35 ("install", "make install", "text/plain"),
36 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
38 "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
39 ("make", "make -j", "text/plain"),
40 ("install", "make install", "text/plain"),
41 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
43 "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
44 ("make", "make -j", "text/plain"),
45 ("install", "make install", "text/plain"),
46 ("test", "make test", "text/plain") ],
48 "lib/tdb" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
49 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
50 ("make", "make -j", "text/plain"),
51 ("install", "make install", "text/plain"),
52 ("test", "make test", "text/plain") ],
54 "lib/talloc" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
55 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
56 ("make", "make -j", "text/plain"),
57 ("install", "make install", "text/plain"),
58 ("test", "make test", "text/x-subunit"), ],
60 "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
61 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
62 ("make", "make -j", "text/plain"),
63 ("install", "make install", "text/plain"),
64 ("test", "make test", "text/plain"), ],
66 "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
67 ("make", "make -j", "text/plain"),
68 ("install", "make install", "text/plain"),
69 ("test", "make test", "text/plain"), ],
73 def run_cmd(cmd, dir=None, show=None, output=False, checkfail=True, shell=False):
75 show = options.verbose
77 print("Running: '%s' in '%s'" % (cmd, dir))
79 return Popen(cmd, stdout=PIPE, cwd=dir, shell=shell).communicate()[0]
81 return check_call(cmd, cwd=dir, shell=shell)
83 return call(cmd, cwd=dir, shell=shell)
86 def clone_gitroot(test_master, revision="HEAD"):
87 run_cmd(["git", "clone", "--shared", gitroot, test_master])
88 if revision != "HEAD":
89 run_cmd(["git", "checkout", revision])
92 class RetryChecker(object):
93 """Check whether it is necessary to retry."""
95 def __init__(self, dir):
96 run_cmd(["git", "remote", "add", "-t", "master", "master", samba_master])
97 run_cmd(["git", "fetch", "master"])
101 git describe master/master > old_master.desc
103 git describe master/master > master.desc
104 diff old_master.desc master.desc
107 self.proc = Popen(cmd, shell=True, cwd=self.dir)
110 return self.proc.poll()
113 self.proc.terminate()
115 self.retry.proc = None
118 class TreeStageBuilder(object):
119 """Handle building of a particular stage for a tree.
122 def __init__(self, tree, name, command, fail_quickly=False):
125 self.command = command
126 self.fail_quickly = fail_quickly
128 self.stdin = open(os.devnull, 'r')
131 raise NotImplementedError(self.start)
134 self.status = self.proc.poll()
138 if self.proc is not None:
140 run_cmd(["killbysubdir", self.tree.sdir], checkfail=False)
142 # killbysubdir doesn't exist ?
144 self.proc.terminate()
149 def failure_reason(self):
150 return "failed '%s' with status %d" % (self.cmd, self.status)
154 return (os.WIFSIGNALED(self.status) or os.WEXITSTATUS(self.status) != 0)
157 class PlainTreeStageBuilder(TreeStageBuilder):
160 print '%s: [%s] Running %s' % (self.name, self.name, self.command)
161 self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
162 stdout=self.tree.stdout, stderr=self.tree.stderr,
166 class AbortingTestResult(subunithelper.TestsuiteEnabledTestResult):
168 def __init__(self, stage):
169 super(AbortingTestResult, self).__init__()
172 def addError(self, test, details=None):
173 self.stage.proc.terminate()
175 def addFailure(self, test, details=None):
176 self.stage.proc.terminate()
179 class SubunitTreeStageBuilder(TreeStageBuilder):
181 def __init__(self, tree, name, command, fail_quickly=False):
182 super(SubunitTreeStageBuilder, self).__init__(tree, name, command,
184 self.failed_tests = []
185 self.subunit_path = os.path.join(gitroot,
186 "%s.%s.subunit" % (self.tree.tag, self.name))
187 self.tree.logfiles.append(
188 (self.subunit_path, os.path.basename(self.subunit_path),
190 self.subunit = open(self.subunit_path, 'w')
192 formatter = subunithelper.PlainFormatter(False, True, {})
193 clients = [formatter, subunit.TestProtocolClient(self.subunit)]
195 clients.append(AbortingTestResult(self))
196 self.subunit_server = subunit.TestProtocolServer(
197 testtools.MultiTestResult(*clients),
202 print '%s: [%s] Running' % (self.tree.name, self.name)
203 self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
204 stdout=PIPE, stderr=self.tree.stderr, stdin=self.stdin)
205 fd = self.proc.stdout.fileno()
206 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
207 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
211 data = self.proc.stdout.read()
215 self.buffered += data
217 for l in self.buffered.splitlines(True):
219 self.subunit_server.lineReceived(l)
222 self.buffered = buffered
223 self.status = self.proc.poll()
224 if self.status is not None:
229 class TreeBuilder(object):
230 '''handle build of one directory'''
232 def __init__(self, name, sequence, fail_quickly=False):
234 self.fail_quickly = fail_quickly
236 self.tag = self.name.replace('/', '_')
237 self.sequence = sequence
239 self.stdout_path = os.path.join(gitroot, "%s.stdout" % (self.tag, ))
240 self.stderr_path = os.path.join(gitroot, "%s.stderr" % (self.tag, ))
242 (self.stdout_path, os.path.basename(self.stdout_path), "text/plain"),
243 (self.stderr_path, os.path.basename(self.stderr_path), "text/plain"),
246 print("stdout for %s in %s" % (self.name, self.stdout_path))
247 print("stderr for %s in %s" % (self.name, self.stderr_path))
248 if os.path.exists(self.stdout_path):
249 os.unlink(self.stdout_path)
250 if os.path.exists(self.stderr_path):
251 os.unlink(self.stderr_path)
252 self.stdout = open(self.stdout_path, 'w')
253 self.stderr = open(self.stderr_path, 'w')
254 self.sdir = os.path.join(testbase, self.tag)
255 if name in ['pass', 'fail', 'retry']:
258 self.dir = os.path.join(self.sdir, self.name)
259 self.prefix = os.path.join(testbase, "prefix", self.tag)
260 run_cmd(["rm", "-rf", self.sdir])
261 cleanup_list.append(self.sdir)
262 cleanup_list.append(self.prefix)
263 os.makedirs(self.sdir)
264 run_cmd(["rm", "-rf", self.sdir])
265 clone_gitroot(self.sdir, revision)
268 def start_next(self):
269 if self.next == len(self.sequence):
270 print '%s: Completed OK' % self.name
275 (stage_name, cmd, output_mime_type) = self.sequence[self.next]
276 cmd = cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
277 if output_mime_type == "text/plain":
278 self.stage = PlainTreeStageBuilder(self, stage_name, cmd,
280 elif output_mime_type == "text/x-subunit":
281 self.stage = SubunitTreeStageBuilder(self, stage_name, cmd,
284 raise Exception("Unknown output mime type %s" % output_mime_type)
288 def remove_logs(self):
289 for path, name, mime_type in self.logfiles:
294 return self.stage.status
297 return self.stage.poll()
300 if self.stage is not None:
306 if self.stage is None:
308 return self.stage.failed
311 def failure_reason(self):
312 return "%s: [%s] %s" % (self.name, self.stage.name,
313 self.stage.failure_reason)
316 class BuildList(object):
317 '''handle build of multiple directories'''
319 def __init__(self, tasklist, tasknames):
322 self.tail_proc = None
324 if tasknames == ['pass']:
325 tasks = { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
326 if tasknames == ['fail']:
327 tasks = { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
331 b = TreeBuilder(n, tasks[n], not options.fail_slowly)
334 self.retry = RetryChecker(self.sdir)
335 self.need_retry = False
338 if self.tail_proc is not None:
339 self.tail_proc.terminate()
340 self.tail_proc.wait()
341 self.tail_proc = None
342 if self.retry is not None:
359 ret = self.retry.poll()
361 self.need_retry = True
371 if options.retry and self.need_retry:
373 print("retry needed")
374 return (0, None, None, None, "retry")
379 return (b.status, b.name, b.stage, b.tag, b.failure_reason)
382 return (0, None, None, None, "All OK")
384 def tarlogs(self, name=None, fileobj=None):
385 tar = tarfile.open(name=name, fileobj=fileobj, mode="w:gz")
387 for (path, name, mime_type) in b.logfiles:
388 tar.add(path, arcname=name)
389 if os.path.exists("autobuild.log"):
390 tar.add("autobuild.log")
393 def attach_logs(self, outer):
395 self.tarlogs(fileobj=f)
396 msg = MIMEApplication(f.getvalue(), "x-gzip")
397 msg.add_header('Content-Disposition', 'attachment',
398 filename="logs.tar.gz")
401 def remove_logs(self):
405 def start_tail(self):
406 cmd = "tail -f *.stdout *.stderr"
407 self.tail_proc = Popen(cmd, shell=True, cwd=gitroot)
411 if options.nocleanup:
413 print("Cleaning up ....")
414 for d in cleanup_list:
415 run_cmd(["rm", "-rf", d])
418 def find_git_root(p):
419 '''get to the top of the git repo'''
421 if os.path.isdir(os.path.join(p, ".git")):
423 p = os.path.abspath(os.path.join(p, '..'))
427 def daemonize(logfile):
429 if pid == 0: # Parent
432 if pid != 0: # Actual daemon
437 import resource # Resource usage information.
438 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
439 if maxfd == resource.RLIM_INFINITY:
440 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
441 for fd in range(0, maxfd):
446 os.open(logfile, os.O_RDWR | os.O_CREAT)
451 def rebase_tree(url):
452 print("Rebasing on %s" % url)
453 run_cmd(["git", "remote", "add", "-t", "master", "master", url], show=True,
455 run_cmd(["git", "fetch", "master"], show=True, dir=test_master)
456 if options.fix_whitespace:
457 run_cmd(["git", "rebase", "--whitespace=fix", "master/master"],
458 show=True, dir=test_master)
460 run_cmd(["git", "rebase", "master/master"], show=True, dir=test_master)
461 diff = run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"],
462 dir=test_master, output=True)
464 print("No differences between HEAD and master/master - exiting")
468 print("Pushing to %s" % url)
470 run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD",
471 dir=test_master, shell=True)
472 # the notes method doesn't work yet, as metze hasn't allowed
473 # refs/notes/* in master
474 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD",
476 run_cmd(["git", "remote", "add", "-t", "master", "pushto", url], show=True,
478 run_cmd(["git", "push", "pushto", "+HEAD:master"], show=True,
481 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
483 parser = OptionParser()
484 parser.add_option("--repository", help="repository to run tests for", default=None, type=str)
485 parser.add_option("--revision", help="revision to compile if not HEAD", default=None, type=str)
486 parser.add_option("--tail", help="show output while running", default=False, action="store_true")
487 parser.add_option("--keeplogs", help="keep logs", default=False, action="store_true")
488 parser.add_option("--nocleanup", help="don't remove test tree", default=False, action="store_true")
489 parser.add_option("--testbase", help="base directory to run tests in (default %s)" % def_testbase,
490 default=def_testbase)
491 parser.add_option("--passcmd", help="command to run on success", default=None)
492 parser.add_option("--verbose", help="show all commands as they are run",
493 default=False, action="store_true")
494 parser.add_option("--rebase", help="rebase on the given tree before testing",
495 default=None, type='str')
496 parser.add_option("--rebase-master", help="rebase on %s before testing" % samba_master,
497 default=False, action='store_true')
498 parser.add_option("--pushto", help="push to a git url on success",
499 default=None, type='str')
500 parser.add_option("--push-master", help="push to %s on success" % samba_master_ssh,
501 default=False, action='store_true')
502 parser.add_option("--mark", help="add a Tested-By signoff before pushing",
503 default=False, action="store_true")
504 parser.add_option("--fix-whitespace", help="fix whitespace on rebase",
505 default=False, action="store_true")
506 parser.add_option("--retry", help="automatically retry if master changes",
507 default=False, action="store_true")
508 parser.add_option("--email", help="send email to the given address on failure",
509 type='str', default=None)
510 parser.add_option("--always-email", help="always send email, even on success",
512 parser.add_option("--daemon", help="daemonize after initial setup",
514 parser.add_option("--fail-slowly", help="continue running tests even after one has already failed",
518 def email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr):
519 '''send an email to options.email about the failure'''
520 user = os.getenv("USER")
524 Your autobuild failed when trying to test %s with the following error:
527 the autobuild has been abandoned. Please fix the error and resubmit.
529 You can see logs of the failed task here:
531 http://git.samba.org/%s/samba-autobuild/%s.stdout
532 http://git.samba.org/%s/samba-autobuild/%s.stderr
534 A summary of the autobuild process is here:
536 http://git.samba.org/%s/samba-autobuild/autobuild.log
538 or you can get full logs of all tasks in this job here:
540 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
542 The top commit for the tree that was built was:
546 ''' % (failed_task, errstr, user, failed_tag, user, failed_tag, user, user,
547 get_top_commit_msg(test_master))
549 msg = MIMEMultipart()
550 msg['Subject'] = 'autobuild failure for task %s during %s' % (
551 failed_task, failed_stage)
552 msg['From'] = 'autobuild@samba.org'
553 msg['To'] = options.email
555 main = MIMEText(text)
558 blist.attach_logs(msg)
562 s.sendmail(msg['From'], [msg['To']], msg.as_string())
565 def email_success(blist):
566 '''send an email to options.email about a successful build'''
567 user = os.getenv("USER")
571 Your autobuild has succeeded.
578 you can get full logs of all tasks in this job here:
580 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
585 The top commit for the tree that was built was:
588 ''' % (get_top_commit_msg(test_master),)
590 msg = MIMEMultipart()
591 msg['Subject'] = 'autobuild success'
592 msg['From'] = 'autobuild@samba.org'
593 msg['To'] = options.email
595 main = MIMEText(text, 'plain')
598 blist.attach_logs(msg)
602 s.sendmail(msg['From'], [msg['To']], msg.as_string())
606 (options, args) = parser.parse_args()
609 if not options.rebase_master and options.rebase is None:
610 raise Exception('You can only use --retry if you also rebase')
612 testbase = os.path.join(options.testbase, "b%u" % (os.getpid(),))
613 test_master = os.path.join(testbase, "master")
615 if options.repository is not None:
616 repository = options.repository
618 repository = os.getcwd()
620 gitroot = find_git_root(repository)
622 raise Exception("Failed to find git root under %s" % repository)
624 # get the top commit message, for emails
625 if options.revision is not None:
626 revision = options.revision
630 def get_top_commit_msg(reporoot):
631 return run_cmd(["git", "log", "-1"], dir=reporoot, output=True)
634 os.makedirs(testbase)
635 except Exception, reason:
636 raise Exception("Unable to create %s : %s" % (testbase, reason))
637 cleanup_list.append(testbase)
640 logfile = os.path.join(testbase, "log")
641 print "Forking into the background, writing progress to %s" % logfile
646 run_cmd(["rm", "-rf", test_master])
647 cleanup_list.append(test_master)
648 clone_gitroot(test_master, revision)
654 if options.rebase is not None:
655 rebase_tree(options.rebase)
656 elif options.rebase_master:
657 rebase_tree(samba_master)
658 blist = BuildList(tasks, args)
661 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
662 if status != 0 or errstr != "retry":
671 print("waiting for tail to flush")
676 if options.passcmd is not None:
677 print("Running passcmd: %s" % options.passcmd)
678 run_cmd(options.passcmd, dir=test_master, shell=True)
679 if options.pushto is not None:
680 push_to(options.pushto)
681 elif options.push_master:
682 push_to(samba_master_ssh)
684 blist.tarlogs("logs.tar.gz")
685 print("Logs in logs.tar.gz")
686 if options.always_email:
692 # something failed, gather a tar of the logs
693 blist.tarlogs("logs.tar.gz")
695 if options.email is not None:
696 email_failure(blist, status, failed_task, failed_stage, failed_tag,
701 print("Logs in logs.tar.gz")