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, dir=test_master)
452 run_cmd(["git", "fetch", "master"], show=True, dir=test_master)
453 if options.fix_whitespace:
454 run_cmd(["git", "rebase", "--whitespace=fix", "master/master"], show=True, dir=test_master)
456 run_cmd(["git", "rebase", "master/master"], show=True, dir=test_master)
457 diff = run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"], dir=test_master, output=True)
459 print("No differences between HEAD and master/master - exiting")
463 print("Pushing to %s" % url)
465 run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD", dir=test_master, shell=True)
466 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
467 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
468 run_cmd(["git", "remote", "add", "-t", "master", "pushto", url], show=True, dir=test_master)
469 run_cmd(["git", "push", "pushto", "+HEAD:master"], show=True, dir=test_master)
471 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
473 parser = OptionParser()
474 parser.add_option("", "--repository", help="repository to run tests for", default=None, type=str)
475 parser.add_option("", "--revision", help="revision to compile if not HEAD", default=None, type=str)
476 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
477 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
478 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
479 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
480 default=def_testbase)
481 parser.add_option("", "--passcmd", help="command to run on success", default=None)
482 parser.add_option("", "--verbose", help="show all commands as they are run",
483 default=False, action="store_true")
484 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
485 default=None, type='str')
486 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
487 default=False, action='store_true')
488 parser.add_option("", "--pushto", help="push to a git url on success",
489 default=None, type='str')
490 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
491 default=False, action='store_true')
492 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
493 default=False, action="store_true")
494 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
495 default=False, action="store_true")
496 parser.add_option("", "--retry", help="automatically retry if master changes",
497 default=False, action="store_true")
498 parser.add_option("", "--email", help="send email to the given address on failure",
499 type='str', default=None)
500 parser.add_option("", "--always-email", help="always send email, even on success",
502 parser.add_option("", "--daemon", help="daemonize after initial setup",
504 parser.add_option("", "--fail-slowly", help="continue running tests even after one has already failed",
508 def email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr):
509 '''send an email to options.email about the failure'''
510 user = os.getenv("USER")
514 Your autobuild failed when trying to test %s with the following error:
517 the autobuild has been abandoned. Please fix the error and resubmit.
519 You can see logs of the failed task here:
521 http://git.samba.org/%s/samba-autobuild/%s.stdout
522 http://git.samba.org/%s/samba-autobuild/%s.stderr
524 A summary of the autobuild process is here:
526 http://git.samba.org/%s/samba-autobuild/autobuild.log
528 or you can get full logs of all tasks in this job here:
530 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
532 The top commit for the tree that was built was:
536 ''' % (failed_task, errstr, user, failed_tag, user, failed_tag, user, user,
537 get_top_commit_msg(test_master))
539 msg = MIMEMultipart()
540 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
541 msg['From'] = 'autobuild@samba.org'
542 msg['To'] = options.email
544 main = MIMEText(text)
547 blist.attach_logs(msg)
551 s.sendmail(msg['From'], [msg['To']], msg.as_string())
554 def email_success(blist):
555 '''send an email to options.email about a successful build'''
556 user = os.getenv("USER")
560 Your autobuild has succeeded.
567 you can get full logs of all tasks in this job here:
569 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
574 The top commit for the tree that was built was:
577 ''' % (get_top_commit_msg(test_master),)
579 msg = MIMEMultipart()
580 msg['Subject'] = 'autobuild success'
581 msg['From'] = 'autobuild@samba.org'
582 msg['To'] = options.email
584 main = MIMEText(text, 'plain')
587 blist.attach_logs(msg)
591 s.sendmail(msg['From'], [msg['To']], msg.as_string())
595 (options, args) = parser.parse_args()
598 if not options.rebase_master and options.rebase is None:
599 raise Exception('You can only use --retry if you also rebase')
601 testbase = os.path.join(options.testbase, "b%u" % (os.getpid(),))
602 test_master = os.path.join(testbase, "master")
604 if options.repository is not None:
605 repository = options.repository
607 repository = os.getcwd()
609 gitroot = find_git_root(repository)
611 raise Exception("Failed to find git root under %s" % repository)
613 # get the top commit message, for emails
614 if options.revision is not None:
615 revision = options.revision
619 def get_top_commit_msg(reporoot):
620 return run_cmd(["git", "log", "-1"], dir=reporoot, output=True)
623 os.makedirs(testbase)
624 except Exception, reason:
625 raise Exception("Unable to create %s : %s" % (testbase, reason))
626 cleanup_list.append(testbase)
629 logfile = os.path.join(testbase, "log")
630 print "Forking into the background, writing progress to %s" % logfile
635 run_cmd(["rm", "-rf", test_master])
636 cleanup_list.append(test_master)
637 clone_gitroot(test_master, revision)
643 if options.rebase is not None:
644 rebase_tree(options.rebase)
645 elif options.rebase_master:
646 rebase_tree(samba_master)
647 blist = BuildList(tasks, args)
650 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
651 if status != 0 or errstr != "retry":
660 print("waiting for tail to flush")
665 if options.passcmd is not None:
666 print("Running passcmd: %s" % options.passcmd)
667 run_cmd(options.passcmd, dir=test_master, shell=True)
668 if options.pushto is not None:
669 push_to(options.pushto)
670 elif options.push_master:
671 push_to(samba_master_ssh)
673 blist.tarlogs("logs.tar.gz")
674 print("Logs in logs.tar.gz")
675 if options.always_email:
681 # something failed, gather a tar of the logs
682 blist.tarlogs("logs.tar.gz")
684 if options.email is not None:
685 email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr)
689 print("Logs in logs.tar.gz")