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