6570e15e509da3bd72ca42ac55e1aac595b1e763
[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     }
31
32 defaulttasks = [ "samba3", "samba4", "ldb", "tdb", "talloc", "replace", "tevent", "pidl" ]
33
34 tasks = {
35     "samba3" : [ ("autogen", "./autogen.sh", "text/plain"),
36                  ("configure", "./configure.developer ${PREFIX}", "text/plain"),
37                  ("make basics", "make basics", "text/plain"),
38                  ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
39                  ("install", "make install", "text/plain"),
40                  ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
41                  ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
42                  ("clean", "make clean", "text/plain") ],
43
44     # We have 'test' before 'install' because, 'test' should work without 'install'
45     "samba4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
46                  ("make", "make -j", "text/plain"),
47                  ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
48                  ("install", "make install", "text/plain"),
49                  ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
50                  ("clean", "make clean", "text/plain") ],
51
52     "ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
53               ("make", "make -j", "text/plain"),
54               ("install", "make install", "text/plain"),
55               ("test", "TDB_NO_FSYNC=1 make test", "text/plain"),
56               ("check-clean-tree", "../../../script/clean-source-tree.sh", "text/plain"),
57               ("distcheck", "make distcheck", "text/plain"),
58               ("clean", "make clean", "text/plain") ],
59
60     # We don't use TDB_NO_FSYNC=1 here, because we want to test the transaction code
61     "tdb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
62               ("make", "make -j", "text/plain"),
63               ("install", "make install", "text/plain"),
64               ("test", "make test", "text/plain"),
65               ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
66               ("distcheck", "make distcheck", "text/plain"),
67               ("clean", "make clean", "text/plain") ],
68
69     "talloc" : [ ("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") ],
76
77     "replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
78                   ("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
139         if name in ['pass', 'fail', 'retry']:
140             self.dir = "."
141         else:
142             self.dir = builddirs[name]
143
144         self.tag = self.name.replace('/', '_')
145         self.sequence = sequence
146         self.next = 0
147         self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
148         self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
149         if options.verbose:
150             print("stdout for %s in %s" % (self.name, self.stdout_path))
151             print("stderr for %s in %s" % (self.name, self.stderr_path))
152         run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
153         self.stdout = open(self.stdout_path, 'w')
154         self.stderr = open(self.stderr_path, 'w')
155         self.stdin  = open("/dev/null", 'r')
156         self.sdir = "%s/%s" % (testbase, self.tag)
157         self.prefix = "%s/prefix/%s" % (testbase, self.tag)
158         run_cmd("rm -rf %s" % self.sdir)
159         cleanup_list.append(self.sdir)
160         cleanup_list.append(self.prefix)
161         os.makedirs(self.sdir)
162         run_cmd("rm -rf %s" % self.sdir)
163         run_cmd("git clone --shared %s %s" % (gitroot, self.sdir))
164         self.start_next()
165
166     def start_next(self):
167         if self.next == len(self.sequence):
168             print '%s: Completed OK' % self.name
169             self.done = True
170             return
171         (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
172         self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
173         self.cmd = self.cmd.replace("${PREFIX_DIR}", "%s" % self.prefix)
174 #        if self.output_mime_type == "text/x-subunit":
175 #            self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
176         print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
177         cwd = os.getcwd()
178         os.chdir("%s/%s" % (self.sdir, self.dir))
179         self.proc = Popen(self.cmd, shell=True,
180                           stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
181         os.chdir(cwd)
182         self.next += 1
183
184
185 class buildlist(object):
186     '''handle build of multiple directories'''
187
188     def __init__(self, tasklist, tasknames):
189         global tasks
190         self.tlist = []
191         self.tail_proc = None
192         self.retry = None
193         if tasknames == []:
194             tasknames = defaulttasks
195         for n in tasknames:
196             b = builder(n, tasks[n])
197             self.tlist.append(b)
198         if options.retry:
199             self.retry = builder('retry', retry_task)
200             self.need_retry = False
201
202     def kill_kids(self):
203         if self.tail_proc is not None:
204             self.tail_proc.terminate()
205             self.tail_proc.wait()
206             self.tail_proc = None
207         if self.retry is not None:
208             self.retry.proc.terminate()
209             self.retry.proc.wait()
210             self.retry = None
211         for b in self.tlist:
212             if b.proc is not None:
213                 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
214                 b.proc.terminate()
215                 b.proc.wait()
216                 b.proc = None
217
218     def wait_one(self):
219         while True:
220             none_running = True
221             for b in self.tlist:
222                 if b.proc is None:
223                     continue
224                 none_running = False
225                 b.status = b.proc.poll()
226                 if b.status is None:
227                     continue
228                 b.proc = None
229                 return b
230             if options.retry:
231                 ret = self.retry.proc.poll()
232                 if ret is not None:
233                     self.need_retry = True
234                     self.retry = None
235                     return None
236             if none_running:
237                 return None
238             time.sleep(0.1)
239
240     def run(self):
241         while True:
242             b = self.wait_one()
243             if options.retry and self.need_retry:
244                 self.kill_kids()
245                 print("retry needed")
246                 return (0, None, None, None, "retry")
247             if b is None:
248                 break
249             if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
250                 self.kill_kids()
251                 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
252             b.start_next()
253         self.kill_kids()
254         return (0, None, None, None, "All OK")
255
256     def tarlogs(self, fname):
257         tar = tarfile.open(fname, "w:gz")
258         for b in self.tlist:
259             tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
260             tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
261         if os.path.exists("autobuild.log"):
262             tar.add("autobuild.log")
263         tar.close()
264
265     def remove_logs(self):
266         for b in self.tlist:
267             os.unlink(b.stdout_path)
268             os.unlink(b.stderr_path)
269
270     def start_tail(self):
271         cwd = os.getcwd()
272         cmd = "tail -f *.stdout *.stderr"
273         os.chdir(gitroot)
274         self.tail_proc = Popen(cmd, shell=True)
275         os.chdir(cwd)
276
277
278 def cleanup():
279     if options.nocleanup:
280         return
281     print("Cleaning up ....")
282     for d in cleanup_list:
283         run_cmd("rm -rf %s" % d)
284
285
286 def find_git_root():
287     '''get to the top of the git repo'''
288     p=os.getcwd()
289     while p != '/':
290         if os.path.isdir(os.path.join(p, ".git")):
291             return p
292         p = os.path.abspath(os.path.join(p, '..'))
293     return None
294
295
296 def daemonize(logfile):
297     pid = os.fork()
298     if pid == 0: # Parent
299         os.setsid()
300         pid = os.fork()
301         if pid != 0: # Actual daemon
302             os._exit(0)
303     else: # Grandparent
304         os._exit(0)
305
306     import resource      # Resource usage information.
307     maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
308     if maxfd == resource.RLIM_INFINITY:
309         maxfd = 1024 # Rough guess at maximum number of open file descriptors.
310     for fd in range(0, maxfd):
311         try:
312             os.close(fd)
313         except OSError:
314             pass
315     os.open(logfile, os.O_RDWR | os.O_CREAT)
316     os.dup2(0, 1)
317     os.dup2(0, 2)
318
319 def write_pidfile(fname):
320     '''write a pid file, cleanup on exit'''
321     f = open(fname, mode='w')
322     f.write("%u\n" % os.getpid())
323     f.close()
324
325
326 def rebase_tree(url):
327     print("Rebasing on %s" % url)
328     run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
329     run_cmd("git fetch master", show=True, dir=test_master)
330     if options.fix_whitespace:
331         run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
332     else:
333         run_cmd("git rebase master/master", show=True, dir=test_master)
334     diff = run_cmd("git --no-pager diff HEAD master/master", dir=test_master, output=True)
335     if diff == '':
336         print("No differences between HEAD and master/master - exiting")
337         sys.exit(0)
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))
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)