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