land: Attach test output files to result emails.
[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, dir=test_master)
452     run_cmd(["git", "fetch", "master"], show=True, dir=test_master)
453     if options.fix_whitespace:
454         run_cmd(["git", "rebase", "--whitespace=fix", "master/master"], show=True, dir=test_master)
455     else:
456         run_cmd(["git", "rebase", "master/master"], show=True, dir=test_master)
457     diff = run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"], dir=test_master, output=True)
458     if diff == '':
459         print("No differences between HEAD and master/master - exiting")
460         sys.exit(0)
461
462 def push_to(url):
463     print("Pushing to %s" % url)
464     if options.mark:
465         run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD", dir=test_master, shell=True)
466         # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
467         # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
468     run_cmd(["git", "remote", "add", "-t", "master", "pushto", url], show=True, dir=test_master)
469     run_cmd(["git", "push", "pushto", "+HEAD:master"], show=True, dir=test_master)
470
471 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
472
473 parser = OptionParser()
474 parser.add_option("", "--repository", help="repository to run tests for", default=None, type=str)
475 parser.add_option("", "--revision", help="revision to compile if not HEAD", default=None, type=str)
476 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
477 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
478 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
479 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
480                   default=def_testbase)
481 parser.add_option("", "--passcmd", help="command to run on success", default=None)
482 parser.add_option("", "--verbose", help="show all commands as they are run",
483                   default=False, action="store_true")
484 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
485                   default=None, type='str')
486 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
487                   default=False, action='store_true')
488 parser.add_option("", "--pushto", help="push to a git url on success",
489                   default=None, type='str')
490 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
491                   default=False, action='store_true')
492 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
493                   default=False, action="store_true")
494 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
495                   default=False, action="store_true")
496 parser.add_option("", "--retry", help="automatically retry if master changes",
497                   default=False, action="store_true")
498 parser.add_option("", "--email", help="send email to the given address on failure",
499                   type='str', default=None)
500 parser.add_option("", "--always-email", help="always send email, even on success",
501                   action="store_true")
502 parser.add_option("", "--daemon", help="daemonize after initial setup",
503                   action="store_true")
504 parser.add_option("", "--fail-slowly", help="continue running tests even after one has already failed",
505                   action="store_true")
506
507
508 def email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr):
509     '''send an email to options.email about the failure'''
510     user = os.getenv("USER")
511     text = '''
512 Dear Developer,
513
514 Your autobuild failed when trying to test %s with the following error:
515    %s
516
517 the autobuild has been abandoned. Please fix the error and resubmit.
518
519 You can see logs of the failed task here:
520
521   http://git.samba.org/%s/samba-autobuild/%s.stdout
522   http://git.samba.org/%s/samba-autobuild/%s.stderr
523
524 A summary of the autobuild process is here:
525
526   http://git.samba.org/%s/samba-autobuild/autobuild.log
527
528 or you can get full logs of all tasks in this job here:
529
530   http://git.samba.org/%s/samba-autobuild/logs.tar.gz
531
532 The top commit for the tree that was built was:
533
534 %s
535
536 ''' % (failed_task, errstr, user, failed_tag, user, failed_tag, user, user,
537        get_top_commit_msg(test_master))
538
539     msg = MIMEMultipart()
540     msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
541     msg['From'] = 'autobuild@samba.org'
542     msg['To'] = options.email
543
544     main = MIMEText(text)
545     msg.attach(main)
546
547     blist.attach_logs(msg)
548
549     s = smtplib.SMTP()
550     s.connect()
551     s.sendmail(msg['From'], [msg['To']], msg.as_string())
552     s.quit()
553
554 def email_success(blist):
555     '''send an email to options.email about a successful build'''
556     user = os.getenv("USER")
557     text = '''
558 Dear Developer,
559
560 Your autobuild has succeeded.
561
562 '''
563
564     if options.keeplogs:
565         text += '''
566
567 you can get full logs of all tasks in this job here:
568
569   http://git.samba.org/%s/samba-autobuild/logs.tar.gz
570
571 ''' % user
572
573     text += '''
574 The top commit for the tree that was built was:
575
576 %s
577 ''' % (get_top_commit_msg(test_master),)
578
579     msg = MIMEMultipart()
580     msg['Subject'] = 'autobuild success'
581     msg['From'] = 'autobuild@samba.org'
582     msg['To'] = options.email
583
584     main = MIMEText(text, 'plain')
585     msg.attach(main)
586
587     blist.attach_logs(msg)
588
589     s = smtplib.SMTP()
590     s.connect()
591     s.sendmail(msg['From'], [msg['To']], msg.as_string())
592     s.quit()
593
594
595 (options, args) = parser.parse_args()
596
597 if options.retry:
598     if not options.rebase_master and options.rebase is None:
599         raise Exception('You can only use --retry if you also rebase')
600
601 testbase = os.path.join(options.testbase, "b%u" % (os.getpid(),))
602 test_master = os.path.join(testbase, "master")
603
604 if options.repository is not None:
605     repository = options.repository
606 else:
607     repository = os.getcwd()
608
609 gitroot = find_git_root(repository)
610 if gitroot is None:
611     raise Exception("Failed to find git root under %s" % repository)
612
613 # get the top commit message, for emails
614 if options.revision is not None:
615     revision = options.revision
616 else:
617     revision = "HEAD"
618
619 def get_top_commit_msg(reporoot):
620     return run_cmd(["git", "log", "-1"], dir=reporoot, output=True)
621
622 try:
623     os.makedirs(testbase)
624 except Exception, reason:
625     raise Exception("Unable to create %s : %s" % (testbase, reason))
626 cleanup_list.append(testbase)
627
628 if options.daemon:
629     logfile = os.path.join(testbase, "log")
630     print "Forking into the background, writing progress to %s" % logfile
631     daemonize(logfile)
632
633 while True:
634     try:
635         run_cmd(["rm", "-rf", test_master])
636         cleanup_list.append(test_master)
637         clone_gitroot(test_master, revision)
638     except:
639         cleanup()
640         raise
641
642     try:
643         if options.rebase is not None:
644             rebase_tree(options.rebase)
645         elif options.rebase_master:
646             rebase_tree(samba_master)
647         blist = BuildList(tasks, args)
648         if options.tail:
649             blist.start_tail()
650         (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
651         if status != 0 or errstr != "retry":
652             break
653         cleanup()
654     except:
655         cleanup()
656         raise
657
658 blist.kill_kids()
659 if options.tail:
660     print("waiting for tail to flush")
661     time.sleep(1)
662
663 if status == 0:
664     print errstr
665     if options.passcmd is not None:
666         print("Running passcmd: %s" % options.passcmd)
667         run_cmd(options.passcmd, dir=test_master, shell=True)
668     if options.pushto is not None:
669         push_to(options.pushto)
670     elif options.push_master:
671         push_to(samba_master_ssh)
672     if options.keeplogs:
673         blist.tarlogs("logs.tar.gz")
674         print("Logs in logs.tar.gz")
675     if options.always_email:
676         email_success(blist)
677     blist.remove_logs()
678     cleanup()
679     print(errstr)
680 else:
681     # something failed, gather a tar of the logs
682     blist.tarlogs("logs.tar.gz")
683
684     if options.email is not None:
685         email_failure(blist, status, failed_task, failed_stage, failed_tag, errstr)
686
687     cleanup()
688     print(errstr)
689     print("Logs in logs.tar.gz")
690 sys.exit(status)