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