heimdal_build: Support using system hdb and kdc libraries.
[Samba.git] / script / autobuild.py
blobc6959a2b937cb8e044e12f3f44b2bfc9e5e75a07
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
6 from subprocess import call, check_call,Popen, PIPE
7 import os, tarfile, sys, time
8 from optparse import OptionParser
9 import smtplib
10 from email.mime.text import MIMEText
12 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
13 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
15 cleanup_list = []
17 os.putenv('CC', "ccache gcc")
19 tasks = {
20 "source3" : [ ("autogen", "./autogen.sh", "text/plain"),
21 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
22 ("make basics", "make basics", "text/plain"),
23 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
24 ("install", "make install", "text/plain"),
25 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
26 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
27 ("clean", "make clean", "text/plain") ],
29 # We have 'test' before 'install' because, 'test' should work without 'install'
30 "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
31 ("make", "make -j", "text/plain"),
32 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
33 ("install", "make install", "text/plain"),
34 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
35 ("clean", "make clean", "text/plain") ],
37 "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
38 ("make", "make -j", "text/plain"),
39 ("install", "make install", "text/plain"),
40 ("test", "TDB_NO_FSYNC=1 make test", "text/plain"),
41 ("check-clean-tree", "../../../script/clean-source-tree.sh", "text/plain"),
42 ("clean", "make clean", "text/plain") ],
44 # We don't use TDB_NO_FSYNC=1 here, because we want to test the transaction code
45 "lib/tdb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
46 ("make", "make -j", "text/plain"),
47 ("install", "make install", "text/plain"),
48 ("test", "make test", "text/plain"),
49 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
50 ("clean", "make clean", "text/plain") ],
52 "lib/talloc" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
53 ("make", "make -j", "text/plain"),
54 ("install", "make install", "text/plain"),
55 ("test", "make test", "text/plain"),
56 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
57 ("clean", "make clean", "text/plain") ],
59 "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
60 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
61 ("make", "make -j", "text/plain"),
62 ("install", "make install", "text/plain"),
63 ("test", "make test", "text/plain"),
64 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
65 ("clean", "make clean", "text/plain") ],
67 "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
68 ("make", "make -j", "text/plain"),
69 ("install", "make install", "text/plain"),
70 ("test", "make test", "text/plain"),
71 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
72 ("clean", "make clean", "text/plain") ],
75 retry_task = [ ( "retry",
76 '''set -e
77 git remote add -t master master %s
78 git fetch master
79 while :; do
80 sleep 60
81 git describe master/master > old_master.desc
82 git fetch master
83 git describe master/master > master.desc
84 diff old_master.desc master.desc
85 done
86 ''' % samba_master, "test/plain" ) ]
88 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
89 if show is None:
90 show = options.verbose
91 if show:
92 print("Running: '%s' in '%s'" % (cmd, dir))
93 if output:
94 return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
95 elif checkfail:
96 return check_call(cmd, shell=True, cwd=dir)
97 else:
98 return call(cmd, shell=True, cwd=dir)
101 class builder(object):
102 '''handle build of one directory'''
104 def __init__(self, name, sequence):
105 self.name = name
107 if name in ['pass', 'fail', 'retry']:
108 self.dir = "."
109 else:
110 self.dir = self.name
112 self.tag = self.name.replace('/', '_')
113 self.sequence = sequence
114 self.next = 0
115 self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
116 self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
117 if options.verbose:
118 print("stdout for %s in %s" % (self.name, self.stdout_path))
119 print("stderr for %s in %s" % (self.name, self.stderr_path))
120 run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
121 self.stdout = open(self.stdout_path, 'w')
122 self.stderr = open(self.stderr_path, 'w')
123 self.stdin = open("/dev/null", 'r')
124 self.sdir = "%s/%s" % (testbase, self.tag)
125 self.prefix = "%s/prefix/%s" % (testbase, self.tag)
126 run_cmd("rm -rf %s" % self.sdir)
127 cleanup_list.append(self.sdir)
128 cleanup_list.append(self.prefix)
129 os.makedirs(self.sdir)
130 run_cmd("rm -rf %s" % self.sdir)
131 run_cmd("git clone --shared %s %s" % (gitroot, self.sdir))
132 self.start_next()
134 def start_next(self):
135 if self.next == len(self.sequence):
136 print '%s: Completed OK' % self.name
137 self.done = True
138 return
139 (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
140 self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
141 # if self.output_mime_type == "text/x-subunit":
142 # self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
143 print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
144 cwd = os.getcwd()
145 os.chdir("%s/%s" % (self.sdir, self.dir))
146 self.proc = Popen(self.cmd, shell=True,
147 stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
148 os.chdir(cwd)
149 self.next += 1
152 class buildlist(object):
153 '''handle build of multiple directories'''
155 def __init__(self, tasklist, tasknames):
156 global tasks
157 self.tlist = []
158 self.tail_proc = None
159 self.retry = None
160 if tasknames == ['pass']:
161 tasks = { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
162 if tasknames == ['fail']:
163 tasks = { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
164 if tasknames == []:
165 tasknames = tasklist
166 for n in tasknames:
167 b = builder(n, tasks[n])
168 self.tlist.append(b)
169 if options.retry:
170 self.retry = builder('retry', retry_task)
171 self.need_retry = False
173 def kill_kids(self):
174 if self.tail_proc is not None:
175 self.tail_proc.terminate()
176 self.tail_proc.wait()
177 self.tail_proc = None
178 if self.retry is not None:
179 self.retry.proc.terminate()
180 self.retry.proc.wait()
181 self.retry = None
182 for b in self.tlist:
183 if b.proc is not None:
184 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
185 b.proc.terminate()
186 b.proc.wait()
187 b.proc = None
189 def wait_one(self):
190 while True:
191 none_running = True
192 for b in self.tlist:
193 if b.proc is None:
194 continue
195 none_running = False
196 b.status = b.proc.poll()
197 if b.status is None:
198 continue
199 b.proc = None
200 return b
201 if options.retry:
202 ret = self.retry.proc.poll()
203 if ret is not None:
204 self.need_retry = True
205 self.retry = None
206 return None
207 if none_running:
208 return None
209 time.sleep(0.1)
211 def run(self):
212 while True:
213 b = self.wait_one()
214 if options.retry and self.need_retry:
215 self.kill_kids()
216 print("retry needed")
217 return (0, None, None, None, "retry")
218 if b is None:
219 break
220 if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
221 self.kill_kids()
222 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
223 b.start_next()
224 self.kill_kids()
225 return (0, None, None, None, "All OK")
227 def tarlogs(self, fname):
228 tar = tarfile.open(fname, "w:gz")
229 for b in self.tlist:
230 tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
231 tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
232 if os.path.exists("autobuild.log"):
233 tar.add("autobuild.log")
234 tar.close()
236 def remove_logs(self):
237 for b in self.tlist:
238 os.unlink(b.stdout_path)
239 os.unlink(b.stderr_path)
241 def start_tail(self):
242 cwd = os.getcwd()
243 cmd = "tail -f *.stdout *.stderr"
244 os.chdir(gitroot)
245 self.tail_proc = Popen(cmd, shell=True)
246 os.chdir(cwd)
249 def cleanup():
250 if options.nocleanup:
251 return
252 print("Cleaning up ....")
253 for d in cleanup_list:
254 run_cmd("rm -rf %s" % d)
257 def find_git_root():
258 '''get to the top of the git repo'''
259 p=os.getcwd()
260 while p != '/':
261 if os.path.isdir(os.path.join(p, ".git")):
262 return p
263 p = os.path.abspath(os.path.join(p, '..'))
264 return None
267 def daemonize(logfile):
268 pid = os.fork()
269 if pid == 0: # Parent
270 os.setsid()
271 pid = os.fork()
272 if pid != 0: # Actual daemon
273 os._exit(0)
274 else: # Grandparent
275 os._exit(0)
277 import resource # Resource usage information.
278 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
279 if maxfd == resource.RLIM_INFINITY:
280 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
281 for fd in range(0, maxfd):
282 try:
283 os.close(fd)
284 except OSError:
285 pass
286 os.open(logfile, os.O_RDWR | os.O_CREAT)
287 os.dup2(0, 1)
288 os.dup2(0, 2)
290 def write_pidfile(fname):
291 '''write a pid file, cleanup on exit'''
292 f = open(fname, mode='w')
293 f.write("%u\n" % os.getpid())
294 f.close()
297 def rebase_tree(url):
298 print("Rebasing on %s" % url)
299 run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
300 run_cmd("git fetch master", show=True, dir=test_master)
301 if options.fix_whitespace:
302 run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
303 else:
304 run_cmd("git rebase master/master", show=True, dir=test_master)
305 diff = run_cmd("git --no-pager diff HEAD master/master", dir=test_master, output=True)
306 if diff == '':
307 print("No differences between HEAD and master/master - exiting")
308 sys.exit(0)
310 def push_to(url):
311 print("Pushing to %s" % url)
312 if options.mark:
313 run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
314 run_cmd("git commit --amend -c HEAD", dir=test_master)
315 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
316 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
317 run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
318 run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
320 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
322 parser = OptionParser()
323 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
324 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
325 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
326 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
327 default=def_testbase)
328 parser.add_option("", "--passcmd", help="command to run on success", default=None)
329 parser.add_option("", "--verbose", help="show all commands as they are run",
330 default=False, action="store_true")
331 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
332 default=None, type='str')
333 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
334 default=False, action='store_true')
335 parser.add_option("", "--pushto", help="push to a git url on success",
336 default=None, type='str')
337 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
338 default=False, action='store_true')
339 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
340 default=False, action="store_true")
341 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
342 default=False, action="store_true")
343 parser.add_option("", "--retry", help="automatically retry if master changes",
344 default=False, action="store_true")
345 parser.add_option("", "--email", help="send email to the given address on failure",
346 type='str', default=None)
347 parser.add_option("", "--always-email", help="always send email, even on success",
348 action="store_true")
349 parser.add_option("", "--daemon", help="daemonize after initial setup",
350 action="store_true")
353 def email_failure(status, failed_task, failed_stage, failed_tag, errstr):
354 '''send an email to options.email about the failure'''
355 user = os.getenv("USER")
356 text = '''
357 Dear Developer,
359 Your autobuild failed when trying to test %s with the following error:
362 the autobuild has been abandoned. Please fix the error and resubmit.
364 A summary of the autobuild process is here:
366 http://git.samba.org/%s/samba-autobuild/autobuild.log
367 ''' % (failed_task, errstr, user)
369 if failed_task != 'rebase':
370 text += '''
371 You can see logs of the failed task here:
373 http://git.samba.org/%s/samba-autobuild/%s.stdout
374 http://git.samba.org/%s/samba-autobuild/%s.stderr
376 or you can get full logs of all tasks in this job here:
378 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
380 The top commit for the tree that was built was:
384 ''' % (user, failed_tag, user, failed_tag, user, top_commit_msg)
385 msg = MIMEText(text)
386 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
387 msg['From'] = 'autobuild@samba.org'
388 msg['To'] = options.email
390 s = smtplib.SMTP()
391 s.connect()
392 s.sendmail(msg['From'], [msg['To']], msg.as_string())
393 s.quit()
395 def email_success():
396 '''send an email to options.email about a successful build'''
397 user = os.getenv("USER")
398 text = '''
399 Dear Developer,
401 Your autobuild has succeeded.
405 if options.keeplogs:
406 text += '''
408 you can get full logs of all tasks in this job here:
410 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
412 ''' % user
414 text += '''
415 The top commit for the tree that was built was:
418 ''' % top_commit_msg
420 msg = MIMEText(text)
421 msg['Subject'] = 'autobuild success'
422 msg['From'] = 'autobuild@samba.org'
423 msg['To'] = options.email
425 s = smtplib.SMTP()
426 s.connect()
427 s.sendmail(msg['From'], [msg['To']], msg.as_string())
428 s.quit()
431 (options, args) = parser.parse_args()
433 if options.retry:
434 if not options.rebase_master and options.rebase is None:
435 raise Exception('You can only use --retry if you also rebase')
437 testbase = "%s/b%u" % (options.testbase, os.getpid())
438 test_master = "%s/master" % testbase
440 gitroot = find_git_root()
441 if gitroot is None:
442 raise Exception("Failed to find git root")
444 # get the top commit message, for emails
445 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
447 try:
448 os.makedirs(testbase)
449 except Exception, reason:
450 raise Exception("Unable to create %s : %s" % (testbase, reason))
451 cleanup_list.append(testbase)
453 if options.daemon:
454 logfile = os.path.join(testbase, "log")
455 print "Forking into the background, writing progress to %s" % logfile
456 daemonize(logfile)
458 write_pidfile(gitroot + "/autobuild.pid")
460 while True:
461 try:
462 run_cmd("rm -rf %s" % test_master)
463 cleanup_list.append(test_master)
464 run_cmd("git clone --shared %s %s" % (gitroot, test_master))
465 except:
466 cleanup()
467 raise
469 try:
470 try:
471 if options.rebase is not None:
472 rebase_tree(options.rebase)
473 elif options.rebase_master:
474 rebase_tree(samba_master)
475 except:
476 email_failure(-1, 'rebase', 'rebase', 'rebase', 'rebase on master failed')
477 sys.exit(1)
478 blist = buildlist(tasks, args)
479 if options.tail:
480 blist.start_tail()
481 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
482 if status != 0 or errstr != "retry":
483 break
484 cleanup()
485 except:
486 cleanup()
487 raise
489 cleanup_list.append(gitroot + "/autobuild.pid")
491 blist.kill_kids()
492 if options.tail:
493 print("waiting for tail to flush")
494 time.sleep(1)
496 if status == 0:
497 print errstr
498 if options.passcmd is not None:
499 print("Running passcmd: %s" % options.passcmd)
500 run_cmd(options.passcmd, dir=test_master)
501 if options.pushto is not None:
502 push_to(options.pushto)
503 elif options.push_master:
504 push_to(samba_master_ssh)
505 if options.keeplogs:
506 blist.tarlogs("logs.tar.gz")
507 print("Logs in logs.tar.gz")
508 if options.always_email:
509 email_success()
510 blist.remove_logs()
511 cleanup()
512 print(errstr)
513 sys.exit(0)
515 # something failed, gather a tar of the logs
516 blist.tarlogs("logs.tar.gz")
518 if options.email is not None:
519 email_failure(status, failed_task, failed_stage, failed_tag, errstr)
521 cleanup()
522 print(errstr)
523 print("Logs in logs.tar.gz")
524 sys.exit(status)