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