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