land: Some cosmetic fixes.
[kai/samba.git] / script / land.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 # Copyright Jelmer Vernooij 2010
5 # released under GNU GPL v3 or later
6
7 import fcntl
8 from subprocess import call, check_call, Popen, PIPE
9 import os, tarfile, sys, time
10 from optparse import OptionParser
11 import smtplib
12 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../selftest"))
13 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../lib/testtools"))
14 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../lib/subunit/python"))
15 import subunit
16 import testtools
17 import subunithelper
18 from email.mime.text import MIMEText
19 from email.mime.multipart import MIMEMultipart
20
21 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
22 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
23
24 cleanup_list = []
25
26 os.putenv('CC', "ccache gcc")
27
28 tasks = {
29     "source3" : [ ("autogen", "./autogen.sh", "text/plain"),
30                   ("configure", "./configure.developer ${PREFIX}", "text/plain"),
31                   ("make basics", "make basics", "text/plain"),
32                   ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
33                   ("install", "make install", "text/plain"),
34                   ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
35
36     "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
37                   ("make", "make -j", "text/plain"),
38                   ("install", "make install", "text/plain"),
39                   ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
40
41     "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
42                           ("make", "make -j", "text/plain"),
43                           ("install", "make install", "text/plain"),
44                           ("test", "make test", "text/plain") ],
45
46     "lib/tdb" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
47                   ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
48                   ("make", "make -j", "text/plain"),
49                   ("install", "make install", "text/plain"),
50                   ("test", "make test", "text/plain") ],
51
52     "lib/talloc" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
53                      ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
54                      ("make", "make -j", "text/plain"),
55                      ("install", "make install", "text/plain"),
56                      ("test", "make test", "text/x-subunit"), ],
57
58     "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
59                       ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
60                       ("make", "make -j", "text/plain"),
61                       ("install", "make install", "text/plain"),
62                       ("test", "make test", "text/plain"), ],
63
64     "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
65                      ("make", "make -j", "text/plain"),
66                      ("install", "make install", "text/plain"),
67                      ("test", "make test", "text/plain"), ],
68 }
69
70 retry_task = [ ( "retry",
71                  '''set -e
72                 git remote add -t master master %s
73                 git fetch master
74                 while :; do
75                   sleep 60
76                   git describe master/master > old_master.desc
77                   git fetch master
78                   git describe master/master > master.desc
79                   diff old_master.desc master.desc
80                 done
81                ''' % samba_master, "test/plain" ) ]
82
83
84 def run_cmd(cmd, dir=None, show=None, output=False, checkfail=True, shell=False):
85     if show is None:
86         show = options.verbose
87     if show:
88         print("Running: '%s' in '%s'" % (cmd, dir))
89     if output:
90         return Popen(cmd, stdout=PIPE, cwd=dir, shell=shell).communicate()[0]
91     elif checkfail:
92         return check_call(cmd, cwd=dir, shell=shell)
93     else:
94         return call(cmd, cwd=dir, shell=shell)
95
96
97 def clone_gitroot(test_master, revision="HEAD"):
98     run_cmd(["git", "clone", "--shared", gitroot, test_master])
99     if revision != "HEAD":
100         run_cmd(["git", "checkout", revision])
101
102
103 class TreeStageBuilder(object):
104     """Handle building of a particular stage for a tree.
105     """
106
107     def __init__(self, tree, name, command, fail_quickly=False):
108         self.tree = tree
109         self.name = name
110         self.command = command
111         self.fail_quickly = fail_quickly
112         self.status = None
113         self.stdin = open(os.devnull, 'r')
114
115     def start(self):
116         raise NotImplementedError(self.start)
117
118     def poll(self):
119         self.status = self.proc.poll()
120         return self.status
121
122     def kill(self):
123         if self.proc is not None:
124             try:
125                 run_cmd(["killbysubdir", self.tree.sdir], checkfail=False)
126             except OSError:
127                 # killbysubdir doesn't exist ?
128                 pass
129             self.proc.terminate()
130             self.proc.wait()
131             self.proc = None
132
133     @property
134     def failure_reason(self):
135         return "failed '%s' with status %d" % (self.cmd, self.status)
136
137     @property
138     def failed(self):
139         return (os.WIFSIGNALED(self.status) or os.WEXITSTATUS(self.status) != 0)
140
141
142 class PlainTreeStageBuilder(TreeStageBuilder):
143
144     def start(self):
145         print '%s: [%s] Running %s' % (self.name, self.name, self.command)
146         self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
147                           stdout=self.tree.stdout, stderr=self.tree.stderr,
148                           stdin=self.stdin)
149
150
151 class AbortingTestResult(subunithelper.TestsuiteEnabledTestResult):
152
153     def __init__(self, stage):
154         super(AbortingTestResult, self).__init__()
155         self.stage = stage
156
157     def addError(self, test, details=None):
158         self.stage.proc.terminate()
159
160     def addFailure(self, test, details=None):
161         self.stage.proc.terminate()
162
163
164 class SubunitTreeStageBuilder(TreeStageBuilder):
165
166     def __init__(self, tree, name, command, fail_quickly=False):
167         super(SubunitTreeStageBuilder, self).__init__(tree, name, command,
168                 fail_quickly)
169         self.failed_tests = []
170         self.subunit_path = os.path.join(gitroot,
171             "%s.%s.subunit" % (self.tree.tag, self.name))
172         self.tree.logfiles.append(
173             (self.subunit_path, os.path.basename(self.subunit_path),
174              "text/x-subunit"))
175         self.subunit = open(self.subunit_path, 'w')
176
177         formatter = subunithelper.PlainFormatter(False, True, {})
178         clients = [formatter, subunit.TestProtocolClient(self.subunit)]
179         if fail_quickly:
180             clients.append(AbortingTestResult(self))
181         self.subunit_server = subunit.TestProtocolServer(
182             testtools.MultiTestResult(*clients),
183             self.subunit)
184         self.buffered = ""
185
186     def start(self):
187         print '%s: [%s] Running' % (self.tree.name, self.name)
188         self.proc = Popen(self.command, shell=True, cwd=self.tree.dir,
189             stdout=PIPE, stderr=self.tree.stderr, stdin=self.stdin)
190         fd = self.proc.stdout.fileno()
191         fl = fcntl.fcntl(fd, fcntl.F_GETFL)
192         fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
193
194     def poll(self):
195         try:
196             data = self.proc.stdout.read()
197         except IOError:
198             return None
199         else:
200             self.tree.stdout.write(data)
201             self.buffered += data
202             buffered = ""
203             for l in self.buffered.splitlines(True):
204                 if l[-1] == "\n":
205                     self.subunit_server.lineReceived(l)
206                 else:
207                     buffered += l
208             self.buffered = buffered
209             self.status = self.proc.poll()
210             if self.status is not None:
211                 self.subunit.close()
212             return self.status
213
214
215 class TreeBuilder(object):
216     '''handle build of one directory'''
217
218     def __init__(self, name, sequence, fail_quickly=False):
219         self.name = name
220         self.fail_quickly = fail_quickly
221
222         self.tag = self.name.replace('/', '_')
223         self.sequence = sequence
224         self.next = 0
225         self.stdout_path = os.path.join(gitroot, "%s.stdout" % (self.tag, ))
226         self.stderr_path = os.path.join(gitroot, "%s.stderr" % (self.tag, ))
227         self.logfiles = [
228             (self.stdout_path, os.path.basename(self.stdout_path), "text/plain"),
229             (self.stderr_path, os.path.basename(self.stderr_path), "text/plain"),
230             ]
231         if options.verbose:
232             print("stdout for %s in %s" % (self.name, self.stdout_path))
233             print("stderr for %s in %s" % (self.name, self.stderr_path))
234         if os.path.exists(self.stdout_path):
235             os.unlink(self.stdout_path)
236         if os.path.exists(self.stderr_path):
237             os.unlink(self.stderr_path)
238         self.stdout = open(self.stdout_path, 'w')
239         self.stderr = open(self.stderr_path, 'w')
240         self.sdir = os.path.join(testbase, self.tag)
241         if name in ['pass', 'fail', 'retry']:
242             self.dir = self.sdir
243         else:
244             self.dir = os.path.join(self.sdir, self.name)
245         self.prefix = os.path.join(testbase, "prefix", self.tag)
246         run_cmd(["rm", "-rf", self.sdir])
247         cleanup_list.append(self.sdir)
248         cleanup_list.append(self.prefix)
249         os.makedirs(self.sdir)
250         run_cmd(["rm",  "-rf", self.sdir])
251         clone_gitroot(self.sdir, revision)
252         self.start_next()
253
254     def start_next(self):
255         if self.next == len(self.sequence):
256             print '%s: Completed OK' % self.name
257             self.done = True
258             self.stdout.close()
259             self.stderr.close()
260             return
261         (stage_name, cmd, output_mime_type) = self.sequence[self.next]
262         cmd = cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
263         if output_mime_type == "text/plain":
264             self.stage = PlainTreeStageBuilder(self, stage_name, cmd,
265                 self.fail_quickly)
266         elif output_mime_type == "text/x-subunit":
267             self.stage = SubunitTreeStageBuilder(self, stage_name, cmd,
268                 self.fail_quickly)
269         else:
270             raise Exception("Unknown output mime type %s" % output_mime_type)
271         self.stage.start()
272         self.next += 1
273
274     def remove_logs(self):
275         for path, name, mime_type in self.logfiles:
276             os.unlink(path)
277
278     def attach_logs(self, outer):
279         for path, name, mime_type in self.logfiles:
280             assert mime_type.startswith("text/")
281             f = open(path, 'r')
282             try:
283                 f.seek(0)
284                 msg = MIMEText(f.read(), mime_type[len("text/"):])
285             finally:
286                 f.close()
287             msg.add_header('Content-Disposition', 'attachment',
288                            filename=name)
289             outer.attach(msg)
290
291     @property
292     def status(self):
293         return self.stage.status
294
295     def poll(self):
296         return self.stage.poll()
297
298     def kill(self):
299         if self.stage is not None:
300             self.stage.kill()
301             self.stage = None
302
303     @property
304     def failed(self):
305         if self.stage is None:
306             return False
307         return self.stage.failed
308
309     @property
310     def failure_reason(self):
311         return "%s: [%s] %s" % (self.name, self.stage.name,
312             self.stage.failure_reason)
313
314
315 class BuildList(object):
316     '''handle build of multiple directories'''
317
318     def __init__(self, tasklist, tasknames):
319         global tasks
320         self.tlist = []
321         self.tail_proc = None
322         self.retry = None
323         if tasknames == ['pass']:
324             tasks = { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
325         if tasknames == ['fail']:
326             tasks = { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
327         if tasknames == []:
328             tasknames = tasklist
329         for n in tasknames:
330             b = TreeBuilder(n, tasks[n], not options.fail_slowly)
331             self.tlist.append(b)
332         if options.retry:
333             self.retry = TreeBuilder('retry', retry_task,
334                 not options.fail_slowly)
335             self.need_retry = False
336
337     def kill_kids(self):
338         if self.tail_proc is not None:
339             self.tail_proc.terminate()
340             self.tail_proc.wait()
341             self.tail_proc = None
342         if self.retry is not None:
343             self.retry.proc.terminate()
344             self.retry.proc.wait()
345             self.retry = None
346         for b in self.tlist:
347             b.kill()
348
349     def wait_one(self):
350         while True:
351             none_running = True
352             for b in self.tlist:
353                 if b.stage is None:
354                     continue
355                 none_running = False
356                 if b.poll() is None:
357                     continue
358                 b.stage = None
359                 return b
360             if options.retry:
361                 ret = self.retry.proc.poll()
362                 if ret is not None:
363                     self.need_retry = True
364                     self.retry = None
365                     return None
366             if none_running:
367                 return None
368             time.sleep(0.1)
369
370     def run(self):
371         while True:
372             b = self.wait_one()
373             if options.retry and self.need_retry:
374                 self.kill_kids()
375                 print("retry needed")
376                 return (0, None, None, None, "retry")
377             if b is None:
378                 break
379             if b.failed:
380                 self.kill_kids()
381                 return (b.status, b.name, b.stage, b.tag, b.failure_reason)
382             b.start_next()
383         self.kill_kids()
384         return (0, None, None, None, "All OK")
385
386     def tarlogs(self, fname):
387         tar = tarfile.open(fname, "w:gz")
388         for b in self.tlist:
389             for (path, name, mime_type) in b.logfiles:
390                 tar.add(path, arcname=name)
391         if os.path.exists("autobuild.log"):
392             tar.add("autobuild.log")
393         tar.close()
394
395     def attach_logs(self, msg):
396         for b in self.tlist:
397             b.attach_logs(msg)
398
399     def remove_logs(self):
400         for b in self.tlist:
401             b.remove_logs()
402
403     def start_tail(self):
404         cmd = "tail -f *.stdout *.stderr"
405         self.tail_proc = Popen(cmd, shell=True, cwd=gitroot)
406
407
408 def cleanup():
409     if options.nocleanup:
410         return
411     print("Cleaning up ....")
412     for d in cleanup_list:
413         run_cmd(["rm", "-rf", d])
414
415
416 def find_git_root(p):
417     '''get to the top of the git repo'''
418     while p != '/':
419         if os.path.isdir(os.path.join(p, ".git")):
420             return p
421         p = os.path.abspath(os.path.join(p, '..'))
422     return None
423
424
425 def daemonize(logfile):
426     pid = os.fork()
427     if pid == 0: # Parent
428         os.setsid()
429         pid = os.fork()
430         if pid != 0: # Actual daemon
431             os._exit(0)
432     else: # Grandparent
433         os._exit(0)
434
435     import resource      # Resource usage information.
436     maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
437     if maxfd == resource.RLIM_INFINITY:
438         maxfd = 1024 # Rough guess at maximum number of open file descriptors.
439     for fd in range(0, maxfd):
440         try:
441             os.close(fd)
442         except OSError:
443             pass
444     os.open(logfile, os.O_RDWR | os.O_CREAT)
445     os.dup2(0, 1)
446     os.dup2(0, 2)
447
448
449 def rebase_tree(url):
450     print("Rebasing on %s" % url)
451     run_cmd(["git", "remote", "add", "-t", "master", "master", url], show=True,
452             dir=test_master)
453     run_cmd(["git", "fetch", "master"], show=True, dir=test_master)
454     if options.fix_whitespace:
455         run_cmd(["git", "rebase", "--whitespace=fix", "master/master"],
456                 show=True, dir=test_master)
457     else:
458         run_cmd(["git", "rebase", "master/master"], show=True, dir=test_master)
459     diff = run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"],
460         dir=test_master, output=True)
461     if diff == '':
462         print("No differences between HEAD and master/master - exiting")
463         sys.exit(0)
464
465 def push_to(url):
466     print("Pushing to %s" % url)
467     if options.mark:
468         run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD",
469             dir=test_master, shell=True)
470         # the notes method doesn't work yet, as metze hasn't allowed
471         # refs/notes/* in master
472         # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD",
473         #     dir=test_master)
474     run_cmd(["git", "remote", "add", "-t", "master", "pushto", url], show=True,
475         dir=test_master)
476     run_cmd(["git", "push", "pushto", "+HEAD:master"], show=True,
477         dir=test_master)
478
479 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
480
481 parser = OptionParser()
482 parser.add_option("--repository", help="repository to run tests for", default=None, type=str)
483 parser.add_option("--revision", help="revision to compile if not HEAD", default=None, type=str)
484 parser.add_option("--tail", help="show output while running", default=False, action="store_true")
485 parser.add_option("--keeplogs", help="keep logs", default=False, action="store_true")
486 parser.add_option("--nocleanup", help="don't remove test tree", default=False, action="store_true")
487 parser.add_option("--testbase", help="base directory to run tests in (default %s)" % def_testbase,
488                   default=def_testbase)
489 parser.add_option("--passcmd", help="command to run on success", default=None)
490 parser.add_option("--verbose", help="show all commands as they are run",
491                   default=False, action="store_true")
492 parser.add_option("--rebase", help="rebase on the given tree before testing",
493                   default=None, type='str')
494 parser.add_option("--rebase-master", help="rebase on %s before testing" % samba_master,
495                   default=False, action='store_true')
496 parser.add_option("--pushto", help="push to a git url on success",
497                   default=None, type='str')
498 parser.add_option("--push-master", help="push to %s on success" % samba_master_ssh,
499                   default=False, action='store_true')
500 parser.add_option("--mark", help="add a Tested-By signoff before pushing",
501                   default=False, action="store_true")
502 parser.add_option("--fix-whitespace", help="fix whitespace on rebase",
503                   default=False, action="store_true")
504 parser.add_option("--retry", help="automatically retry if master changes",
505                   default=False, action="store_true")
506 parser.add_option("--email", help="send email to the given address on failure",
507                   type='str', default=None)
508 parser.add_option("--always-email", help="always send email, even on success",
509                   action="store_true")
510 parser.add_option("--daemon", help="daemonize after initial setup",
511                   action="store_true")
512 parser.add_option("--fail-slowly", help="continue running tests even after one has already failed",
513                   action="store_true")
514
515
516 def email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr):
517     '''send an email to options.email about the failure'''
518     user = os.getenv("USER")
519     text = '''
520 Dear Developer,
521
522 Your autobuild failed when trying to test %s with the following error:
523    %s
524
525 the autobuild has been abandoned. Please fix the error and resubmit.
526
527 You can see logs of the failed task here:
528
529   http://git.samba.org/%s/samba-autobuild/%s.stdout
530   http://git.samba.org/%s/samba-autobuild/%s.stderr
531
532 A summary of the autobuild process is here:
533
534   http://git.samba.org/%s/samba-autobuild/autobuild.log
535
536 or you can get full logs of all tasks in this job here:
537
538   http://git.samba.org/%s/samba-autobuild/logs.tar.gz
539
540 The top commit for the tree that was built was:
541
542 %s
543
544 ''' % (failed_task, errstr, user, failed_tag, user, failed_tag, user, user,
545        get_top_commit_msg(test_master))
546
547     msg = MIMEMultipart()
548     msg['Subject'] = 'autobuild failure for task %s during %s' % (
549         failed_task, failed_stage)
550     msg['From'] = 'autobuild@samba.org'
551     msg['To'] = options.email
552
553     main = MIMEText(text)
554     msg.attach(main)
555
556     blist.attach_logs(msg)
557
558     s = smtplib.SMTP()
559     s.connect()
560     s.sendmail(msg['From'], [msg['To']], msg.as_string())
561     s.quit()
562
563 def email_success(blist):
564     '''send an email to options.email about a successful build'''
565     user = os.getenv("USER")
566     text = '''
567 Dear Developer,
568
569 Your autobuild has succeeded.
570
571 '''
572
573     if options.keeplogs:
574         text += '''
575
576 you can get full logs of all tasks in this job here:
577
578   http://git.samba.org/%s/samba-autobuild/logs.tar.gz
579
580 ''' % user
581
582     text += '''
583 The top commit for the tree that was built was:
584
585 %s
586 ''' % (get_top_commit_msg(test_master),)
587
588     msg = MIMEMultipart()
589     msg['Subject'] = 'autobuild success'
590     msg['From'] = 'autobuild@samba.org'
591     msg['To'] = options.email
592
593     main = MIMEText(text, 'plain')
594     msg.attach(main)
595
596     blist.attach_logs(msg)
597
598     s = smtplib.SMTP()
599     s.connect()
600     s.sendmail(msg['From'], [msg['To']], msg.as_string())
601     s.quit()
602
603
604 (options, args) = parser.parse_args()
605
606 if options.retry:
607     if not options.rebase_master and options.rebase is None:
608         raise Exception('You can only use --retry if you also rebase')
609
610 testbase = os.path.join(options.testbase, "b%u" % (os.getpid(),))
611 test_master = os.path.join(testbase, "master")
612
613 if options.repository is not None:
614     repository = options.repository
615 else:
616     repository = os.getcwd()
617
618 gitroot = find_git_root(repository)
619 if gitroot is None:
620     raise Exception("Failed to find git root under %s" % repository)
621
622 # get the top commit message, for emails
623 if options.revision is not None:
624     revision = options.revision
625 else:
626     revision = "HEAD"
627
628 def get_top_commit_msg(reporoot):
629     return run_cmd(["git", "log", "-1"], dir=reporoot, output=True)
630
631 try:
632     os.makedirs(testbase)
633 except Exception, reason:
634     raise Exception("Unable to create %s : %s" % (testbase, reason))
635 cleanup_list.append(testbase)
636
637 if options.daemon:
638     logfile = os.path.join(testbase, "log")
639     print "Forking into the background, writing progress to %s" % logfile
640     daemonize(logfile)
641
642 while True:
643     try:
644         run_cmd(["rm", "-rf", test_master])
645         cleanup_list.append(test_master)
646         clone_gitroot(test_master, revision)
647     except:
648         cleanup()
649         raise
650
651     try:
652         if options.rebase is not None:
653             rebase_tree(options.rebase)
654         elif options.rebase_master:
655             rebase_tree(samba_master)
656         blist = BuildList(tasks, args)
657         if options.tail:
658             blist.start_tail()
659         (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
660         if status != 0 or errstr != "retry":
661             break
662         cleanup()
663     except:
664         cleanup()
665         raise
666
667 blist.kill_kids()
668 if options.tail:
669     print("waiting for tail to flush")
670     time.sleep(1)
671
672 if status == 0:
673     print errstr
674     if options.passcmd is not None:
675         print("Running passcmd: %s" % options.passcmd)
676         run_cmd(options.passcmd, dir=test_master, shell=True)
677     if options.pushto is not None:
678         push_to(options.pushto)
679     elif options.push_master:
680         push_to(samba_master_ssh)
681     if options.keeplogs:
682         blist.tarlogs("logs.tar.gz")
683         print("Logs in logs.tar.gz")
684     if options.always_email:
685         email_success(blist)
686     blist.remove_logs()
687     cleanup()
688     print(errstr)
689 else:
690     # something failed, gather a tar of the logs
691     blist.tarlogs("logs.tar.gz")
692
693     if options.email is not None:
694         email_failure(blist, status, failed_task, failed_stage, failed_tag,
695             errstr)
696
697     cleanup()
698     print(errstr)
699     print("Logs in logs.tar.gz")
700 sys.exit(status)