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