autobuild: Use cp --recursive --link --archive
[kai/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 import email
11 from email.mime.text import MIMEText
12 from email.mime.base import MIMEBase
13 from email.mime.application import MIMEApplication
14 from email.mime.multipart import MIMEMultipart
15 from distutils.sysconfig import get_python_lib
16 import platform
17
18 # This speeds up testing remarkably.
19 os.environ['TDB_NO_FSYNC'] = '1'
20
21 cleanup_list = []
22
23 builddirs = {
24     "ctdb"    : "ctdb",
25     "samba"  : ".",
26     "samba-xc" : ".",
27     "samba-ctdb" : ".",
28     "samba-libs"  : ".",
29     "ldb"     : "lib/ldb",
30     "tdb"     : "lib/tdb",
31     "talloc"  : "lib/talloc",
32     "replace" : "lib/replace",
33     "tevent"  : "lib/tevent",
34     "pidl"    : "pidl",
35     "pass"    : ".",
36     "fail"    : ".",
37     "retry"   : "."
38     }
39
40 defaulttasks = [ "ctdb", "samba", "samba-xc", "samba-ctdb", "samba-libs", "ldb", "tdb", "talloc", "replace", "tevent", "pidl" ]
41
42 samba_configure_params = " --picky-developer ${PREFIX} --with-profiling-data"
43
44 samba_libs_envvars =  "PYTHONPATH=${PYTHON_PREFIX}/site-packages:$PYTHONPATH"
45 samba_libs_envvars += " PKG_CONFIG_PATH=$PKG_CONFIG_PATH:${PREFIX_DIR}/lib/pkgconfig"
46 samba_libs_envvars += " ADDITIONAL_CFLAGS='-Wmissing-prototypes'"
47 samba_libs_configure_base = samba_libs_envvars + " ./configure --abi-check --enable-debug --picky-developer -C ${PREFIX}"
48 samba_libs_configure_libs = samba_libs_configure_base + " --bundled-libraries=NONE"
49 samba_libs_configure_samba = samba_libs_configure_base + " --bundled-libraries=!talloc,!pytalloc-util,!tdb,!pytdb,!ldb,!pyldb,!pyldb-util,!tevent,!pytevent"
50
51 tasks = {
52     "ctdb" : [ ("random-sleep", "../script/random-sleep.sh 60 600", "text/plain"),
53                ("configure", "./configure ${PREFIX}", "text/plain"),
54                ("make", "make all", "text/plain"),
55                ("install", "make install", "text/plain"),
56                ("test", "make autotest", "text/plain"),
57                ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
58                ("clean", "make clean", "text/plain") ],
59
60     # We have 'test' before 'install' because, 'test' should work without 'install'
61     "samba" : [ ("configure", "./configure.developer --with-selftest-prefix=./bin/ab" + samba_configure_params, "text/plain"),
62                 ("make", "make -j", "text/plain"),
63                 ("test", "make test FAIL_IMMEDIATELY=1", "text/plain"),
64                 ("install", "make install", "text/plain"),
65                 ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
66                 ("clean", "make clean", "text/plain") ],
67
68     # Test cross-compile infrastructure
69     "samba-xc" : [ ("configure-native", "./configure.developer --with-selftest-prefix=./bin/ab" + samba_configure_params, "text/plain"),
70                    ("configure-cross-execute", "./configure.developer -b ./bin-xe --cross-compile --cross-execute=script/identity_cc.sh" \
71                     " --cross-answers=./bin-xe/cross-answers.txt --with-selftest-prefix=./bin-xe/ab" + samba_configure_params, "text/plain"),
72                    ("configure-cross-answers", "./configure.developer -b ./bin-xa --cross-compile" \
73                     " --cross-answers=./bin-xe/cross-answers.txt --with-selftest-prefix=./bin-xa/ab" + samba_configure_params, "text/plain"),
74                    ("compare-results", "script/compare_cc_results.py ./bin/c4che/default.cache.py ./bin-xe/c4che/default.cache.py ./bin-xa/c4che/default.cache.py", "text/plain")],
75
76
77     "samba-ctdb" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
78
79                      # make sure we have tdb around:
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
85                      # build samba with cluster support (also building ctdb):
86                      ("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"),
87                      ("samba-make", "make", "text/plain"),
88                      ("samba-check", "./bin/smbd -b | grep CLUSTER_SUPPORT", "text/plain"),
89                      ("samba-install", "make install", "text/plain"),
90                      ("ctdb-check", "test -e ${PREFIX_DIR}/sbin/ctdbd", "text/plain"),
91
92                      # clean up:
93                      ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
94                      ("clean", "make clean", "text/plain"),
95                      ("ctdb-clean", "cd ./ctdb && make clean", "text/plain") ],
96
97     "samba-libs" : [
98                       ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
99                       ("talloc-configure", "cd lib/talloc && " + samba_libs_configure_libs, "text/plain"),
100                       ("talloc-make", "cd lib/talloc && make", "text/plain"),
101                       ("talloc-install", "cd lib/talloc && make install", "text/plain"),
102
103                       ("tdb-configure", "cd lib/tdb && " + samba_libs_configure_libs, "text/plain"),
104                       ("tdb-make", "cd lib/tdb && make", "text/plain"),
105                       ("tdb-install", "cd lib/tdb && make install", "text/plain"),
106
107                       ("tevent-configure", "cd lib/tevent && " + samba_libs_configure_libs, "text/plain"),
108                       ("tevent-make", "cd lib/tevent && make", "text/plain"),
109                       ("tevent-install", "cd lib/tevent && make install", "text/plain"),
110
111                       ("ldb-configure", "cd lib/ldb && " + samba_libs_configure_libs, "text/plain"),
112                       ("ldb-make", "cd lib/ldb && make", "text/plain"),
113                       ("ldb-install", "cd lib/ldb && make install", "text/plain"),
114
115                       ("nondevel-configure", "./configure ${PREFIX}", "text/plain"),
116                       ("nondevel-make", "make -j", "text/plain"),
117                       ("nondevel-check", "./bin/smbd -b | grep WITH_NTVFS_FILESERVER && exit 1; exit 0", "text/plain"),
118                       ("nondevel-install", "make install", "text/plain"),
119                       ("nondevel-dist", "make dist", "text/plain"),
120
121                       # retry with all modules shared
122                       ("allshared-distclean", "make distclean", "text/plain"),
123                       ("allshared-configure", samba_libs_configure_samba + " --with-shared-modules=ALL", "text/plain"),
124                       ("allshared-make", "make", "text/plain"),
125
126                       # retry with all modules static
127                       ("allstatic-distclean", "make distclean", "text/plain"),
128                       ("allstatic-configure", samba_libs_configure_samba + " --with-static-modules=ALL", "text/plain"),
129                       ("allstatic-make", "make", "text/plain"),
130
131                       # retry without any required modules
132                       ("none-distclean", "make distclean", "text/plain"),
133                       ("none-configure", samba_libs_configure_samba + " --with-static-modules=!FORCED,!DEFAULT --with-shared-modules=!FORCED,!DEFAULT", "text/plain"),
134                       ("none-make", "make", "text/plain"),
135
136                       # retry with nonshared smbd and smbtorture
137                       ("nonshared-distclean", "make distclean", "text/plain"),
138                       ("nonshared-configure", samba_libs_configure_base + " --bundled-libraries=talloc,tdb,pytdb,ldb,pyldb,tevent,pytevent --with-static-modules=ALL --nonshared-binary=smbtorture,smbd/smbd", "text/plain"),
139                       ("nonshared-make", "make", "text/plain")],
140
141     "ldb" : [
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     "tdb" : [
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     "talloc" : [
162                  ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
163                  ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
164                  ("make", "make", "text/plain"),
165                  ("install", "make install", "text/plain"),
166                  ("test", "make test", "text/plain"),
167                  ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
168                  ("distcheck", "make distcheck", "text/plain"),
169                  ("clean", "make clean", "text/plain") ],
170
171     "replace" : [
172                   ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
173                   ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
174                   ("make", "make", "text/plain"),
175                   ("install", "make install", "text/plain"),
176                   ("test", "make test", "text/plain"),
177                   ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
178                   ("distcheck", "make distcheck", "text/plain"),
179                   ("clean", "make clean", "text/plain") ],
180
181     "tevent" : [
182                  ("random-sleep", "../../script/random-sleep.sh 60 600", "text/plain"),
183                  ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
184                  ("make", "make", "text/plain"),
185                  ("install", "make install", "text/plain"),
186                  ("test", "make test", "text/plain"),
187                  ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
188                  ("distcheck", "make distcheck", "text/plain"),
189                  ("clean", "make clean", "text/plain") ],
190
191     "pidl" : [
192                ("random-sleep", "../script/random-sleep.sh 60 600", "text/plain"),
193                ("configure", "perl Makefile.PL PREFIX=${PREFIX_DIR}", "text/plain"),
194                ("touch", "touch *.yp", "text/plain"),
195                ("make", "make", "text/plain"),
196                ("test", "make test", "text/plain"),
197                ("install", "make install", "text/plain"),
198                ("checkout-yapp-generated", "git checkout lib/Parse/Pidl/IDL.pm lib/Parse/Pidl/Expr.pm", "text/plain"),
199                ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
200                ("clean", "make clean", "text/plain") ],
201
202     # these are useful for debugging autobuild
203     'pass' : [ ("pass", 'echo passing && /bin/true', "text/plain") ],
204     'fail' : [ ("fail", 'echo failing && /bin/false', "text/plain") ]
205 }
206
207 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
208     if show is None:
209         show = options.verbose
210     if show:
211         print("Running: '%s' in '%s'" % (cmd, dir))
212     if output:
213         return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
214     elif checkfail:
215         return check_call(cmd, shell=True, cwd=dir)
216     else:
217         return call(cmd, shell=True, cwd=dir)
218
219
220 class builder(object):
221     '''handle build of one directory'''
222
223     def __init__(self, name, sequence, cp=True):
224         self.name = name
225         self.dir = builddirs[name]
226
227         self.tag = self.name.replace('/', '_')
228         self.sequence = sequence
229         self.next = 0
230         self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
231         self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
232         if options.verbose:
233             print("stdout for %s in %s" % (self.name, self.stdout_path))
234             print("stderr for %s in %s" % (self.name, self.stderr_path))
235         run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
236         self.stdout = open(self.stdout_path, 'w')
237         self.stderr = open(self.stderr_path, 'w')
238         self.stdin  = open("/dev/null", 'r')
239         self.sdir = "%s/%s" % (testbase, self.tag)
240         self.prefix = "%s/prefix/%s" % (testbase, self.tag)
241         run_cmd("rm -rf %s" % self.sdir)
242         cleanup_list.append(self.sdir)
243         cleanup_list.append(self.prefix)
244         os.makedirs(self.sdir)
245         run_cmd("rm -rf %s" % self.sdir)
246         if cp:
247             run_cmd("cp --recursive --link --archive %s %s" % (test_master, self.sdir), dir=test_master, show=True)
248         else:
249             run_cmd("git clone --recursive --shared %s %s" % (test_master, self.sdir), dir=test_master, show=True)
250         self.start_next()
251
252     def start_next(self):
253         if self.next == len(self.sequence):
254             print '%s: Completed OK' % self.name
255             self.done = True
256             return
257         (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
258         self.cmd = self.cmd.replace("${PYTHON_PREFIX}", get_python_lib(standard_lib=1, prefix=self.prefix))
259         self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
260         self.cmd = self.cmd.replace("${PREFIX_DIR}", "%s" % self.prefix)
261 #        if self.output_mime_type == "text/x-subunit":
262 #            self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
263         print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
264         cwd = os.getcwd()
265         os.chdir("%s/%s" % (self.sdir, self.dir))
266         self.proc = Popen(self.cmd, shell=True,
267                           stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
268         os.chdir(cwd)
269         self.next += 1
270
271
272 class buildlist(object):
273     '''handle build of multiple directories'''
274
275     def __init__(self, tasklist, tasknames, rebase_url, rebase_branch="master"):
276         global tasks
277         self.tlist = []
278         self.tail_proc = None
279         self.retry = None
280         if tasknames == []:
281             tasknames = defaulttasks
282         else:
283             # If we are only running one test,
284             # do not sleep randomly to wait for it to start
285             os.environ['AUTOBUILD_RANDOM_SLEEP_OVERRIDE'] = '1'
286
287         for n in tasknames:
288             b = builder(n, tasks[n], cp=n is not "pidl")
289             self.tlist.append(b)
290         if options.retry:
291             rebase_remote = "rebaseon"
292             retry_task = [ ("retry",
293                             '''set -e
294                             git remote add -t %s %s %s
295                             git fetch %s
296                             while :; do
297                               sleep 60
298                               git describe %s/%s > old_remote_branch.desc
299                               git fetch %s
300                               git describe %s/%s > remote_branch.desc
301                               diff old_remote_branch.desc remote_branch.desc
302                             done
303                            ''' % (
304                                rebase_branch, rebase_remote, rebase_url,
305                                rebase_remote,
306                                rebase_remote, rebase_branch,
307                                rebase_remote,
308                                rebase_remote, rebase_branch
309                            ),
310                            "test/plain" ) ]
311
312             self.retry = builder('retry', retry_task, cp=False)
313             self.need_retry = False
314
315     def kill_kids(self):
316         if self.tail_proc is not None:
317             self.tail_proc.terminate()
318             self.tail_proc.wait()
319             self.tail_proc = None
320         if self.retry is not None:
321             self.retry.proc.terminate()
322             self.retry.proc.wait()
323             self.retry = None
324         for b in self.tlist:
325             if b.proc is not None:
326                 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
327                 b.proc.terminate()
328                 b.proc.wait()
329                 b.proc = None
330
331     def wait_one(self):
332         while True:
333             none_running = True
334             for b in self.tlist:
335                 if b.proc is None:
336                     continue
337                 none_running = False
338                 b.status = b.proc.poll()
339                 if b.status is None:
340                     continue
341                 b.proc = None
342                 return b
343             if options.retry:
344                 ret = self.retry.proc.poll()
345                 if ret is not None:
346                     self.need_retry = True
347                     self.retry = None
348                     return None
349             if none_running:
350                 return None
351             time.sleep(0.1)
352
353     def run(self):
354         while True:
355             b = self.wait_one()
356             if options.retry and self.need_retry:
357                 self.kill_kids()
358                 print("retry needed")
359                 return (0, None, None, None, "retry")
360             if b is None:
361                 break
362             if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
363                 self.kill_kids()
364                 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
365             b.start_next()
366         self.kill_kids()
367         return (0, None, None, None, "All OK")
368
369     def write_system_info(self):
370         filename = 'system-info.txt'
371         f = open(filename, 'w')
372         for cmd in ['uname -a', 'free', 'cat /proc/cpuinfo']:
373             print >>f, '### %s' % cmd
374             print >>f, run_cmd(cmd, output=True, checkfail=False)
375             print >>f
376         f.close()
377         return filename
378
379     def tarlogs(self, fname):
380         tar = tarfile.open(fname, "w:gz")
381         for b in self.tlist:
382             tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
383             tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
384         if os.path.exists("autobuild.log"):
385             tar.add("autobuild.log")
386         sys_info = self.write_system_info()
387         tar.add(sys_info)
388         tar.close()
389
390     def remove_logs(self):
391         for b in self.tlist:
392             os.unlink(b.stdout_path)
393             os.unlink(b.stderr_path)
394
395     def start_tail(self):
396         cwd = os.getcwd()
397         cmd = "tail -f *.stdout *.stderr"
398         os.chdir(gitroot)
399         self.tail_proc = Popen(cmd, shell=True)
400         os.chdir(cwd)
401
402
403 def cleanup():
404     if options.nocleanup:
405         return
406     print("Cleaning up ....")
407     for d in cleanup_list:
408         run_cmd("rm -rf %s" % d)
409
410
411 def find_git_root():
412     '''get to the top of the git repo'''
413     p=os.getcwd()
414     while p != '/':
415         if os.path.isdir(os.path.join(p, ".git")):
416             return p
417         p = os.path.abspath(os.path.join(p, '..'))
418     return None
419
420
421 def daemonize(logfile):
422     pid = os.fork()
423     if pid == 0: # Parent
424         os.setsid()
425         pid = os.fork()
426         if pid != 0: # Actual daemon
427             os._exit(0)
428     else: # Grandparent
429         os._exit(0)
430
431     import resource      # Resource usage information.
432     maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
433     if maxfd == resource.RLIM_INFINITY:
434         maxfd = 1024 # Rough guess at maximum number of open file descriptors.
435     for fd in range(0, maxfd):
436         try:
437             os.close(fd)
438         except OSError:
439             pass
440     os.open(logfile, os.O_RDWR | os.O_CREAT)
441     os.dup2(0, 1)
442     os.dup2(0, 2)
443
444 def write_pidfile(fname):
445     '''write a pid file, cleanup on exit'''
446     f = open(fname, mode='w')
447     f.write("%u\n" % os.getpid())
448     f.close()
449
450
451 def rebase_tree(rebase_url, rebase_branch = "master"):
452     rebase_remote = "rebaseon"
453     print("Rebasing on %s" % rebase_url)
454     run_cmd("git describe HEAD", show=True, dir=test_master)
455     run_cmd("git remote add -t %s %s %s" %
456             (rebase_branch, rebase_remote, rebase_url),
457             show=True, dir=test_master)
458     run_cmd("git fetch %s" % rebase_remote, show=True, dir=test_master)
459     if options.fix_whitespace:
460         run_cmd("git rebase --force-rebase --whitespace=fix %s/%s" %
461                 (rebase_remote, rebase_branch),
462                 show=True, dir=test_master)
463     else:
464         run_cmd("git rebase --force-rebase %s/%s" %
465                 (rebase_remote, rebase_branch),
466                 show=True, dir=test_master)
467     diff = run_cmd("git --no-pager diff HEAD %s/%s" %
468                    (rebase_remote, rebase_branch),
469                    dir=test_master, output=True)
470     if diff == '':
471         print("No differences between HEAD and %s/%s - exiting" %
472               (rebase_remote, rebase_branch))
473         sys.exit(0)
474     run_cmd("git describe %s/%s" %
475             (rebase_remote, rebase_branch),
476             show=True, dir=test_master)
477     run_cmd("git describe HEAD", show=True, dir=test_master)
478     run_cmd("git --no-pager diff --stat HEAD %s/%s" %
479             (rebase_remote, rebase_branch),
480             show=True, dir=test_master)
481
482 def push_to(push_url, push_branch = "master"):
483     push_remote = "pushto"
484     print("Pushing to %s" % push_url)
485     if options.mark:
486         run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
487         run_cmd("git commit --amend -c HEAD", dir=test_master)
488         # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
489         # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
490     run_cmd("git remote add -t %s %s %s" %
491             (push_branch, push_remote, push_url),
492             show=True, dir=test_master)
493     run_cmd("git push %s +HEAD:%s" %
494             (push_remote, push_branch),
495             show=True, dir=test_master)
496
497 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
498
499 gitroot = find_git_root()
500 if gitroot is None:
501     raise Exception("Failed to find git root")
502
503 parser = OptionParser()
504 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
505 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
506 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
507 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
508                   default=def_testbase)
509 parser.add_option("", "--passcmd", help="command to run on success", default=None)
510 parser.add_option("", "--verbose", help="show all commands as they are run",
511                   default=False, action="store_true")
512 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
513                   default=None, type='str')
514 parser.add_option("", "--pushto", help="push to a git url on success",
515                   default=None, type='str')
516 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
517                   default=False, action="store_true")
518 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
519                   default=False, action="store_true")
520 parser.add_option("", "--retry", help="automatically retry if master changes",
521                   default=False, action="store_true")
522 parser.add_option("", "--email", help="send email to the given address on failure",
523                   type='str', default=None)
524 parser.add_option("", "--email-from", help="send email from the given address",
525                   type='str', default="autobuild@samba.org")
526 parser.add_option("", "--email-server", help="send email via the given server",
527                   type='str', default='localhost')
528 parser.add_option("", "--always-email", help="always send email, even on success",
529                   action="store_true")
530 parser.add_option("", "--daemon", help="daemonize after initial setup",
531                   action="store_true")
532 parser.add_option("", "--branch", help="the branch to work on (default=master)",
533                   default="master", type='str')
534 parser.add_option("", "--log-base", help="location where the logs can be found (default=cwd)",
535                   default=gitroot, type='str')
536 parser.add_option("", "--attach-logs", help="Attach logs to mails sent on success/failure?",
537                   default=False, action="store_true")
538
539 def send_email(subject, text, log_tar):
540     outer = MIMEMultipart()
541     outer['Subject'] = subject
542     outer['To'] = options.email
543     outer['From'] = options.email_from
544     outer['Date'] = email.utils.formatdate(localtime = True)
545     outer.preamble = 'Autobuild mails are now in MIME because we optionally attach the logs.\n'
546     outer.attach(MIMEText(text, 'plain'))
547     if options.attach_logs:
548         fp = open(log_tar, 'rb')
549         msg = MIMEApplication(fp.read(), 'gzip', email.encoders.encode_base64)
550         fp.close()
551         # Set the filename parameter
552         msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(log_tar))
553         outer.attach(msg)
554     content = outer.as_string()
555     s = smtplib.SMTP(options.email_server)
556     s.sendmail(options.email_from, [options.email], content)
557     s.set_debuglevel(1)
558     s.quit()
559
560 def email_failure(status, failed_task, failed_stage, failed_tag, errstr,
561                   elapsed_time, log_base=None):
562     '''send an email to options.email about the failure'''
563     elapsed_minutes = elapsed_time / 60.0
564     user = os.getenv("USER")
565     if log_base is None:
566         log_base = gitroot
567     text = '''
568 Dear Developer,
569
570 Your autobuild on %s failed after %.1f minutes
571 when trying to test %s with the following error:
572
573    %s
574
575 the autobuild has been abandoned. Please fix the error and resubmit.
576
577 A summary of the autobuild process is here:
578
579   %s/autobuild.log
580 ''' % (platform.node(), elapsed_minutes, failed_task, errstr, log_base)
581
582     if failed_task != 'rebase':
583         text += '''
584 You can see logs of the failed task here:
585
586   %s/%s.stdout
587   %s/%s.stderr
588
589 or you can get full logs of all tasks in this job here:
590
591   %s/logs.tar.gz
592
593 The top commit for the tree that was built was:
594
595 %s
596
597 ''' % (log_base, failed_tag, log_base, failed_tag, log_base, top_commit_msg)
598
599     logs = os.path.join(gitroot, 'logs.tar.gz')
600     send_email('autobuild failure on %s for task %s during %s'
601                % (platform.node(), failed_task, failed_stage),
602                text, logs)
603
604 def email_success(elapsed_time, log_base=None):
605     '''send an email to options.email about a successful build'''
606     user = os.getenv("USER")
607     if log_base is None:
608         log_base = gitroot
609     text = '''
610 Dear Developer,
611
612 Your autobuild on %s has succeeded after %.1f minutes.
613
614 ''' % (platform.node(), elapsed_time / 60.)
615
616     if options.keeplogs:
617         text += '''
618
619 you can get full logs of all tasks in this job here:
620
621   %s/logs.tar.gz
622
623 ''' % log_base
624
625     text += '''
626 The top commit for the tree that was built was:
627
628 %s
629 ''' % top_commit_msg
630
631     logs = os.path.join(gitroot, 'logs.tar.gz')
632     send_email('autobuild sucess on %s ' % platform.node(),
633                text, logs)
634
635
636 (options, args) = parser.parse_args()
637
638 if options.retry:
639     if options.rebase is None:
640         raise Exception('You can only use --retry if you also rebase')
641
642 testbase = "%s/b%u" % (options.testbase, os.getpid())
643 test_master = "%s/master" % testbase
644
645 # get the top commit message, for emails
646 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
647
648 try:
649     os.makedirs(testbase)
650 except Exception, reason:
651     raise Exception("Unable to create %s : %s" % (testbase, reason))
652 cleanup_list.append(testbase)
653
654 if options.daemon:
655     logfile = os.path.join(testbase, "log")
656     print "Forking into the background, writing progress to %s" % logfile
657     daemonize(logfile)
658
659 write_pidfile(gitroot + "/autobuild.pid")
660
661 start_time = time.time()
662
663 while True:
664     try:
665         run_cmd("rm -rf %s" % test_master)
666         cleanup_list.append(test_master)
667         run_cmd("git clone --recursive --shared %s %s" % (gitroot, test_master), show=True, dir=gitroot)
668     except Exception:
669         cleanup()
670         raise
671
672     try:
673         try:
674             if options.rebase is not None:
675                 rebase_tree(options.rebase, rebase_branch=options.branch)
676         except Exception:
677             cleanup_list.append(gitroot + "/autobuild.pid")
678             cleanup()
679             elapsed_time = time.time() - start_time
680             email_failure(-1, 'rebase', 'rebase', 'rebase',
681                           'rebase on %s failed' % options.branch,
682                           elapsed_time, log_base=options.log_base)
683             sys.exit(1)
684         blist = buildlist(tasks, args, options.rebase, rebase_branch=options.branch)
685         if options.tail:
686             blist.start_tail()
687         (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
688         if status != 0 or errstr != "retry":
689             break
690         cleanup()
691     except Exception:
692         cleanup()
693         raise
694
695 cleanup_list.append(gitroot + "/autobuild.pid")
696
697 blist.kill_kids()
698 if options.tail:
699     print("waiting for tail to flush")
700     time.sleep(1)
701
702 elapsed_time = time.time() - start_time
703 if status == 0:
704     print errstr
705     if options.passcmd is not None:
706         print("Running passcmd: %s" % options.passcmd)
707         run_cmd(options.passcmd, dir=test_master)
708     if options.pushto is not None:
709         push_to(options.pushto, push_branch=options.branch)
710     if options.keeplogs or options.attach_logs:
711         blist.tarlogs("logs.tar.gz")
712         print("Logs in logs.tar.gz")
713     if options.always_email:
714         email_success(elapsed_time, log_base=options.log_base)
715     blist.remove_logs()
716     cleanup()
717     print(errstr)
718     sys.exit(0)
719
720 # something failed, gather a tar of the logs
721 blist.tarlogs("logs.tar.gz")
722
723 if options.email is not None:
724     email_failure(status, failed_task, failed_stage, failed_tag, errstr,
725                   elapsed_time, log_base=options.log_base)
726 else:
727     elapsed_minutes = elapsed_time / 60.0
728     print '''
729
730 ####################################################################
731
732 AUTOBUILD FAILURE
733
734 Your autobuild on %s failed after %.1f minutes
735 when trying to test %s with the following error:
736
737    %s
738
739 the autobuild has been abandoned. Please fix the error and resubmit.
740
741 ####################################################################
742
743 ''' % (platform.node(), elapsed_minutes, failed_task, errstr)
744
745 cleanup()
746 print(errstr)
747 print("Logs in logs.tar.gz")
748 sys.exit(status)