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