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