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