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