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