autobuild: Do not consider IDL.pm and Expr.pm changes to make a build bad
[amitay/samba.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 from distutils.sysconfig import get_python_lib
12
13 # This speeds up testing remarkably.
14 os.environ['TDB_NO_FSYNC'] = '1'
15
16 cleanup_list = []
17
18 builddirs = {
19     "ctdb"    : "ctdb",
20     "samba"  : ".",
21     "samba-ctdb" : ".",
22     "samba-libs"  : ".",
23     "ldb"     : "lib/ldb",
24     "tdb"     : "lib/tdb",
25     "talloc"  : "lib/talloc",
26     "replace" : "lib/replace",
27     "tevent"  : "lib/tevent",
28     "pidl"    : "pidl",
29     "pass"    : ".",
30     "fail"    : ".",
31     "retry"   : "."
32     }
33
34 defaulttasks = [ "ctdb", "samba", "samba-ctdb", "samba-libs", "ldb", "tdb", "talloc", "replace", "tevent", "pidl" ]
35
36 tasks = {
37     "ctdb" : [ ("random-sleep", "../script/random-sleep.sh 60 600", "text/plain"),
38                ("configure", "./configure ${PREFIX}", "text/plain"),
39                ("make", "make all", "text/plain"),
40                ("install", "make install", "text/plain"),
41                ("test", "make autotest", "text/plain"),
42                ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
43                ("clean", "make clean", "text/plain") ],
44
45     # We have 'test' before 'install' because, 'test' should work without 'install'
46     "samba" : [ ("configure", "./configure.developer --picky-developer ${PREFIX} --with-selftest-prefix=./bin/ab  --with-profiling-data", "text/plain"),
47                 ("make", "make -j", "text/plain"),
48                 ("test", "make test FAIL_IMMEDIATELY=1", "text/plain"),
49                 ("install", "make install", "text/plain"),
50                 ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
51                 ("clean", "make clean", "text/plain") ],
52
53     "samba-ctdb" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
54
55                      # make sure we have tdb around:
56                      ("tdb-configure", "cd lib/tdb && PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig ./configure --bundled-libraries=NONE --abi-check --enable-debug -C ${PREFIX}", "text/plain"),
57                      ("tdb-make", "cd lib/tdb && make", "text/plain"),
58                      ("tdb-install", "cd lib/tdb && make install", "text/plain"),
59
60
61                      # build samba with cluster support (also building ctdb):
62                      ("samba-configure", "PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=${PREFIX_DIR}/lib/pkgconfig:${PKG_CONFIG_PATH} ./configure.developer --picky-developer ${PREFIX} --with-selftest-prefix=./bin/ab --with-cluster-support --bundled-libraries=!tdb", "text/plain"),
63                      ("samba-make", "make", "text/plain"),
64                      ("samba-check", "./bin/smbd -b | grep CLUSTER_SUPPORT", "text/plain"),
65                      ("samba-install", "make install", "text/plain"),
66                      ("ctdb-check", "test -e ${PREFIX_DIR}/sbin/ctdbd", "text/plain"),
67
68                      # clean up:
69                      ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
70                      ("clean", "make clean", "text/plain"),
71                      ("ctdb-clean", "cd ./ctdb && make clean", "text/plain") ],
72
73     "samba-libs" : [
74                       ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
75                       ("talloc-configure", "cd lib/talloc && PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig ./configure --bundled-libraries=NONE --abi-check --enable-debug -C ${PREFIX}", "text/plain"),
76                       ("talloc-make", "cd lib/talloc && make", "text/plain"),
77                       ("talloc-install", "cd lib/talloc && make install", "text/plain"),
78
79                       ("tdb-configure", "cd lib/tdb && PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig ./configure --bundled-libraries=NONE --abi-check --enable-debug -C ${PREFIX}", "text/plain"),
80                       ("tdb-make", "cd lib/tdb && make", "text/plain"),
81                       ("tdb-install", "cd lib/tdb && make install", "text/plain"),
82
83                       ("tevent-configure", "cd lib/tevent && PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig ./configure --bundled-libraries=NONE --abi-check --enable-debug -C ${PREFIX}", "text/plain"),
84                       ("tevent-make", "cd lib/tevent && make", "text/plain"),
85                       ("tevent-install", "cd lib/tevent && make install", "text/plain"),
86
87                       ("ldb-configure", "cd lib/ldb && PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig ./configure --bundled-libraries=NONE --abi-check --enable-debug -C ${PREFIX}", "text/plain"),
88                       ("ldb-make", "cd lib/ldb && make", "text/plain"),
89                       ("ldb-install", "cd lib/ldb && make install", "text/plain"),
90
91                       ("configure", "PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig ./configure --bundled-libraries=!talloc,!tdb,!pytdb,!ldb,!pyldb,!tevent,!pytevent --abi-check --enable-debug -C ${PREFIX}", "text/plain"),
92                       ("make", "make", "text/plain"),
93                       ("install", "make install", "text/plain"),
94                       ("dist", "make dist", "text/plain")],
95
96     "ldb" : [
97               ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
98               ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
99               ("make", "make", "text/plain"),
100               ("install", "make install", "text/plain"),
101               ("test", "make test", "text/plain"),
102               ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
103               ("distcheck", "make distcheck", "text/plain"),
104               ("clean", "make clean", "text/plain") ],
105
106     "tdb" : [
107               ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
108               ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
109               ("make", "make", "text/plain"),
110               ("install", "make install", "text/plain"),
111               ("test", "make test", "text/plain"),
112               ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
113               ("distcheck", "make distcheck", "text/plain"),
114               ("clean", "make clean", "text/plain") ],
115
116     "talloc" : [
117                  ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
118                  ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
119                  ("make", "make", "text/plain"),
120                  ("install", "make install", "text/plain"),
121                  ("test", "make test", "text/plain"),
122                  ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
123                  ("distcheck", "make distcheck", "text/plain"),
124                  ("clean", "make clean", "text/plain") ],
125
126     "replace" : [
127                   ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
128                   ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
129                   ("make", "make", "text/plain"),
130                   ("install", "make install", "text/plain"),
131                   ("test", "make test", "text/plain"),
132                   ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
133                   ("distcheck", "make distcheck", "text/plain"),
134                   ("clean", "make clean", "text/plain") ],
135
136     "tevent" : [
137                  ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
138                  ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
139                  ("make", "make", "text/plain"),
140                  ("install", "make install", "text/plain"),
141                  ("test", "make test", "text/plain"),
142                  ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
143                  ("distcheck", "make distcheck", "text/plain"),
144                  ("clean", "make clean", "text/plain") ],
145
146     "pidl" : [
147                ("random-sleep", "../script/random-sleep.sh 60 600", "text/plain"),
148                ("configure", "perl Makefile.PL PREFIX=${PREFIX_DIR}", "text/plain"),
149                ("touch", "touch *.yp", "text/plain"),
150                ("make", "make", "text/plain"),
151                ("test", "make test", "text/plain"),
152                ("install", "make install", "text/plain"),
153                ("checkout-yapp-generated", "git checkout lib/Parse/Pidl/IDL.pm lib/Parse/Pidl/Expr.pm", "text/plain"),
154                ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
155                ("clean", "make clean", "text/plain") ],
156
157     # these are useful for debugging autobuild
158     'pass' : [ ("pass", 'echo passing && /bin/true', "text/plain") ],
159     'fail' : [ ("fail", 'echo failing && /bin/false', "text/plain") ]
160 }
161
162 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
163     if show is None:
164         show = options.verbose
165     if show:
166         print("Running: '%s' in '%s'" % (cmd, dir))
167     if output:
168         return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
169     elif checkfail:
170         return check_call(cmd, shell=True, cwd=dir)
171     else:
172         return call(cmd, shell=True, cwd=dir)
173
174
175 class builder(object):
176     '''handle build of one directory'''
177
178     def __init__(self, name, sequence):
179         self.name = name
180         self.dir = builddirs[name]
181
182         self.tag = self.name.replace('/', '_')
183         self.sequence = sequence
184         self.next = 0
185         self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
186         self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
187         if options.verbose:
188             print("stdout for %s in %s" % (self.name, self.stdout_path))
189             print("stderr for %s in %s" % (self.name, self.stderr_path))
190         run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
191         self.stdout = open(self.stdout_path, 'w')
192         self.stderr = open(self.stderr_path, 'w')
193         self.stdin  = open("/dev/null", 'r')
194         self.sdir = "%s/%s" % (testbase, self.tag)
195         self.prefix = "%s/prefix/%s" % (testbase, self.tag)
196         run_cmd("rm -rf %s" % self.sdir)
197         cleanup_list.append(self.sdir)
198         cleanup_list.append(self.prefix)
199         os.makedirs(self.sdir)
200         run_cmd("rm -rf %s" % self.sdir)
201         run_cmd("git clone --recursive --shared %s %s" % (test_master, self.sdir), dir=test_master, show=True)
202         self.start_next()
203
204     def start_next(self):
205         if self.next == len(self.sequence):
206             print '%s: Completed OK' % self.name
207             self.done = True
208             return
209         (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
210         self.cmd = self.cmd.replace("${PYTHON_PREFIX}", get_python_lib(standard_lib=1, prefix=self.prefix))
211         self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
212         self.cmd = self.cmd.replace("${PREFIX_DIR}", "%s" % self.prefix)
213 #        if self.output_mime_type == "text/x-subunit":
214 #            self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
215         print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
216         cwd = os.getcwd()
217         os.chdir("%s/%s" % (self.sdir, self.dir))
218         self.proc = Popen(self.cmd, shell=True,
219                           stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
220         os.chdir(cwd)
221         self.next += 1
222
223
224 class buildlist(object):
225     '''handle build of multiple directories'''
226
227     def __init__(self, tasklist, tasknames, rebase_url, rebase_branch="master"):
228         global tasks
229         self.tlist = []
230         self.tail_proc = None
231         self.retry = None
232         if tasknames == []:
233             tasknames = defaulttasks
234         else:
235             # If we are only running one test,
236             # do not sleep randomly to wait for it to start
237             os.environ['AUTOBUILD_RANDOM_SLEEP_OVERRIDE'] = '1'
238
239         for n in tasknames:
240             b = builder(n, tasks[n])
241             self.tlist.append(b)
242         if options.retry:
243             rebase_remote = "rebaseon"
244             retry_task = [ ("retry",
245                             '''set -e
246                             git remote add -t %s %s %s
247                             git fetch %s
248                             while :; do
249                               sleep 60
250                               git describe %s/%s > old_remote_branch.desc
251                               git fetch %s
252                               git describe %s/%s > remote_branch.desc
253                               diff old_remote_branch.desc remote_branch.desc
254                             done
255                            ''' % (
256                                rebase_branch, rebase_remote, rebase_url,
257                                rebase_remote,
258                                rebase_remote, rebase_branch,
259                                rebase_remote,
260                                rebase_remote, rebase_branch
261                            ),
262                            "test/plain" ) ]
263
264             self.retry = builder('retry', retry_task)
265             self.need_retry = False
266
267     def kill_kids(self):
268         if self.tail_proc is not None:
269             self.tail_proc.terminate()
270             self.tail_proc.wait()
271             self.tail_proc = None
272         if self.retry is not None:
273             self.retry.proc.terminate()
274             self.retry.proc.wait()
275             self.retry = None
276         for b in self.tlist:
277             if b.proc is not None:
278                 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
279                 b.proc.terminate()
280                 b.proc.wait()
281                 b.proc = None
282
283     def wait_one(self):
284         while True:
285             none_running = True
286             for b in self.tlist:
287                 if b.proc is None:
288                     continue
289                 none_running = False
290                 b.status = b.proc.poll()
291                 if b.status is None:
292                     continue
293                 b.proc = None
294                 return b
295             if options.retry:
296                 ret = self.retry.proc.poll()
297                 if ret is not None:
298                     self.need_retry = True
299                     self.retry = None
300                     return None
301             if none_running:
302                 return None
303             time.sleep(0.1)
304
305     def run(self):
306         while True:
307             b = self.wait_one()
308             if options.retry and self.need_retry:
309                 self.kill_kids()
310                 print("retry needed")
311                 return (0, None, None, None, "retry")
312             if b is None:
313                 break
314             if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
315                 self.kill_kids()
316                 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
317             b.start_next()
318         self.kill_kids()
319         return (0, None, None, None, "All OK")
320
321     def tarlogs(self, fname):
322         tar = tarfile.open(fname, "w:gz")
323         for b in self.tlist:
324             tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
325             tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
326         if os.path.exists("autobuild.log"):
327             tar.add("autobuild.log")
328         tar.close()
329
330     def remove_logs(self):
331         for b in self.tlist:
332             os.unlink(b.stdout_path)
333             os.unlink(b.stderr_path)
334
335     def start_tail(self):
336         cwd = os.getcwd()
337         cmd = "tail -f *.stdout *.stderr"
338         os.chdir(gitroot)
339         self.tail_proc = Popen(cmd, shell=True)
340         os.chdir(cwd)
341
342
343 def cleanup():
344     if options.nocleanup:
345         return
346     print("Cleaning up ....")
347     for d in cleanup_list:
348         run_cmd("rm -rf %s" % d)
349
350
351 def find_git_root():
352     '''get to the top of the git repo'''
353     p=os.getcwd()
354     while p != '/':
355         if os.path.isdir(os.path.join(p, ".git")):
356             return p
357         p = os.path.abspath(os.path.join(p, '..'))
358     return None
359
360
361 def daemonize(logfile):
362     pid = os.fork()
363     if pid == 0: # Parent
364         os.setsid()
365         pid = os.fork()
366         if pid != 0: # Actual daemon
367             os._exit(0)
368     else: # Grandparent
369         os._exit(0)
370
371     import resource      # Resource usage information.
372     maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
373     if maxfd == resource.RLIM_INFINITY:
374         maxfd = 1024 # Rough guess at maximum number of open file descriptors.
375     for fd in range(0, maxfd):
376         try:
377             os.close(fd)
378         except OSError:
379             pass
380     os.open(logfile, os.O_RDWR | os.O_CREAT)
381     os.dup2(0, 1)
382     os.dup2(0, 2)
383
384 def write_pidfile(fname):
385     '''write a pid file, cleanup on exit'''
386     f = open(fname, mode='w')
387     f.write("%u\n" % os.getpid())
388     f.close()
389
390
391 def rebase_tree(rebase_url, rebase_branch = "master"):
392     rebase_remote = "rebaseon"
393     print("Rebasing on %s" % rebase_url)
394     run_cmd("git describe HEAD", show=True, dir=test_master)
395     run_cmd("git remote add -t %s %s %s" %
396             (rebase_branch, rebase_remote, rebase_url),
397             show=True, dir=test_master)
398     run_cmd("git fetch %s" % rebase_remote, show=True, dir=test_master)
399     if options.fix_whitespace:
400         run_cmd("git rebase --force-rebase --whitespace=fix %s/%s" %
401                 (rebase_remote, rebase_branch),
402                 show=True, dir=test_master)
403     else:
404         run_cmd("git rebase --force-rebase %s/%s" %
405                 (rebase_remote, rebase_branch),
406                 show=True, dir=test_master)
407     diff = run_cmd("git --no-pager diff HEAD %s/%s" %
408                    (rebase_remote, rebase_branch),
409                    dir=test_master, output=True)
410     if diff == '':
411         print("No differences between HEAD and %s/%s - exiting" %
412               (rebase_remote, rebase_branch))
413         sys.exit(0)
414     run_cmd("git describe %s/%s" %
415             (rebase_remote, rebase_branch),
416             show=True, dir=test_master)
417     run_cmd("git describe HEAD", show=True, dir=test_master)
418     run_cmd("git --no-pager diff --stat HEAD %s/%s" %
419             (rebase_remote, rebase_branch),
420             show=True, dir=test_master)
421
422 def push_to(push_url, push_branch = "master"):
423     push_remote = "pushto"
424     print("Pushing to %s" % push_url)
425     if options.mark:
426         run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
427         run_cmd("git commit --amend -c HEAD", dir=test_master)
428         # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
429         # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
430     run_cmd("git remote add -t %s %s %s" %
431             (push_branch, push_remote, push_url),
432             show=True, dir=test_master)
433     run_cmd("git push %s +HEAD:%s" %
434             (push_remote, push_branch),
435             show=True, dir=test_master)
436
437 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
438
439 gitroot = find_git_root()
440 if gitroot is None:
441     raise Exception("Failed to find git root")
442
443 parser = OptionParser()
444 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
445 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
446 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
447 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
448                   default=def_testbase)
449 parser.add_option("", "--passcmd", help="command to run on success", default=None)
450 parser.add_option("", "--verbose", help="show all commands as they are run",
451                   default=False, action="store_true")
452 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
453                   default=None, type='str')
454 parser.add_option("", "--pushto", help="push to a git url on success",
455                   default=None, type='str')
456 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
457                   default=False, action="store_true")
458 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
459                   default=False, action="store_true")
460 parser.add_option("", "--retry", help="automatically retry if master changes",
461                   default=False, action="store_true")
462 parser.add_option("", "--email", help="send email to the given address on failure",
463                   type='str', default=None)
464 parser.add_option("", "--always-email", help="always send email, even on success",
465                   action="store_true")
466 parser.add_option("", "--daemon", help="daemonize after initial setup",
467                   action="store_true")
468 parser.add_option("", "--branch", help="the branch to work on (default=master)",
469                   default="master", type='str')
470 parser.add_option("", "--log-base", help="location where the logs can be found (default=cwd)",
471                   default=gitroot, type='str')
472
473 def email_failure(status, failed_task, failed_stage, failed_tag, errstr, log_base=None):
474     '''send an email to options.email about the failure'''
475     user = os.getenv("USER")
476     if log_base is None:
477         log_base = gitroot
478     text = '''
479 Dear Developer,
480
481 Your autobuild failed when trying to test %s with the following error:
482    %s
483
484 the autobuild has been abandoned. Please fix the error and resubmit.
485
486 A summary of the autobuild process is here:
487
488   %s/autobuild.log
489 ''' % (failed_task, errstr, log_base)
490     
491     if failed_task != 'rebase':
492         text += '''
493 You can see logs of the failed task here:
494
495   %s/%s.stdout
496   %s/%s.stderr
497
498 or you can get full logs of all tasks in this job here:
499
500   %s/logs.tar.gz
501
502 The top commit for the tree that was built was:
503
504 %s
505
506 ''' % (log_base, failed_tag, log_base, failed_tag, log_base, top_commit_msg)
507     msg = MIMEText(text)
508     msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
509     msg['From'] = 'autobuild@samba.org'
510     msg['To'] = options.email
511
512     s = smtplib.SMTP()
513     s.connect()
514     s.sendmail(msg['From'], [msg['To']], msg.as_string())
515     s.quit()
516
517 def email_success(log_base=None):
518     '''send an email to options.email about a successful build'''
519     user = os.getenv("USER")
520     if log_base is None:
521         log_base = gitroot
522     text = '''
523 Dear Developer,
524
525 Your autobuild has succeeded.
526
527 '''
528
529     if options.keeplogs:
530         text += '''
531
532 you can get full logs of all tasks in this job here:
533
534   %s/logs.tar.gz
535
536 ''' % log_base
537
538     text += '''
539 The top commit for the tree that was built was:
540
541 %s
542 ''' % top_commit_msg
543
544     msg = MIMEText(text)
545     msg['Subject'] = 'autobuild success'
546     msg['From'] = 'autobuild@samba.org'
547     msg['To'] = options.email
548
549     s = smtplib.SMTP()
550     s.connect()
551     s.sendmail(msg['From'], [msg['To']], msg.as_string())
552     s.quit()
553
554
555 (options, args) = parser.parse_args()
556
557 if options.retry:
558     if options.rebase is None:
559         raise Exception('You can only use --retry if you also rebase')
560
561 testbase = "%s/b%u" % (options.testbase, os.getpid())
562 test_master = "%s/master" % testbase
563
564 # get the top commit message, for emails
565 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
566
567 try:
568     os.makedirs(testbase)
569 except Exception, reason:
570     raise Exception("Unable to create %s : %s" % (testbase, reason))
571 cleanup_list.append(testbase)
572
573 if options.daemon:
574     logfile = os.path.join(testbase, "log")
575     print "Forking into the background, writing progress to %s" % logfile
576     daemonize(logfile)
577
578 write_pidfile(gitroot + "/autobuild.pid")
579
580 while True:
581     try:
582         run_cmd("rm -rf %s" % test_master)
583         cleanup_list.append(test_master)
584         run_cmd("git clone --recursive --shared %s %s" % (gitroot, test_master), show=True, dir=gitroot)
585     except Exception:
586         cleanup()
587         raise
588
589     try:
590         try:
591             if options.rebase is not None:
592                 rebase_tree(options.rebase, rebase_branch=options.branch)
593         except Exception:
594             cleanup_list.append(gitroot + "/autobuild.pid")
595             cleanup()
596             email_failure(-1, 'rebase', 'rebase', 'rebase',
597                           'rebase on %s failed' % options.branch,
598                           log_base=options.log_base)
599             sys.exit(1)
600         blist = buildlist(tasks, args, options.rebase, rebase_branch=options.branch)
601         if options.tail:
602             blist.start_tail()
603         (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
604         if status != 0 or errstr != "retry":
605             break
606         cleanup()
607     except Exception:
608         cleanup()
609         raise
610
611 cleanup_list.append(gitroot + "/autobuild.pid")
612
613 blist.kill_kids()
614 if options.tail:
615     print("waiting for tail to flush")
616     time.sleep(1)
617
618 if status == 0:
619     print errstr
620     if options.passcmd is not None:
621         print("Running passcmd: %s" % options.passcmd)
622         run_cmd(options.passcmd, dir=test_master)
623     if options.pushto is not None:
624         push_to(options.pushto, push_branch=options.branch)
625     if options.keeplogs:
626         blist.tarlogs("logs.tar.gz")
627         print("Logs in logs.tar.gz")
628     if options.always_email:
629         email_success(log_base=options.log_base)
630     blist.remove_logs()
631     cleanup()
632     print(errstr)
633     sys.exit(0)
634
635 # something failed, gather a tar of the logs
636 blist.tarlogs("logs.tar.gz")
637
638 if options.email is not None:
639     email_failure(status, failed_task, failed_stage, failed_tag, errstr, log_base=options.log_base)
640
641 cleanup()
642 print(errstr)
643 print("Logs in logs.tar.gz")
644 sys.exit(status)