s3-printing: fix broken print_job_get_name() return
[Samba.git] / script / autobuild.py
blob47751435e38ac97d461283601d39d72a44119c25
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 os.environ['CC'] = "ccache gcc"
19 builddirs = {
20 "samba3" : "source3",
21 "samba3-waf": "source3",
22 "samba4" : ".",
23 "ldb" : "source4/lib/ldb",
24 "tdb" : "lib/tdb",
25 "talloc" : "lib/talloc",
26 "replace" : "lib/replace",
27 "tevent" : "lib/tevent",
28 "pidl" : "pidl",
29 "pass" : ".",
30 "fail" : ".",
31 "retry" : "."
34 defaulttasks = [ "samba3", "samba3-waf", "samba4", "ldb", "tdb", "talloc", "replace", "tevent", "pidl" ]
36 tasks = {
37 "samba3" : [ ("autogen", "./autogen.sh", "text/plain"),
38 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
39 ("make basics", "make basics", "text/plain"),
40 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
41 ("install", "make install", "text/plain"),
42 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
43 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
44 ("clean", "make clean", "text/plain") ],
46 "samba3-waf" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
47 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
48 ("make", "make -j", "text/plain"),
49 ("install", "make install", "text/plain"),
50 ("clean", "make clean", "text/plain") ],
52 # We have 'test' before 'install' because, 'test' should work without 'install'
53 "samba4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
54 ("make", "make -j", "text/plain"),
55 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
56 ("install", "make install", "text/plain"),
57 ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
58 ("clean", "make clean", "text/plain") ],
60 "ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
61 ("make", "make -j", "text/plain"),
62 ("install", "make install", "text/plain"),
63 ("test", "TDB_NO_FSYNC=1 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 # We don't use TDB_NO_FSYNC=1 here, because we want to test the transaction code
69 "tdb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
70 ("make", "make -j", "text/plain"),
71 ("install", "make install", "text/plain"),
72 ("test", "make test", "text/plain"),
73 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
74 ("distcheck", "make distcheck", "text/plain"),
75 ("clean", "make clean", "text/plain") ],
77 "talloc" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
78 ("make", "make -j", "text/plain"),
79 ("install", "make install", "text/plain"),
80 ("test", "make test", "text/plain"),
81 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
82 ("distcheck", "make distcheck", "text/plain"),
83 ("clean", "make clean", "text/plain") ],
85 "replace" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
86 ("make", "make -j", "text/plain"),
87 ("install", "make install", "text/plain"),
88 ("test", "make test", "text/plain"),
89 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
90 ("distcheck", "make distcheck", "text/plain"),
91 ("clean", "make clean", "text/plain") ],
93 "tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
94 ("make", "make -j", "text/plain"),
95 ("install", "make install", "text/plain"),
96 ("test", "make test", "text/plain"),
97 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
98 ("distcheck", "make distcheck", "text/plain"),
99 ("clean", "make clean", "text/plain") ],
101 "pidl" : [ ("configure", "perl Makefile.PL PREFIX=${PREFIX_DIR}", "text/plain"),
102 ("touch", "touch *.yp", "text/plain"),
103 ("make", "make", "text/plain"),
104 ("test", "make test", "text/plain"),
105 ("install", "make install", "text/plain"),
106 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
107 ("clean", "make clean", "text/plain") ],
109 # these are useful for debugging autobuild
110 'pass' : [ ("pass", 'echo passing && /bin/true', "text/plain") ],
111 'fail' : [ ("fail", 'echo failing && /bin/false', "text/plain") ]
114 retry_task = [ ( "retry",
115 '''set -e
116 git remote add -t master master %s
117 git fetch master
118 while :; do
119 sleep 60
120 git describe master/master > old_master.desc
121 git fetch master
122 git describe master/master > master.desc
123 diff old_master.desc master.desc
124 done
125 ''' % samba_master, "test/plain" ) ]
127 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
128 if show is None:
129 show = options.verbose
130 if show:
131 print("Running: '%s' in '%s'" % (cmd, dir))
132 if output:
133 return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
134 elif checkfail:
135 return check_call(cmd, shell=True, cwd=dir)
136 else:
137 return call(cmd, shell=True, cwd=dir)
140 class builder(object):
141 '''handle build of one directory'''
143 def __init__(self, name, sequence):
144 self.name = name
145 self.dir = builddirs[name]
147 self.tag = self.name.replace('/', '_')
148 self.sequence = sequence
149 self.next = 0
150 self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
151 self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
152 if options.verbose:
153 print("stdout for %s in %s" % (self.name, self.stdout_path))
154 print("stderr for %s in %s" % (self.name, self.stderr_path))
155 run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
156 self.stdout = open(self.stdout_path, 'w')
157 self.stderr = open(self.stderr_path, 'w')
158 self.stdin = open("/dev/null", 'r')
159 self.sdir = "%s/%s" % (testbase, self.tag)
160 self.prefix = "%s/prefix/%s" % (testbase, self.tag)
161 run_cmd("rm -rf %s" % self.sdir)
162 cleanup_list.append(self.sdir)
163 cleanup_list.append(self.prefix)
164 os.makedirs(self.sdir)
165 run_cmd("rm -rf %s" % self.sdir)
166 run_cmd("git clone --shared %s %s" % (test_master, self.sdir), dir=test_master, show=True)
167 self.start_next()
169 def start_next(self):
170 if self.next == len(self.sequence):
171 print '%s: Completed OK' % self.name
172 self.done = True
173 return
174 (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
175 self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
176 self.cmd = self.cmd.replace("${PREFIX_DIR}", "%s" % self.prefix)
177 # if self.output_mime_type == "text/x-subunit":
178 # self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
179 print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
180 cwd = os.getcwd()
181 os.chdir("%s/%s" % (self.sdir, self.dir))
182 self.proc = Popen(self.cmd, shell=True,
183 stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
184 os.chdir(cwd)
185 self.next += 1
188 class buildlist(object):
189 '''handle build of multiple directories'''
191 def __init__(self, tasklist, tasknames):
192 global tasks
193 self.tlist = []
194 self.tail_proc = None
195 self.retry = None
196 if tasknames == []:
197 tasknames = defaulttasks
198 for n in tasknames:
199 b = builder(n, tasks[n])
200 self.tlist.append(b)
201 if options.retry:
202 self.retry = builder('retry', retry_task)
203 self.need_retry = False
205 def kill_kids(self):
206 if self.tail_proc is not None:
207 self.tail_proc.terminate()
208 self.tail_proc.wait()
209 self.tail_proc = None
210 if self.retry is not None:
211 self.retry.proc.terminate()
212 self.retry.proc.wait()
213 self.retry = None
214 for b in self.tlist:
215 if b.proc is not None:
216 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
217 b.proc.terminate()
218 b.proc.wait()
219 b.proc = None
221 def wait_one(self):
222 while True:
223 none_running = True
224 for b in self.tlist:
225 if b.proc is None:
226 continue
227 none_running = False
228 b.status = b.proc.poll()
229 if b.status is None:
230 continue
231 b.proc = None
232 return b
233 if options.retry:
234 ret = self.retry.proc.poll()
235 if ret is not None:
236 self.need_retry = True
237 self.retry = None
238 return None
239 if none_running:
240 return None
241 time.sleep(0.1)
243 def run(self):
244 while True:
245 b = self.wait_one()
246 if options.retry and self.need_retry:
247 self.kill_kids()
248 print("retry needed")
249 return (0, None, None, None, "retry")
250 if b is None:
251 break
252 if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
253 self.kill_kids()
254 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
255 b.start_next()
256 self.kill_kids()
257 return (0, None, None, None, "All OK")
259 def tarlogs(self, fname):
260 tar = tarfile.open(fname, "w:gz")
261 for b in self.tlist:
262 tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
263 tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
264 if os.path.exists("autobuild.log"):
265 tar.add("autobuild.log")
266 tar.close()
268 def remove_logs(self):
269 for b in self.tlist:
270 os.unlink(b.stdout_path)
271 os.unlink(b.stderr_path)
273 def start_tail(self):
274 cwd = os.getcwd()
275 cmd = "tail -f *.stdout *.stderr"
276 os.chdir(gitroot)
277 self.tail_proc = Popen(cmd, shell=True)
278 os.chdir(cwd)
281 def cleanup():
282 if options.nocleanup:
283 return
284 print("Cleaning up ....")
285 for d in cleanup_list:
286 run_cmd("rm -rf %s" % d)
289 def find_git_root():
290 '''get to the top of the git repo'''
291 p=os.getcwd()
292 while p != '/':
293 if os.path.isdir(os.path.join(p, ".git")):
294 return p
295 p = os.path.abspath(os.path.join(p, '..'))
296 return None
299 def daemonize(logfile):
300 pid = os.fork()
301 if pid == 0: # Parent
302 os.setsid()
303 pid = os.fork()
304 if pid != 0: # Actual daemon
305 os._exit(0)
306 else: # Grandparent
307 os._exit(0)
309 import resource # Resource usage information.
310 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
311 if maxfd == resource.RLIM_INFINITY:
312 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
313 for fd in range(0, maxfd):
314 try:
315 os.close(fd)
316 except OSError:
317 pass
318 os.open(logfile, os.O_RDWR | os.O_CREAT)
319 os.dup2(0, 1)
320 os.dup2(0, 2)
322 def write_pidfile(fname):
323 '''write a pid file, cleanup on exit'''
324 f = open(fname, mode='w')
325 f.write("%u\n" % os.getpid())
326 f.close()
329 def rebase_tree(url):
330 print("Rebasing on %s" % url)
331 run_cmd("git describe HEAD", show=True, dir=test_master)
332 run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
333 run_cmd("git fetch master", show=True, dir=test_master)
334 if options.fix_whitespace:
335 run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
336 else:
337 run_cmd("git rebase master/master", show=True, dir=test_master)
338 diff = run_cmd("git --no-pager diff HEAD master/master", dir=test_master, output=True)
339 if diff == '':
340 print("No differences between HEAD and master/master - exiting")
341 sys.exit(0)
342 run_cmd("git describe master/master", show=True, dir=test_master)
343 run_cmd("git describe HEAD", show=True, dir=test_master)
344 run_cmd("git --no-pager diff --stat HEAD master/master", show=True, dir=test_master)
346 def push_to(url):
347 print("Pushing to %s" % url)
348 if options.mark:
349 run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
350 run_cmd("git commit --amend -c HEAD", dir=test_master)
351 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
352 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
353 run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
354 run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
356 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
358 parser = OptionParser()
359 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
360 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
361 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
362 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
363 default=def_testbase)
364 parser.add_option("", "--passcmd", help="command to run on success", default=None)
365 parser.add_option("", "--verbose", help="show all commands as they are run",
366 default=False, action="store_true")
367 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
368 default=None, type='str')
369 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
370 default=False, action='store_true')
371 parser.add_option("", "--pushto", help="push to a git url on success",
372 default=None, type='str')
373 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
374 default=False, action='store_true')
375 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
376 default=False, action="store_true")
377 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
378 default=False, action="store_true")
379 parser.add_option("", "--retry", help="automatically retry if master changes",
380 default=False, action="store_true")
381 parser.add_option("", "--email", help="send email to the given address on failure",
382 type='str', default=None)
383 parser.add_option("", "--always-email", help="always send email, even on success",
384 action="store_true")
385 parser.add_option("", "--daemon", help="daemonize after initial setup",
386 action="store_true")
389 def email_failure(status, failed_task, failed_stage, failed_tag, errstr):
390 '''send an email to options.email about the failure'''
391 user = os.getenv("USER")
392 text = '''
393 Dear Developer,
395 Your autobuild failed when trying to test %s with the following error:
398 the autobuild has been abandoned. Please fix the error and resubmit.
400 A summary of the autobuild process is here:
402 http://git.samba.org/%s/samba-autobuild/autobuild.log
403 ''' % (failed_task, errstr, user)
405 if failed_task != 'rebase':
406 text += '''
407 You can see logs of the failed task here:
409 http://git.samba.org/%s/samba-autobuild/%s.stdout
410 http://git.samba.org/%s/samba-autobuild/%s.stderr
412 or you can get full logs of all tasks in this job here:
414 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
416 The top commit for the tree that was built was:
420 ''' % (user, failed_tag, user, failed_tag, user, top_commit_msg)
421 msg = MIMEText(text)
422 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
423 msg['From'] = 'autobuild@samba.org'
424 msg['To'] = options.email
426 s = smtplib.SMTP()
427 s.connect()
428 s.sendmail(msg['From'], [msg['To']], msg.as_string())
429 s.quit()
431 def email_success():
432 '''send an email to options.email about a successful build'''
433 user = os.getenv("USER")
434 text = '''
435 Dear Developer,
437 Your autobuild has succeeded.
441 if options.keeplogs:
442 text += '''
444 you can get full logs of all tasks in this job here:
446 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
448 ''' % user
450 text += '''
451 The top commit for the tree that was built was:
454 ''' % top_commit_msg
456 msg = MIMEText(text)
457 msg['Subject'] = 'autobuild success'
458 msg['From'] = 'autobuild@samba.org'
459 msg['To'] = options.email
461 s = smtplib.SMTP()
462 s.connect()
463 s.sendmail(msg['From'], [msg['To']], msg.as_string())
464 s.quit()
467 (options, args) = parser.parse_args()
469 if options.retry:
470 if not options.rebase_master and options.rebase is None:
471 raise Exception('You can only use --retry if you also rebase')
473 testbase = "%s/b%u" % (options.testbase, os.getpid())
474 test_master = "%s/master" % testbase
476 gitroot = find_git_root()
477 if gitroot is None:
478 raise Exception("Failed to find git root")
480 # get the top commit message, for emails
481 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
483 try:
484 os.makedirs(testbase)
485 except Exception, reason:
486 raise Exception("Unable to create %s : %s" % (testbase, reason))
487 cleanup_list.append(testbase)
489 if options.daemon:
490 logfile = os.path.join(testbase, "log")
491 print "Forking into the background, writing progress to %s" % logfile
492 daemonize(logfile)
494 write_pidfile(gitroot + "/autobuild.pid")
496 while True:
497 try:
498 run_cmd("rm -rf %s" % test_master)
499 cleanup_list.append(test_master)
500 run_cmd("git clone --shared %s %s" % (gitroot, test_master), show=True, dir=gitroot)
501 except:
502 cleanup()
503 raise
505 try:
506 try:
507 if options.rebase is not None:
508 rebase_tree(options.rebase)
509 elif options.rebase_master:
510 rebase_tree(samba_master)
511 except:
512 email_failure(-1, 'rebase', 'rebase', 'rebase', 'rebase on master failed')
513 sys.exit(1)
514 blist = buildlist(tasks, args)
515 if options.tail:
516 blist.start_tail()
517 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
518 if status != 0 or errstr != "retry":
519 break
520 cleanup()
521 except:
522 cleanup()
523 raise
525 cleanup_list.append(gitroot + "/autobuild.pid")
527 blist.kill_kids()
528 if options.tail:
529 print("waiting for tail to flush")
530 time.sleep(1)
532 if status == 0:
533 print errstr
534 if options.passcmd is not None:
535 print("Running passcmd: %s" % options.passcmd)
536 run_cmd(options.passcmd, dir=test_master)
537 if options.pushto is not None:
538 push_to(options.pushto)
539 elif options.push_master:
540 push_to(samba_master_ssh)
541 if options.keeplogs:
542 blist.tarlogs("logs.tar.gz")
543 print("Logs in logs.tar.gz")
544 if options.always_email:
545 email_success()
546 blist.remove_logs()
547 cleanup()
548 print(errstr)
549 sys.exit(0)
551 # something failed, gather a tar of the logs
552 blist.tarlogs("logs.tar.gz")
554 if options.email is not None:
555 email_failure(status, failed_task, failed_stage, failed_tag, errstr)
557 cleanup()
558 print(errstr)
559 print("Logs in logs.tar.gz")
560 sys.exit(status)