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 subprocess import call, check_call, Popen, PIPE
8 import os, tarfile, sys, time
9 from optparse import OptionParser
11 from email.mime.text import MIMEText
13 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
14 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
18 os.putenv('CC', "ccache gcc")
21 "source3" : [ ("autogen", "./autogen.sh", "text/plain"),
22 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
23 ("make basics", "make basics", "text/plain"),
24 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
25 ("install", "make install", "text/plain"),
26 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
28 "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
29 ("make", "make -j", "text/plain"),
30 ("install", "make install", "text/plain"),
31 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
33 "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
34 ("make", "make -j", "text/plain"),
35 ("install", "make install", "text/plain"),
36 ("test", "make test", "text/plain") ],
38 "lib/tdb" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
39 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
40 ("make", "make -j", "text/plain"),
41 ("install", "make install", "text/plain"),
42 ("test", "make test", "text/plain") ],
44 "lib/talloc" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
45 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
46 ("make", "make -j", "text/plain"),
47 ("install", "make install", "text/plain"),
48 ("test", "make test", "text/plain"), ],
50 "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
51 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
52 ("make", "make -j", "text/plain"),
53 ("install", "make install", "text/plain"),
54 ("test", "make test", "text/plain"), ],
56 "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
57 ("make", "make -j", "text/plain"),
58 ("install", "make install", "text/plain"),
59 ("test", "make test", "text/plain"), ],
62 retry_task = [ ( "retry",
64 git remote add -t master master %s
68 git describe master/master > old_master.desc
70 git describe master/master > master.desc
71 diff old_master.desc master.desc
73 ''' % samba_master, "test/plain" ) ]
76 def run_cmd(cmd, dir=None, show=None, output=False, checkfail=True, shell=False):
78 show = options.verbose
80 print("Running: '%s' in '%s'" % (cmd, dir))
82 return Popen(cmd, stdout=PIPE, cwd=dir, shell=shell).communicate()[0]
84 return check_call(cmd, cwd=dir, shell=shell)
86 return call(cmd, cwd=dir, shell=shell)
89 class TreeStageBuilder(object):
90 """Handle building of a particular stage for a tree.
93 def __init__(self, tree, name, command, output_mime_type, fail_quickly=False):
96 self.command = command
97 self.output_mime_type = output_mime_type
98 self.fail_quickly = fail_quickly
102 if self.output_mime_type == "text/x-subunit":
103 if self.fail_quickly:
104 self.command += " | %s --fail-immediately" % (os.path.join(os.path.dirname(__file__), "selftest/filter-subunit"))
105 self.command += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
106 print '%s: [%s] Running %s' % (self.name, self.stage, self.command)
107 self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
108 stdout=self.tree.stdout, stderr=self.tree.stderr, stdin=self.tree.stdin)
111 self.status = self.proc.poll()
115 if self.proc is not None:
117 run_cmd(["killbysubdir", self.tree.sdir], checkfail=False)
119 # killbysubdir doesn't exist ?
121 self.proc.terminate()
126 class TreeBuilder(object):
127 '''handle build of one directory'''
129 def __init__(self, name, sequence, fail_quickly=False):
131 self.fail_quickly = fail_quickly
133 self.tag = self.name.replace('/', '_')
134 self.sequence = sequence
136 self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
137 self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
139 print("stdout for %s in %s" % (self.name, self.stdout_path))
140 print("stderr for %s in %s" % (self.name, self.stderr_path))
141 if os.path.exists(self.stdout_path):
142 os.unlink(self.stdout_path)
143 if os.path.exists(self.stderr_path):
144 os.unlink(self.stderr_path)
145 self.stdout = open(self.stdout_path, 'w')
146 self.stderr = open(self.stderr_path, 'w')
147 self.stdin = open(os.devnull, 'r')
148 self.sdir = "%s/%s" % (testbase, self.tag)
149 if name in ['pass', 'fail', 'retry']:
152 self.dir = os.path.join(self.sdir, self.name)
153 self.prefix = os.path.join(testbase, "prefix", self.tag)
154 run_cmd(["rm", "-rf", self.sdir])
155 cleanup_list.append(self.sdir)
156 cleanup_list.append(self.prefix)
157 os.makedirs(self.sdir)
158 run_cmd(["rm", "-rf", self.sdir])
159 run_cmd(["git", "clone", "--shared", gitroot, self.sdir])
162 def start_next(self):
163 if self.next == len(self.sequence):
164 print '%s: Completed OK' % self.name
167 (stage_name, cmd, output_mime_type) = self.sequence[self.next]
168 cmd = cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
169 self.stage = TreeStageBuilder(self, stage_name, cmd, output_mime_type, self.fail_quickly)
172 def remove_logs(self):
173 os.unlink(self.stdout_path)
174 os.unlink(self.stderr_path)
178 return self.stage.status
181 return self.stage.poll()
189 return (os.WIFSIGNALED(self.status) or os.WEXITSTATUS(self.status) != 0)
192 def failure_reason(self):
193 return "%s: [%s] failed '%s' with status %d" % (self.name, self.stage.name, self.stage.cmd, self.stage.status)
196 class BuildList(object):
197 '''handle build of multiple directories'''
199 def __init__(self, tasklist, tasknames):
202 self.tail_proc = None
204 if tasknames == ['pass']:
205 tasks = { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
206 if tasknames == ['fail']:
207 tasks = { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
211 b = TreeBuilder(n, tasks[n], not options.fail_slowly)
214 self.retry = TreeBuilder('retry', retry_task, not options.fail_slowly)
215 self.need_retry = False
218 if self.tail_proc is not None:
219 self.tail_proc.terminate()
220 self.tail_proc.wait()
221 self.tail_proc = None
222 if self.retry is not None:
223 self.retry.proc.terminate()
224 self.retry.proc.wait()
241 ret = self.retry.proc.poll()
243 self.need_retry = True
253 if options.retry and self.need_retry:
255 print("retry needed")
256 return (0, None, None, None, "retry")
261 return (b.status, b.name, b.stage, b.tag, b.failure_reason)
264 return (0, None, None, None, "All OK")
266 def tarlogs(self, fname):
267 tar = tarfile.open(fname, "w:gz")
269 tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
270 tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
271 tar.add("autobuild.log")
274 def remove_logs(self):
278 def start_tail(self):
279 cmd = "tail -f *.stdout *.stderr"
280 self.tail_proc = Popen(cmd, shell=True, cwd=gitroot)
284 if options.nocleanup:
286 print("Cleaning up ....")
287 for d in cleanup_list:
288 run_cmd(["rm", "-rf", d])
291 def find_git_root(p):
292 '''get to the top of the git repo'''
294 if os.path.isdir(os.path.join(p, ".git")):
296 p = os.path.abspath(os.path.join(p, '..'))
300 def daemonize(logfile):
302 if pid == 0: # Parent
305 if pid != 0: # Actual daemon
310 import resource # Resource usage information.
311 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
312 if maxfd == resource.RLIM_INFINITY:
313 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
314 for fd in range(0, maxfd):
319 os.open(logfile, os.O_RDWR | os.O_CREAT)
324 def rebase_tree(url):
325 print("Rebasing on %s" % url)
326 run_cmd(["git", "remote", "add", "-t", "master", "master", url], show=True, dir=test_master)
327 run_cmd(["git", "fetch", "master"], show=True, dir=test_master)
328 if options.fix_whitespace:
329 run_cmd(["git", "rebase", "--whitespace=fix", "master/master"], show=True, dir=test_master)
331 run_cmd(["git", "rebase", "master/master"], show=True, dir=test_master)
332 diff = run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"], dir=test_master, output=True)
334 print("No differences between HEAD and master/master - exiting")
338 print("Pushing to %s" % url)
340 run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD", dir=test_master, shell=True)
341 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
342 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
343 run_cmd(["git", "remote", "add", "-t", "master", "pushto", url], show=True, dir=test_master)
344 run_cmd(["git", "push", "pushto", "+HEAD:master"], show=True, dir=test_master)
346 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
348 parser = OptionParser()
349 parser.add_option("", "--repository", help="repository to run tests for", default=None, type=str)
350 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
351 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
352 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
353 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
354 default=def_testbase)
355 parser.add_option("", "--passcmd", help="command to run on success", default=None)
356 parser.add_option("", "--verbose", help="show all commands as they are run",
357 default=False, action="store_true")
358 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
359 default=None, type='str')
360 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
361 default=False, action='store_true')
362 parser.add_option("", "--pushto", help="push to a git url on success",
363 default=None, type='str')
364 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
365 default=False, action='store_true')
366 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
367 default=False, action="store_true")
368 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
369 default=False, action="store_true")
370 parser.add_option("", "--retry", help="automatically retry if master changes",
371 default=False, action="store_true")
372 parser.add_option("", "--email", help="send email to the given address on failure",
373 type='str', default=None)
374 parser.add_option("", "--always-email", help="always send email, even on success",
376 parser.add_option("", "--daemon", help="daemonize after initial setup",
378 parser.add_option("", "--fail-slowly", help="continue running tests even after one has already failed",
382 def email_failure(status, failed_task, failed_stage, failed_tag, errstr):
383 '''send an email to options.email about the failure'''
384 user = os.getenv("USER")
388 Your autobuild failed when trying to test %s with the following error:
391 the autobuild has been abandoned. Please fix the error and resubmit.
393 You can see logs of the failed task here:
395 http://git.samba.org/%s/samba-autobuild/%s.stdout
396 http://git.samba.org/%s/samba-autobuild/%s.stderr
398 A summary of the autobuild process is here:
400 http://git.samba.org/%s/samba-autobuild/autobuild.log
402 or you can get full logs of all tasks in this job here:
404 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
406 The top commit for the tree that was built was:
410 ''' % (failed_task, errstr, user, failed_tag, user, failed_tag, user, user, top_commit_msg)
412 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
413 msg['From'] = 'autobuild@samba.org'
414 msg['To'] = options.email
418 s.sendmail(msg['From'], [msg['To']], msg.as_string())
422 '''send an email to options.email about a successful build'''
423 user = os.getenv("USER")
427 Your autobuild has succeeded.
434 you can get full logs of all tasks in this job here:
436 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
441 The top commit for the tree that was built was:
447 msg['Subject'] = 'autobuild success'
448 msg['From'] = 'autobuild@samba.org'
449 msg['To'] = options.email
453 s.sendmail(msg['From'], [msg['To']], msg.as_string())
457 (options, args) = parser.parse_args()
460 if not options.rebase_master and options.rebase is None:
461 raise Exception('You can only use --retry if you also rebase')
463 testbase = "%s/b%u" % (options.testbase, os.getpid())
464 test_master = os.path.join(testbase, "master")
466 if options.repository is not None:
467 repository = options.repository
469 repository = os.getcwd()
471 gitroot = find_git_root(repository)
473 raise Exception("Failed to find git root under %s" % repository)
475 # get the top commit message, for emails
476 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
479 os.makedirs(testbase)
480 except Exception, reason:
481 raise Exception("Unable to create %s : %s" % (testbase, reason))
482 cleanup_list.append(testbase)
485 logfile = os.path.join(testbase, "log")
486 print "Forking into the background, writing progress to %s" % logfile
491 run_cmd(["rm", "-rf", test_master])
492 cleanup_list.append(test_master)
493 run_cmd(["git", "clone", "--shared", gitroot, test_master])
499 if options.rebase is not None:
500 rebase_tree(options.rebase)
501 elif options.rebase_master:
502 rebase_tree(samba_master)
503 blist = BuildList(tasks, args)
506 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
507 if status != 0 or errstr != "retry":
516 print("waiting for tail to flush")
521 if options.passcmd is not None:
522 print("Running passcmd: %s" % options.passcmd)
523 run_cmd(options.passcmd, dir=test_master, shell=True)
524 if options.pushto is not None:
525 push_to(options.pushto)
526 elif options.push_master:
527 push_to(samba_master_ssh)
529 blist.tarlogs("logs.tar.gz")
530 print("Logs in logs.tar.gz")
531 if options.always_email:
537 # something failed, gather a tar of the logs
538 blist.tarlogs("logs.tar.gz")
540 if options.email is not None:
541 email_failure(status, failed_task, failed_stage, failed_tag, errstr)
545 print("Logs in logs.tar.gz")