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