s3:smb2_server add function to verify creditcharge
[Samba/bb.git] / script / autobuild.py
blobd8a1ad354ecee71f86adbceb84aafd6f89e54bce
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 builddirs = {
18 "samba3" : "source3",
19 "samba4" : ".",
20 "ldb" : "lib/ldb",
21 "tdb" : "lib/tdb",
22 "tdb2" : "lib/tdb2",
23 "talloc" : "lib/talloc",
24 "replace" : "lib/replace",
25 "tevent" : "lib/tevent",
26 "pidl" : "pidl",
27 "pass" : ".",
28 "fail" : ".",
29 "retry" : "."
32 defaulttasks = [ "samba3", "samba4", "ldb", "tdb", "tdb2", "talloc", "replace", "tevent", "pidl" ]
34 tasks = {
35 "samba3" : [ ("autogen", "./autogen.sh", "text/plain"),
36 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
37 ("make basics", "make basics", "text/plain"),
38 # we split 'make -j 4', 'make bin/smbtorture4' and 'make -j 4 everything'
39 # because it makes it much easier to find errors.
40 ("make", "make -j 4", "text/plain"), # don't use too many processes
41 ("make bin/smbtorture4", "make -j 4 bin/smbtorture4", "text/plain"),
42 ("make everything", "make -j 4 everything", "text/plain"),
43 ("install", "make install", "text/plain"),
44 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
45 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
46 ("clean", "make clean", "text/plain") ],
48 # We have 'test' before 'install' because, 'test' should work without 'install'
49 "samba4" : [ ("configure", "./configure.developer ${PREFIX} --with-selftest-prefix=./bin/ab", "text/plain"),
50 ("make", "make -j", "text/plain"),
51 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
52 ("install", "make install", "text/plain"),
53 ("check-clean-tree", "script/clean-source-tree.sh", "text/plain"),
54 ("clean", "make clean", "text/plain") ],
56 "ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
57 ("make", "make -j", "text/plain"),
58 ("install", "make install", "text/plain"),
59 ("test", "TDB_NO_FSYNC=1 make test", "text/plain"),
60 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
61 ("distcheck", "make distcheck", "text/plain"),
62 ("clean", "make clean", "text/plain") ],
64 # We don't use TDB_NO_FSYNC=1 here, because we want to test the transaction code
65 "tdb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
66 ("make", "make -j", "text/plain"),
67 ("install", "make install", "text/plain"),
68 ("test", "make test", "text/plain"),
69 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
70 ("distcheck", "make distcheck", "text/plain"),
71 ("clean", "make clean", "text/plain") ],
73 "tdb2" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
74 ("make", "make -j", "text/plain"),
75 ("install", "make install", "text/plain"),
76 ("test", "make test", "text/plain"),
77 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
78 ("distcheck", "make distcheck", "text/plain"),
79 ("clean", "make clean", "text/plain") ],
81 "talloc" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
82 ("make", "make -j", "text/plain"),
83 ("install", "make install", "text/plain"),
84 ("test", "make test", "text/plain"),
85 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
86 ("distcheck", "make distcheck", "text/plain"),
87 ("clean", "make clean", "text/plain") ],
89 "replace" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
90 ("make", "make -j", "text/plain"),
91 ("install", "make install", "text/plain"),
92 ("test", "make test", "text/plain"),
93 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
94 ("distcheck", "make distcheck", "text/plain"),
95 ("clean", "make clean", "text/plain") ],
97 "tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
98 ("make", "make -j", "text/plain"),
99 ("install", "make install", "text/plain"),
100 ("test", "make test", "text/plain"),
101 ("check-clean-tree", "../../script/clean-source-tree.sh", "text/plain"),
102 ("distcheck", "make distcheck", "text/plain"),
103 ("clean", "make clean", "text/plain") ],
105 "pidl" : [ ("configure", "perl Makefile.PL PREFIX=${PREFIX_DIR}", "text/plain"),
106 ("touch", "touch *.yp", "text/plain"),
107 ("make", "make", "text/plain"),
108 ("test", "make test", "text/plain"),
109 ("install", "make install", "text/plain"),
110 ("check-clean-tree", "../script/clean-source-tree.sh", "text/plain"),
111 ("clean", "make clean", "text/plain") ],
113 # these are useful for debugging autobuild
114 'pass' : [ ("pass", 'echo passing && /bin/true', "text/plain") ],
115 'fail' : [ ("fail", 'echo failing && /bin/false', "text/plain") ]
118 retry_task = [ ( "retry",
119 '''set -e
120 git remote add -t master master %s
121 git fetch master
122 while :; do
123 sleep 60
124 git describe master/master > old_master.desc
125 git fetch master
126 git describe master/master > master.desc
127 diff old_master.desc master.desc
128 done
129 ''' % samba_master, "test/plain" ) ]
131 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
132 if show is None:
133 show = options.verbose
134 if show:
135 print("Running: '%s' in '%s'" % (cmd, dir))
136 if output:
137 return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
138 elif checkfail:
139 return check_call(cmd, shell=True, cwd=dir)
140 else:
141 return call(cmd, shell=True, cwd=dir)
144 class builder(object):
145 '''handle build of one directory'''
147 def __init__(self, name, sequence):
148 self.name = name
149 self.dir = builddirs[name]
151 self.tag = self.name.replace('/', '_')
152 self.sequence = sequence
153 self.next = 0
154 self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
155 self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
156 if options.verbose:
157 print("stdout for %s in %s" % (self.name, self.stdout_path))
158 print("stderr for %s in %s" % (self.name, self.stderr_path))
159 run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
160 self.stdout = open(self.stdout_path, 'w')
161 self.stderr = open(self.stderr_path, 'w')
162 self.stdin = open("/dev/null", 'r')
163 self.sdir = "%s/%s" % (testbase, self.tag)
164 self.prefix = "%s/prefix/%s" % (testbase, self.tag)
165 run_cmd("rm -rf %s" % self.sdir)
166 cleanup_list.append(self.sdir)
167 cleanup_list.append(self.prefix)
168 os.makedirs(self.sdir)
169 run_cmd("rm -rf %s" % self.sdir)
170 run_cmd("git clone --shared %s %s" % (test_master, self.sdir), dir=test_master, show=True)
171 self.start_next()
173 def start_next(self):
174 if self.next == len(self.sequence):
175 print '%s: Completed OK' % self.name
176 self.done = True
177 return
178 (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
179 self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
180 self.cmd = self.cmd.replace("${PREFIX_DIR}", "%s" % self.prefix)
181 # if self.output_mime_type == "text/x-subunit":
182 # self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
183 print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
184 cwd = os.getcwd()
185 os.chdir("%s/%s" % (self.sdir, self.dir))
186 self.proc = Popen(self.cmd, shell=True,
187 stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
188 os.chdir(cwd)
189 self.next += 1
192 class buildlist(object):
193 '''handle build of multiple directories'''
195 def __init__(self, tasklist, tasknames):
196 global tasks
197 self.tlist = []
198 self.tail_proc = None
199 self.retry = None
200 if tasknames == []:
201 tasknames = defaulttasks
202 for n in tasknames:
203 b = builder(n, tasks[n])
204 self.tlist.append(b)
205 if options.retry:
206 self.retry = builder('retry', retry_task)
207 self.need_retry = False
209 def kill_kids(self):
210 if self.tail_proc is not None:
211 self.tail_proc.terminate()
212 self.tail_proc.wait()
213 self.tail_proc = None
214 if self.retry is not None:
215 self.retry.proc.terminate()
216 self.retry.proc.wait()
217 self.retry = None
218 for b in self.tlist:
219 if b.proc is not None:
220 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
221 b.proc.terminate()
222 b.proc.wait()
223 b.proc = None
225 def wait_one(self):
226 while True:
227 none_running = True
228 for b in self.tlist:
229 if b.proc is None:
230 continue
231 none_running = False
232 b.status = b.proc.poll()
233 if b.status is None:
234 continue
235 b.proc = None
236 return b
237 if options.retry:
238 ret = self.retry.proc.poll()
239 if ret is not None:
240 self.need_retry = True
241 self.retry = None
242 return None
243 if none_running:
244 return None
245 time.sleep(0.1)
247 def run(self):
248 while True:
249 b = self.wait_one()
250 if options.retry and self.need_retry:
251 self.kill_kids()
252 print("retry needed")
253 return (0, None, None, None, "retry")
254 if b is None:
255 break
256 if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
257 self.kill_kids()
258 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
259 b.start_next()
260 self.kill_kids()
261 return (0, None, None, None, "All OK")
263 def tarlogs(self, fname):
264 tar = tarfile.open(fname, "w:gz")
265 for b in self.tlist:
266 tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
267 tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
268 if os.path.exists("autobuild.log"):
269 tar.add("autobuild.log")
270 tar.close()
272 def remove_logs(self):
273 for b in self.tlist:
274 os.unlink(b.stdout_path)
275 os.unlink(b.stderr_path)
277 def start_tail(self):
278 cwd = os.getcwd()
279 cmd = "tail -f *.stdout *.stderr"
280 os.chdir(gitroot)
281 self.tail_proc = Popen(cmd, shell=True)
282 os.chdir(cwd)
285 def cleanup():
286 if options.nocleanup:
287 return
288 print("Cleaning up ....")
289 for d in cleanup_list:
290 run_cmd("rm -rf %s" % d)
293 def find_git_root():
294 '''get to the top of the git repo'''
295 p=os.getcwd()
296 while p != '/':
297 if os.path.isdir(os.path.join(p, ".git")):
298 return p
299 p = os.path.abspath(os.path.join(p, '..'))
300 return None
303 def daemonize(logfile):
304 pid = os.fork()
305 if pid == 0: # Parent
306 os.setsid()
307 pid = os.fork()
308 if pid != 0: # Actual daemon
309 os._exit(0)
310 else: # Grandparent
311 os._exit(0)
313 import resource # Resource usage information.
314 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
315 if maxfd == resource.RLIM_INFINITY:
316 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
317 for fd in range(0, maxfd):
318 try:
319 os.close(fd)
320 except OSError:
321 pass
322 os.open(logfile, os.O_RDWR | os.O_CREAT)
323 os.dup2(0, 1)
324 os.dup2(0, 2)
326 def write_pidfile(fname):
327 '''write a pid file, cleanup on exit'''
328 f = open(fname, mode='w')
329 f.write("%u\n" % os.getpid())
330 f.close()
333 def rebase_tree(url):
334 print("Rebasing on %s" % url)
335 run_cmd("git describe HEAD", show=True, dir=test_master)
336 run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
337 run_cmd("git fetch master", show=True, dir=test_master)
338 if options.fix_whitespace:
339 run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
340 else:
341 run_cmd("git rebase master/master", show=True, dir=test_master)
342 diff = run_cmd("git --no-pager diff HEAD master/master", dir=test_master, output=True)
343 if diff == '':
344 print("No differences between HEAD and master/master - exiting")
345 sys.exit(0)
346 run_cmd("git describe master/master", show=True, dir=test_master)
347 run_cmd("git describe HEAD", show=True, dir=test_master)
348 run_cmd("git --no-pager diff --stat HEAD master/master", show=True, dir=test_master)
350 def push_to(url):
351 print("Pushing to %s" % url)
352 if options.mark:
353 run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
354 run_cmd("git commit --amend -c HEAD", dir=test_master)
355 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
356 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
357 run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
358 run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
360 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
362 parser = OptionParser()
363 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
364 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
365 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
366 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
367 default=def_testbase)
368 parser.add_option("", "--passcmd", help="command to run on success", default=None)
369 parser.add_option("", "--verbose", help="show all commands as they are run",
370 default=False, action="store_true")
371 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
372 default=None, type='str')
373 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
374 default=False, action='store_true')
375 parser.add_option("", "--pushto", help="push to a git url on success",
376 default=None, type='str')
377 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
378 default=False, action='store_true')
379 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
380 default=False, action="store_true")
381 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
382 default=False, action="store_true")
383 parser.add_option("", "--retry", help="automatically retry if master changes",
384 default=False, action="store_true")
385 parser.add_option("", "--email", help="send email to the given address on failure",
386 type='str', default=None)
387 parser.add_option("", "--always-email", help="always send email, even on success",
388 action="store_true")
389 parser.add_option("", "--daemon", help="daemonize after initial setup",
390 action="store_true")
393 def email_failure(status, failed_task, failed_stage, failed_tag, errstr):
394 '''send an email to options.email about the failure'''
395 user = os.getenv("USER")
396 text = '''
397 Dear Developer,
399 Your autobuild failed when trying to test %s with the following error:
402 the autobuild has been abandoned. Please fix the error and resubmit.
404 A summary of the autobuild process is here:
406 http://git.samba.org/%s/samba-autobuild/autobuild.log
407 ''' % (failed_task, errstr, user)
409 if failed_task != 'rebase':
410 text += '''
411 You can see logs of the failed task here:
413 http://git.samba.org/%s/samba-autobuild/%s.stdout
414 http://git.samba.org/%s/samba-autobuild/%s.stderr
416 or you can get full logs of all tasks in this job here:
418 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
420 The top commit for the tree that was built was:
424 ''' % (user, failed_tag, user, failed_tag, user, top_commit_msg)
425 msg = MIMEText(text)
426 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
427 msg['From'] = 'autobuild@samba.org'
428 msg['To'] = options.email
430 s = smtplib.SMTP()
431 s.connect()
432 s.sendmail(msg['From'], [msg['To']], msg.as_string())
433 s.quit()
435 def email_success():
436 '''send an email to options.email about a successful build'''
437 user = os.getenv("USER")
438 text = '''
439 Dear Developer,
441 Your autobuild has succeeded.
445 if options.keeplogs:
446 text += '''
448 you can get full logs of all tasks in this job here:
450 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
452 ''' % user
454 text += '''
455 The top commit for the tree that was built was:
458 ''' % top_commit_msg
460 msg = MIMEText(text)
461 msg['Subject'] = 'autobuild success'
462 msg['From'] = 'autobuild@samba.org'
463 msg['To'] = options.email
465 s = smtplib.SMTP()
466 s.connect()
467 s.sendmail(msg['From'], [msg['To']], msg.as_string())
468 s.quit()
471 (options, args) = parser.parse_args()
473 if options.retry:
474 if not options.rebase_master and options.rebase is None:
475 raise Exception('You can only use --retry if you also rebase')
477 testbase = "%s/b%u" % (options.testbase, os.getpid())
478 test_master = "%s/master" % testbase
480 gitroot = find_git_root()
481 if gitroot is None:
482 raise Exception("Failed to find git root")
484 # get the top commit message, for emails
485 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
487 try:
488 os.makedirs(testbase)
489 except Exception, reason:
490 raise Exception("Unable to create %s : %s" % (testbase, reason))
491 cleanup_list.append(testbase)
493 if options.daemon:
494 logfile = os.path.join(testbase, "log")
495 print "Forking into the background, writing progress to %s" % logfile
496 daemonize(logfile)
498 write_pidfile(gitroot + "/autobuild.pid")
500 while True:
501 try:
502 run_cmd("rm -rf %s" % test_master)
503 cleanup_list.append(test_master)
504 run_cmd("git clone --shared %s %s" % (gitroot, test_master), show=True, dir=gitroot)
505 except Exception:
506 cleanup()
507 raise
509 try:
510 try:
511 if options.rebase is not None:
512 rebase_tree(options.rebase)
513 elif options.rebase_master:
514 rebase_tree(samba_master)
515 except Exception:
516 cleanup_list.append(gitroot + "/autobuild.pid")
517 cleanup()
518 email_failure(-1, 'rebase', 'rebase', 'rebase', 'rebase on master failed')
519 sys.exit(1)
520 blist = buildlist(tasks, args)
521 if options.tail:
522 blist.start_tail()
523 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
524 if status != 0 or errstr != "retry":
525 break
526 cleanup()
527 except Exception:
528 cleanup()
529 raise
531 cleanup_list.append(gitroot + "/autobuild.pid")
533 blist.kill_kids()
534 if options.tail:
535 print("waiting for tail to flush")
536 time.sleep(1)
538 if status == 0:
539 print errstr
540 if options.passcmd is not None:
541 print("Running passcmd: %s" % options.passcmd)
542 run_cmd(options.passcmd, dir=test_master)
543 if options.pushto is not None:
544 push_to(options.pushto)
545 elif options.push_master:
546 push_to(samba_master_ssh)
547 if options.keeplogs:
548 blist.tarlogs("logs.tar.gz")
549 print("Logs in logs.tar.gz")
550 if options.always_email:
551 email_success()
552 blist.remove_logs()
553 cleanup()
554 print(errstr)
555 sys.exit(0)
557 # something failed, gather a tar of the logs
558 blist.tarlogs("logs.tar.gz")
560 if options.email is not None:
561 email_failure(status, failed_task, failed_stage, failed_tag, errstr)
563 cleanup()
564 print(errstr)
565 print("Logs in logs.tar.gz")
566 sys.exit(status)