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