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