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