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