autobuild: Remove s3-waf from autobuild
[Samba/gebeck_regimport.git] / script / autobuild.py
blob9945c66cb6d6934645ee0596e6e82c5a8fc83136
1 #!/usr/bin/env python
2 # run tests on all Samba subprojects and push to a git tree on success
3 # Copyright Andrew Tridgell 2010
4 # released under GNU GPL v3 or later
6 from subprocess import call, check_call,Popen, PIPE
7 import os, tarfile, sys, time
8 from optparse import OptionParser
9 import smtplib
10 from email.mime.text import MIMEText
12 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
13 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
15 cleanup_list = []
17 builddirs = {
18 "samba3" : "source3",
19 "samba4" : ".",
20 "ldb" : "lib/ldb",
21 "tdb" : "lib/tdb",
22 "talloc" : "lib/talloc",
23 "replace" : "lib/replace",
24 "tevent" : "lib/tevent",
25 "pidl" : "pidl",
26 "pass" : ".",
27 "fail" : ".",
28 "retry" : "."
31 defaulttasks = [ "samba3", "samba4", "ldb", "tdb", "talloc", "replace", "tevent", "pidl" ]
33 tasks = {
34 "samba3" : [ ("autogen", "./autogen.sh", "text/plain"),
35 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
36 ("make basics", "make basics", "text/plain"),
37 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
38 ("install", "make install", "text/plain"),
39 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
40 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
41 ("clean", "make clean", "text/plain") ],
43 # We have 'test' before 'install' because, 'test' should work without 'install'
44 "samba4" : [ ("configure", "./configure.developer ${PREFIX} --with-selftest-prefix=./bin/ab", "text/plain"),
45 ("make", "make -j", "text/plain"),
46 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
47 ("install", "make install", "text/plain"),
48 ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
49 ("clean", "make clean", "text/plain") ],
51 "ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
52 ("make", "make -j", "text/plain"),
53 ("install", "make install", "text/plain"),
54 ("test", "TDB_NO_FSYNC=1 make test", "text/plain"),
55 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
56 ("distcheck", "make distcheck", "text/plain"),
57 ("clean", "make clean", "text/plain") ],
59 # We don't use TDB_NO_FSYNC=1 here, because we want to test the transaction code
60 "tdb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
61 ("make", "make -j", "text/plain"),
62 ("install", "make install", "text/plain"),
63 ("test", "make test", "text/plain"),
64 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
65 ("distcheck", "make distcheck", "text/plain"),
66 ("clean", "make clean", "text/plain") ],
68 "talloc" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
69 ("make", "make -j", "text/plain"),
70 ("install", "make install", "text/plain"),
71 ("test", "make test", "text/plain"),
72 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
73 ("distcheck", "make distcheck", "text/plain"),
74 ("clean", "make clean", "text/plain") ],
76 "replace" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
77 ("make", "make -j", "text/plain"),
78 ("install", "make install", "text/plain"),
79 ("test", "make test", "text/plain"),
80 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
81 ("distcheck", "make distcheck", "text/plain"),
82 ("clean", "make clean", "text/plain") ],
84 "tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
85 ("make", "make -j", "text/plain"),
86 ("install", "make install", "text/plain"),
87 ("test", "make test", "text/plain"),
88 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
89 ("distcheck", "make distcheck", "text/plain"),
90 ("clean", "make clean", "text/plain") ],
92 "pidl" : [ ("configure", "perl Makefile.PL PREFIX=${PREFIX_DIR}", "text/plain"),
93 ("touch", "touch *.yp", "text/plain"),
94 ("make", "make", "text/plain"),
95 ("test", "make test", "text/plain"),
96 ("install", "make install", "text/plain"),
97 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
98 ("clean", "make clean", "text/plain") ],
100 # these are useful for debugging autobuild
101 'pass' : [ ("pass", 'echo passing && /bin/true', "text/plain") ],
102 'fail' : [ ("fail", 'echo failing && /bin/false', "text/plain") ]
105 retry_task = [ ( "retry",
106 '''set -e
107 git remote add -t master master %s
108 git fetch master
109 while :; do
110 sleep 60
111 git describe master/master > old_master.desc
112 git fetch master
113 git describe master/master > master.desc
114 diff old_master.desc master.desc
115 done
116 ''' % samba_master, "test/plain" ) ]
118 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
119 if show is None:
120 show = options.verbose
121 if show:
122 print("Running: '%s' in '%s'" % (cmd, dir))
123 if output:
124 return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
125 elif checkfail:
126 return check_call(cmd, shell=True, cwd=dir)
127 else:
128 return call(cmd, shell=True, cwd=dir)
131 class builder(object):
132 '''handle build of one directory'''
134 def __init__(self, name, sequence):
135 self.name = name
136 self.dir = builddirs[name]
138 self.tag = self.name.replace('/', '_')
139 self.sequence = sequence
140 self.next = 0
141 self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
142 self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
143 if options.verbose:
144 print("stdout for %s in %s" % (self.name, self.stdout_path))
145 print("stderr for %s in %s" % (self.name, self.stderr_path))
146 run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
147 self.stdout = open(self.stdout_path, 'w')
148 self.stderr = open(self.stderr_path, 'w')
149 self.stdin = open("/dev/null", 'r')
150 self.sdir = "%s/%s" % (testbase, self.tag)
151 self.prefix = "%s/prefix/%s" % (testbase, self.tag)
152 run_cmd("rm -rf %s" % self.sdir)
153 cleanup_list.append(self.sdir)
154 cleanup_list.append(self.prefix)
155 os.makedirs(self.sdir)
156 run_cmd("rm -rf %s" % self.sdir)
157 run_cmd("git clone --shared %s %s" % (test_master, self.sdir), dir=test_master, show=True)
158 self.start_next()
160 def start_next(self):
161 if self.next == len(self.sequence):
162 print '%s: Completed OK' % self.name
163 self.done = True
164 return
165 (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
166 self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
167 self.cmd = self.cmd.replace("${PREFIX_DIR}", "%s" % self.prefix)
168 # if self.output_mime_type == "text/x-subunit":
169 # self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
170 print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
171 cwd = os.getcwd()
172 os.chdir("%s/%s" % (self.sdir, self.dir))
173 self.proc = Popen(self.cmd, shell=True,
174 stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
175 os.chdir(cwd)
176 self.next += 1
179 class buildlist(object):
180 '''handle build of multiple directories'''
182 def __init__(self, tasklist, tasknames):
183 global tasks
184 self.tlist = []
185 self.tail_proc = None
186 self.retry = None
187 if tasknames == []:
188 tasknames = defaulttasks
189 for n in tasknames:
190 b = builder(n, tasks[n])
191 self.tlist.append(b)
192 if options.retry:
193 self.retry = builder('retry', retry_task)
194 self.need_retry = False
196 def kill_kids(self):
197 if self.tail_proc is not None:
198 self.tail_proc.terminate()
199 self.tail_proc.wait()
200 self.tail_proc = None
201 if self.retry is not None:
202 self.retry.proc.terminate()
203 self.retry.proc.wait()
204 self.retry = None
205 for b in self.tlist:
206 if b.proc is not None:
207 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
208 b.proc.terminate()
209 b.proc.wait()
210 b.proc = None
212 def wait_one(self):
213 while True:
214 none_running = True
215 for b in self.tlist:
216 if b.proc is None:
217 continue
218 none_running = False
219 b.status = b.proc.poll()
220 if b.status is None:
221 continue
222 b.proc = None
223 return b
224 if options.retry:
225 ret = self.retry.proc.poll()
226 if ret is not None:
227 self.need_retry = True
228 self.retry = None
229 return None
230 if none_running:
231 return None
232 time.sleep(0.1)
234 def run(self):
235 while True:
236 b = self.wait_one()
237 if options.retry and self.need_retry:
238 self.kill_kids()
239 print("retry needed")
240 return (0, None, None, None, "retry")
241 if b is None:
242 break
243 if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
244 self.kill_kids()
245 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
246 b.start_next()
247 self.kill_kids()
248 return (0, None, None, None, "All OK")
250 def tarlogs(self, fname):
251 tar = tarfile.open(fname, "w:gz")
252 for b in self.tlist:
253 tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
254 tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
255 if os.path.exists("autobuild.log"):
256 tar.add("autobuild.log")
257 tar.close()
259 def remove_logs(self):
260 for b in self.tlist:
261 os.unlink(b.stdout_path)
262 os.unlink(b.stderr_path)
264 def start_tail(self):
265 cwd = os.getcwd()
266 cmd = "tail -f *.stdout *.stderr"
267 os.chdir(gitroot)
268 self.tail_proc = Popen(cmd, shell=True)
269 os.chdir(cwd)
272 def cleanup():
273 if options.nocleanup:
274 return
275 print("Cleaning up ....")
276 for d in cleanup_list:
277 run_cmd("rm -rf %s" % d)
280 def find_git_root():
281 '''get to the top of the git repo'''
282 p=os.getcwd()
283 while p != '/':
284 if os.path.isdir(os.path.join(p, ".git")):
285 return p
286 p = os.path.abspath(os.path.join(p, '..'))
287 return None
290 def daemonize(logfile):
291 pid = os.fork()
292 if pid == 0: # Parent
293 os.setsid()
294 pid = os.fork()
295 if pid != 0: # Actual daemon
296 os._exit(0)
297 else: # Grandparent
298 os._exit(0)
300 import resource # Resource usage information.
301 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
302 if maxfd == resource.RLIM_INFINITY:
303 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
304 for fd in range(0, maxfd):
305 try:
306 os.close(fd)
307 except OSError:
308 pass
309 os.open(logfile, os.O_RDWR | os.O_CREAT)
310 os.dup2(0, 1)
311 os.dup2(0, 2)
313 def write_pidfile(fname):
314 '''write a pid file, cleanup on exit'''
315 f = open(fname, mode='w')
316 f.write("%u\n" % os.getpid())
317 f.close()
320 def rebase_tree(url):
321 print("Rebasing on %s" % url)
322 run_cmd("git describe HEAD", show=True, dir=test_master)
323 run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
324 run_cmd("git fetch master", show=True, dir=test_master)
325 if options.fix_whitespace:
326 run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
327 else:
328 run_cmd("git rebase master/master", show=True, dir=test_master)
329 diff = run_cmd("git --no-pager diff HEAD master/master", dir=test_master, output=True)
330 if diff == '':
331 print("No differences between HEAD and master/master - exiting")
332 sys.exit(0)
333 run_cmd("git describe master/master", show=True, dir=test_master)
334 run_cmd("git describe HEAD", show=True, dir=test_master)
335 run_cmd("git --no-pager diff --stat HEAD master/master", show=True, dir=test_master)
337 def push_to(url):
338 print("Pushing to %s" % url)
339 if options.mark:
340 run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
341 run_cmd("git commit --amend -c HEAD", dir=test_master)
342 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
343 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
344 run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
345 run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
347 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
349 parser = OptionParser()
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",
375 action="store_true")
376 parser.add_option("", "--daemon", help="daemonize after initial setup",
377 action="store_true")
380 def email_failure(status, failed_task, failed_stage, failed_tag, errstr):
381 '''send an email to options.email about the failure'''
382 user = os.getenv("USER")
383 text = '''
384 Dear Developer,
386 Your autobuild failed when trying to test %s with the following error:
389 the autobuild has been abandoned. Please fix the error and resubmit.
391 A summary of the autobuild process is here:
393 http://git.samba.org/%s/samba-autobuild/autobuild.log
394 ''' % (failed_task, errstr, user)
396 if failed_task != 'rebase':
397 text += '''
398 You can see logs of the failed task here:
400 http://git.samba.org/%s/samba-autobuild/%s.stdout
401 http://git.samba.org/%s/samba-autobuild/%s.stderr
403 or you can get full logs of all tasks in this job here:
405 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
407 The top commit for the tree that was built was:
411 ''' % (user, failed_tag, user, failed_tag, user, top_commit_msg)
412 msg = MIMEText(text)
413 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
414 msg['From'] = 'autobuild@samba.org'
415 msg['To'] = options.email
417 s = smtplib.SMTP()
418 s.connect()
419 s.sendmail(msg['From'], [msg['To']], msg.as_string())
420 s.quit()
422 def email_success():
423 '''send an email to options.email about a successful build'''
424 user = os.getenv("USER")
425 text = '''
426 Dear Developer,
428 Your autobuild has succeeded.
432 if options.keeplogs:
433 text += '''
435 you can get full logs of all tasks in this job here:
437 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
439 ''' % user
441 text += '''
442 The top commit for the tree that was built was:
445 ''' % top_commit_msg
447 msg = MIMEText(text)
448 msg['Subject'] = 'autobuild success'
449 msg['From'] = 'autobuild@samba.org'
450 msg['To'] = options.email
452 s = smtplib.SMTP()
453 s.connect()
454 s.sendmail(msg['From'], [msg['To']], msg.as_string())
455 s.quit()
458 (options, args) = parser.parse_args()
460 if options.retry:
461 if not options.rebase_master and options.rebase is None:
462 raise Exception('You can only use --retry if you also rebase')
464 testbase = "%s/b%u" % (options.testbase, os.getpid())
465 test_master = "%s/master" % testbase
467 gitroot = find_git_root()
468 if gitroot is None:
469 raise Exception("Failed to find git root")
471 # get the top commit message, for emails
472 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
474 try:
475 os.makedirs(testbase)
476 except Exception, reason:
477 raise Exception("Unable to create %s : %s" % (testbase, reason))
478 cleanup_list.append(testbase)
480 if options.daemon:
481 logfile = os.path.join(testbase, "log")
482 print "Forking into the background, writing progress to %s" % logfile
483 daemonize(logfile)
485 write_pidfile(gitroot + "/autobuild.pid")
487 while True:
488 try:
489 run_cmd("rm -rf %s" % test_master)
490 cleanup_list.append(test_master)
491 run_cmd("git clone --shared %s %s" % (gitroot, test_master), show=True, dir=gitroot)
492 except:
493 cleanup()
494 raise
496 try:
497 try:
498 if options.rebase is not None:
499 rebase_tree(options.rebase)
500 elif options.rebase_master:
501 rebase_tree(samba_master)
502 except:
503 email_failure(-1, 'rebase', 'rebase', 'rebase', 'rebase on master failed')
504 sys.exit(1)
505 blist = buildlist(tasks, args)
506 if options.tail:
507 blist.start_tail()
508 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
509 if status != 0 or errstr != "retry":
510 break
511 cleanup()
512 except:
513 cleanup()
514 raise
516 cleanup_list.append(gitroot + "/autobuild.pid")
518 blist.kill_kids()
519 if options.tail:
520 print("waiting for tail to flush")
521 time.sleep(1)
523 if status == 0:
524 print errstr
525 if options.passcmd is not None:
526 print("Running passcmd: %s" % options.passcmd)
527 run_cmd(options.passcmd, dir=test_master)
528 if options.pushto is not None:
529 push_to(options.pushto)
530 elif options.push_master:
531 push_to(samba_master_ssh)
532 if options.keeplogs:
533 blist.tarlogs("logs.tar.gz")
534 print("Logs in logs.tar.gz")
535 if options.always_email:
536 email_success()
537 blist.remove_logs()
538 cleanup()
539 print(errstr)
540 sys.exit(0)
542 # something failed, gather a tar of the logs
543 blist.tarlogs("logs.tar.gz")
545 if options.email is not None:
546 email_failure(status, failed_task, failed_stage, failed_tag, errstr)
548 cleanup()
549 print(errstr)
550 print("Logs in logs.tar.gz")
551 sys.exit(status)