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
8 from subprocess import call, check_call, Popen, PIPE
9 import os, tarfile, sys, time
10 from optparse import OptionParser
12 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../selftest"))
13 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../lib/testtools"))
14 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../lib/subunit/python"))
18 from email.mime.text import MIMEText
19 from email.mime.multipart import MIMEMultipart
21 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
22 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
26 os.putenv('CC', "ccache gcc")
29 "source3" : [ ("autogen", "./autogen.sh", "text/plain"),
30 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
31 ("make basics", "make basics", "text/plain"),
32 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
33 ("install", "make install", "text/plain"),
34 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
36 "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
37 ("make", "make -j", "text/plain"),
38 ("install", "make install", "text/plain"),
39 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
41 "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
42 ("make", "make -j", "text/plain"),
43 ("install", "make install", "text/plain"),
44 ("test", "make test", "text/plain") ],
46 "lib/tdb" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
47 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
48 ("make", "make -j", "text/plain"),
49 ("install", "make install", "text/plain"),
50 ("test", "make test", "text/plain") ],
52 "lib/talloc" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
53 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
54 ("make", "make -j", "text/plain"),
55 ("install", "make install", "text/plain"),
56 ("test", "make test", "text/x-subunit"), ],
58 "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
59 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
60 ("make", "make -j", "text/plain"),
61 ("install", "make install", "text/plain"),
62 ("test", "make test", "text/plain"), ],
64 "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
65 ("make", "make -j", "text/plain"),
66 ("install", "make install", "text/plain"),
67 ("test", "make test", "text/plain"), ],
70 retry_task = [ ( "retry",
72 git remote add -t master master %s
76 git describe master/master > old_master.desc
78 git describe master/master > master.desc
79 diff old_master.desc master.desc
81 ''' % samba_master, "test/plain" ) ]
84 def run_cmd(cmd, dir=None, show=None, output=False, checkfail=True, shell=False):
86 show = options.verbose
88 print("Running: '%s' in '%s'" % (cmd, dir))
90 return Popen(cmd, stdout=PIPE, cwd=dir, shell=shell).communicate()[0]
92 return check_call(cmd, cwd=dir, shell=shell)
94 return call(cmd, cwd=dir, shell=shell)
97 def clone_gitroot(test_master, revision="HEAD"):
98 run_cmd(["git", "clone", "--shared", gitroot, test_master])
99 if revision != "HEAD":
100 run_cmd(["git", "checkout", revision])
103 class TreeStageBuilder(object):
104 """Handle building of a particular stage for a tree.
107 def __init__(self, tree, name, command, fail_quickly=False):
110 self.command = command
111 self.fail_quickly = fail_quickly
113 self.stdin = open(os.devnull, 'r')
116 raise NotImplementedError(self.start)
119 self.status = self.proc.poll()
123 if self.proc is not None:
125 run_cmd(["killbysubdir", self.tree.sdir], checkfail=False)
127 # killbysubdir doesn't exist ?
129 self.proc.terminate()
134 def failure_reason(self):
135 return "failed '%s' with status %d" % (self.cmd, self.status)
139 return (os.WIFSIGNALED(self.status) or os.WEXITSTATUS(self.status) != 0)
142 class PlainTreeStageBuilder(TreeStageBuilder):
145 print '%s: [%s] Running %s' % (self.name, self.name, self.command)
146 self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
147 stdout=self.tree.stdout, stderr=self.tree.stderr,
151 class AbortingTestResult(subunithelper.TestsuiteEnabledTestResult):
153 def __init__(self, stage):
154 super(AbortingTestResult, self).__init__()
157 def addError(self, test, details=None):
158 self.stage.proc.terminate()
160 def addFailure(self, test, details=None):
161 self.stage.proc.terminate()
164 class SubunitTreeStageBuilder(TreeStageBuilder):
166 def __init__(self, tree, name, command, fail_quickly=False):
167 super(SubunitTreeStageBuilder, self).__init__(tree, name, command,
169 self.failed_tests = []
170 self.subunit_path = os.path.join(gitroot,
171 "%s.%s.subunit" % (self.tree.tag, self.name))
172 self.tree.logfiles.append(
173 (self.subunit_path, os.path.basename(self.subunit_path),
175 self.subunit = open(self.subunit_path, 'w')
177 formatter = subunithelper.PlainFormatter(False, True, {})
178 clients = [formatter, subunit.TestProtocolClient(self.subunit)]
180 clients.append(AbortingTestResult(self))
181 self.subunit_server = subunit.TestProtocolServer(
182 testtools.MultiTestResult(*clients),
187 print '%s: [%s] Running' % (self.tree.name, self.name)
188 self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
189 stdout=PIPE, stderr=self.tree.stderr, stdin=self.stdin)
190 fd = self.proc.stdout.fileno()
191 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
192 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
196 data = self.proc.stdout.read()
200 self.tree.stdout.write(data)
201 self.buffered += data
203 for l in self.buffered.splitlines(True):
205 self.subunit_server.lineReceived(l)
208 self.buffered = buffered
209 self.status = self.proc.poll()
210 if self.status is not None:
215 class TreeBuilder(object):
216 '''handle build of one directory'''
218 def __init__(self, name, sequence, fail_quickly=False):
220 self.fail_quickly = fail_quickly
222 self.tag = self.name.replace('/', '_')
223 self.sequence = sequence
225 self.stdout_path = os.path.join(gitroot, "%s.stdout" % (self.tag, ))
226 self.stderr_path = os.path.join(gitroot, "%s.stderr" % (self.tag, ))
228 (self.stdout_path, os.path.basename(self.stdout_path), "text/plain"),
229 (self.stderr_path, os.path.basename(self.stderr_path), "text/plain"),
232 print("stdout for %s in %s" % (self.name, self.stdout_path))
233 print("stderr for %s in %s" % (self.name, self.stderr_path))
234 if os.path.exists(self.stdout_path):
235 os.unlink(self.stdout_path)
236 if os.path.exists(self.stderr_path):
237 os.unlink(self.stderr_path)
238 self.stdout = open(self.stdout_path, 'w')
239 self.stderr = open(self.stderr_path, 'w')
240 self.sdir = os.path.join(testbase, self.tag)
241 if name in ['pass', 'fail', 'retry']:
244 self.dir = os.path.join(self.sdir, self.name)
245 self.prefix = os.path.join(testbase, "prefix", self.tag)
246 run_cmd(["rm", "-rf", self.sdir])
247 cleanup_list.append(self.sdir)
248 cleanup_list.append(self.prefix)
249 os.makedirs(self.sdir)
250 run_cmd(["rm", "-rf", self.sdir])
251 clone_gitroot(self.sdir, revision)
254 def start_next(self):
255 if self.next == len(self.sequence):
256 print '%s: Completed OK' % self.name
261 (stage_name, cmd, output_mime_type) = self.sequence[self.next]
262 cmd = cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
263 if output_mime_type == "text/plain":
264 self.stage = PlainTreeStageBuilder(self, stage_name, cmd,
266 elif output_mime_type == "text/x-subunit":
267 self.stage = SubunitTreeStageBuilder(self, stage_name, cmd,
270 raise Exception("Unknown output mime type %s" % output_mime_type)
274 def remove_logs(self):
275 for path, name, mime_type in self.logfiles:
278 def attach_logs(self, outer):
279 for path, name, mime_type in self.logfiles:
280 assert mime_type.startswith("text/")
284 msg = MIMEText(f.read(), mime_type[len("text/"):])
287 msg.add_header('Content-Disposition', 'attachment',
293 return self.stage.status
296 return self.stage.poll()
299 if self.stage is not None:
305 if self.stage is None:
307 return self.stage.failed
310 def failure_reason(self):
311 return "%s: [%s] %s" % (self.name, self.stage.name,
312 self.stage.failure_reason)
315 class BuildList(object):
316 '''handle build of multiple directories'''
318 def __init__(self, tasklist, tasknames):
321 self.tail_proc = None
323 if tasknames == ['pass']:
324 tasks = { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
325 if tasknames == ['fail']:
326 tasks = { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
330 b = TreeBuilder(n, tasks[n], not options.fail_slowly)
333 self.retry = TreeBuilder('retry', retry_task,
334 not options.fail_slowly)
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:
343 self.retry.proc.terminate()
344 self.retry.proc.wait()
361 ret = self.retry.proc.poll()
363 self.need_retry = True
373 if options.retry and self.need_retry:
375 print("retry needed")
376 return (0, None, None, None, "retry")
381 return (b.status, b.name, b.stage, b.tag, b.failure_reason)
384 return (0, None, None, None, "All OK")
386 def tarlogs(self, fname):
387 tar = tarfile.open(fname, "w:gz")
389 for (path, name, mime_type) in b.logfiles:
390 tar.add(path, arcname=name)
391 if os.path.exists("autobuild.log"):
392 tar.add("autobuild.log")
395 def attach_logs(self, msg):
399 def remove_logs(self):
403 def start_tail(self):
404 cmd = "tail -f *.stdout *.stderr"
405 self.tail_proc = Popen(cmd, shell=True, cwd=gitroot)
409 if options.nocleanup:
411 print("Cleaning up ....")
412 for d in cleanup_list:
413 run_cmd(["rm", "-rf", d])
416 def find_git_root(p):
417 '''get to the top of the git repo'''
419 if os.path.isdir(os.path.join(p, ".git")):
421 p = os.path.abspath(os.path.join(p, '..'))
425 def daemonize(logfile):
427 if pid == 0: # Parent
430 if pid != 0: # Actual daemon
435 import resource # Resource usage information.
436 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
437 if maxfd == resource.RLIM_INFINITY:
438 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
439 for fd in range(0, maxfd):
444 os.open(logfile, os.O_RDWR | os.O_CREAT)
449 def rebase_tree(url):
450 print("Rebasing on %s" % url)
451 run_cmd(["git", "remote", "add", "-t", "master", "master", url], show=True,
453 run_cmd(["git", "fetch", "master"], show=True, dir=test_master)
454 if options.fix_whitespace:
455 run_cmd(["git", "rebase", "--whitespace=fix", "master/master"],
456 show=True, dir=test_master)
458 run_cmd(["git", "rebase", "master/master"], show=True, dir=test_master)
459 diff = run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"],
460 dir=test_master, output=True)
462 print("No differences between HEAD and master/master - exiting")
466 print("Pushing to %s" % url)
468 run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD",
469 dir=test_master, shell=True)
470 # the notes method doesn't work yet, as metze hasn't allowed
471 # refs/notes/* in master
472 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD",
474 run_cmd(["git", "remote", "add", "-t", "master", "pushto", url], show=True,
476 run_cmd(["git", "push", "pushto", "+HEAD:master"], show=True,
479 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
481 parser = OptionParser()
482 parser.add_option("--repository", help="repository to run tests for", default=None, type=str)
483 parser.add_option("--revision", help="revision to compile if not HEAD", default=None, type=str)
484 parser.add_option("--tail", help="show output while running", default=False, action="store_true")
485 parser.add_option("--keeplogs", help="keep logs", default=False, action="store_true")
486 parser.add_option("--nocleanup", help="don't remove test tree", default=False, action="store_true")
487 parser.add_option("--testbase", help="base directory to run tests in (default %s)" % def_testbase,
488 default=def_testbase)
489 parser.add_option("--passcmd", help="command to run on success", default=None)
490 parser.add_option("--verbose", help="show all commands as they are run",
491 default=False, action="store_true")
492 parser.add_option("--rebase", help="rebase on the given tree before testing",
493 default=None, type='str')
494 parser.add_option("--rebase-master", help="rebase on %s before testing" % samba_master,
495 default=False, action='store_true')
496 parser.add_option("--pushto", help="push to a git url on success",
497 default=None, type='str')
498 parser.add_option("--push-master", help="push to %s on success" % samba_master_ssh,
499 default=False, action='store_true')
500 parser.add_option("--mark", help="add a Tested-By signoff before pushing",
501 default=False, action="store_true")
502 parser.add_option("--fix-whitespace", help="fix whitespace on rebase",
503 default=False, action="store_true")
504 parser.add_option("--retry", help="automatically retry if master changes",
505 default=False, action="store_true")
506 parser.add_option("--email", help="send email to the given address on failure",
507 type='str', default=None)
508 parser.add_option("--always-email", help="always send email, even on success",
510 parser.add_option("--daemon", help="daemonize after initial setup",
512 parser.add_option("--fail-slowly", help="continue running tests even after one has already failed",
516 def email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr):
517 '''send an email to options.email about the failure'''
518 user = os.getenv("USER")
522 Your autobuild failed when trying to test %s with the following error:
525 the autobuild has been abandoned. Please fix the error and resubmit.
527 You can see logs of the failed task here:
529 http://git.samba.org/%s/samba-autobuild/%s.stdout
530 http://git.samba.org/%s/samba-autobuild/%s.stderr
532 A summary of the autobuild process is here:
534 http://git.samba.org/%s/samba-autobuild/autobuild.log
536 or you can get full logs of all tasks in this job here:
538 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
540 The top commit for the tree that was built was:
544 ''' % (failed_task, errstr, user, failed_tag, user, failed_tag, user, user,
545 get_top_commit_msg(test_master))
547 msg = MIMEMultipart()
548 msg['Subject'] = 'autobuild failure for task %s during %s' % (
549 failed_task, failed_stage)
550 msg['From'] = 'autobuild@samba.org'
551 msg['To'] = options.email
553 main = MIMEText(text)
556 blist.attach_logs(msg)
560 s.sendmail(msg['From'], [msg['To']], msg.as_string())
563 def email_success(blist):
564 '''send an email to options.email about a successful build'''
565 user = os.getenv("USER")
569 Your autobuild has succeeded.
576 you can get full logs of all tasks in this job here:
578 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
583 The top commit for the tree that was built was:
586 ''' % (get_top_commit_msg(test_master),)
588 msg = MIMEMultipart()
589 msg['Subject'] = 'autobuild success'
590 msg['From'] = 'autobuild@samba.org'
591 msg['To'] = options.email
593 main = MIMEText(text, 'plain')
596 blist.attach_logs(msg)
600 s.sendmail(msg['From'], [msg['To']], msg.as_string())
604 (options, args) = parser.parse_args()
607 if not options.rebase_master and options.rebase is None:
608 raise Exception('You can only use --retry if you also rebase')
610 testbase = os.path.join(options.testbase, "b%u" % (os.getpid(),))
611 test_master = os.path.join(testbase, "master")
613 if options.repository is not None:
614 repository = options.repository
616 repository = os.getcwd()
618 gitroot = find_git_root(repository)
620 raise Exception("Failed to find git root under %s" % repository)
622 # get the top commit message, for emails
623 if options.revision is not None:
624 revision = options.revision
628 def get_top_commit_msg(reporoot):
629 return run_cmd(["git", "log", "-1"], dir=reporoot, output=True)
632 os.makedirs(testbase)
633 except Exception, reason:
634 raise Exception("Unable to create %s : %s" % (testbase, reason))
635 cleanup_list.append(testbase)
638 logfile = os.path.join(testbase, "log")
639 print "Forking into the background, writing progress to %s" % logfile
644 run_cmd(["rm", "-rf", test_master])
645 cleanup_list.append(test_master)
646 clone_gitroot(test_master, revision)
652 if options.rebase is not None:
653 rebase_tree(options.rebase)
654 elif options.rebase_master:
655 rebase_tree(samba_master)
656 blist = BuildList(tasks, args)
659 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
660 if status != 0 or errstr != "retry":
669 print("waiting for tail to flush")
674 if options.passcmd is not None:
675 print("Running passcmd: %s" % options.passcmd)
676 run_cmd(options.passcmd, dir=test_master, shell=True)
677 if options.pushto is not None:
678 push_to(options.pushto)
679 elif options.push_master:
680 push_to(samba_master_ssh)
682 blist.tarlogs("logs.tar.gz")
683 print("Logs in logs.tar.gz")
684 if options.always_email:
690 # something failed, gather a tar of the logs
691 blist.tarlogs("logs.tar.gz")
693 if options.email is not None:
694 email_failure(blist, status, failed_task, failed_stage, failed_tag,
699 print("Logs in logs.tar.gz")