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