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