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