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