tsocket: fill in sa.sa_len if the system supports it
[Samba/gebeck_regimport.git] / script / autobuild.py
bloba124ddfd787e650b1ac40e3abd4aeeebc848c952
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") ],
27 # We have 'test' before 'install' because, 'test' should work without 'install'
28 "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
29 ("make", "make -j", "text/plain"),
30 ("test", "TDB_NO_FSYNC=1 make test FAIL_IMMEDIATELY=1", "text/plain"),
31 ("install", "make install", "text/plain") ],
33 "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
34 ("make", "make -j", "text/plain"),
35 ("install", "make install", "text/plain"),
36 ("test", "TDB_NO_FSYNC=1 make test", "text/plain") ],
38 # We don't use TDB_NO_FSYNC=1 here, because we want to test the transaction code
39 "lib/tdb" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
40 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
41 ("make", "make -j", "text/plain"),
42 ("install", "make install", "text/plain"),
43 ("test", "make test", "text/plain") ],
45 "lib/talloc" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
46 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
47 ("make", "make -j", "text/plain"),
48 ("install", "make install", "text/plain"),
49 ("test", "make test", "text/plain"), ],
51 "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
52 ("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"), ],
57 "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
58 ("make", "make -j", "text/plain"),
59 ("install", "make install", "text/plain"),
60 ("test", "make test", "text/plain"), ],
63 retry_task = [ ( "retry",
64 '''set -e
65 git remote add -t master master %s
66 git fetch master
67 while :; do
68 sleep 60
69 git describe master/master > old_master.desc
70 git fetch master
71 git describe master/master > master.desc
72 diff old_master.desc master.desc
73 done
74 ''' % samba_master, "test/plain" ) ]
76 def run_cmd(cmd, dir=".", show=None, output=False, checkfail=True):
77 if show is None:
78 show = options.verbose
79 if show:
80 print("Running: '%s' in '%s'" % (cmd, dir))
81 if output:
82 return Popen([cmd], shell=True, stdout=PIPE, cwd=dir).communicate()[0]
83 elif checkfail:
84 return check_call(cmd, shell=True, cwd=dir)
85 else:
86 return call(cmd, shell=True, cwd=dir)
89 class builder(object):
90 '''handle build of one directory'''
92 def __init__(self, name, sequence):
93 self.name = name
95 if name in ['pass', 'fail', 'retry']:
96 self.dir = "."
97 else:
98 self.dir = self.name
100 self.tag = self.name.replace('/', '_')
101 self.sequence = sequence
102 self.next = 0
103 self.stdout_path = "%s/%s.stdout" % (gitroot, self.tag)
104 self.stderr_path = "%s/%s.stderr" % (gitroot, self.tag)
105 if options.verbose:
106 print("stdout for %s in %s" % (self.name, self.stdout_path))
107 print("stderr for %s in %s" % (self.name, self.stderr_path))
108 run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
109 self.stdout = open(self.stdout_path, 'w')
110 self.stderr = open(self.stderr_path, 'w')
111 self.stdin = open("/dev/null", 'r')
112 self.sdir = "%s/%s" % (testbase, self.tag)
113 self.prefix = "%s/prefix/%s" % (testbase, self.tag)
114 run_cmd("rm -rf %s" % self.sdir)
115 cleanup_list.append(self.sdir)
116 cleanup_list.append(self.prefix)
117 os.makedirs(self.sdir)
118 run_cmd("rm -rf %s" % self.sdir)
119 run_cmd("git clone --shared %s %s" % (gitroot, self.sdir))
120 self.start_next()
122 def start_next(self):
123 if self.next == len(self.sequence):
124 print '%s: Completed OK' % self.name
125 self.done = True
126 return
127 (self.stage, self.cmd, self.output_mime_type) = self.sequence[self.next]
128 self.cmd = self.cmd.replace("${PREFIX}", "--prefix=%s" % self.prefix)
129 # if self.output_mime_type == "text/x-subunit":
130 # self.cmd += " | %s --immediate" % (os.path.join(os.path.dirname(__file__), "selftest/format-subunit"))
131 print '%s: [%s] Running %s' % (self.name, self.stage, self.cmd)
132 cwd = os.getcwd()
133 os.chdir("%s/%s" % (self.sdir, self.dir))
134 self.proc = Popen(self.cmd, shell=True,
135 stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
136 os.chdir(cwd)
137 self.next += 1
140 class buildlist(object):
141 '''handle build of multiple directories'''
143 def __init__(self, tasklist, tasknames):
144 global tasks
145 self.tlist = []
146 self.tail_proc = None
147 self.retry = None
148 if tasknames == ['pass']:
149 tasks = { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
150 if tasknames == ['fail']:
151 tasks = { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
152 if tasknames == []:
153 tasknames = tasklist
154 for n in tasknames:
155 b = builder(n, tasks[n])
156 self.tlist.append(b)
157 if options.retry:
158 self.retry = builder('retry', retry_task)
159 self.need_retry = False
161 def kill_kids(self):
162 if self.tail_proc is not None:
163 self.tail_proc.terminate()
164 self.tail_proc.wait()
165 self.tail_proc = None
166 if self.retry is not None:
167 self.retry.proc.terminate()
168 self.retry.proc.wait()
169 self.retry = None
170 for b in self.tlist:
171 if b.proc is not None:
172 run_cmd("killbysubdir %s > /dev/null 2>&1" % b.sdir, checkfail=False)
173 b.proc.terminate()
174 b.proc.wait()
175 b.proc = None
177 def wait_one(self):
178 while True:
179 none_running = True
180 for b in self.tlist:
181 if b.proc is None:
182 continue
183 none_running = False
184 b.status = b.proc.poll()
185 if b.status is None:
186 continue
187 b.proc = None
188 return b
189 if options.retry:
190 ret = self.retry.proc.poll()
191 if ret is not None:
192 self.need_retry = True
193 self.retry = None
194 return None
195 if none_running:
196 return None
197 time.sleep(0.1)
199 def run(self):
200 while True:
201 b = self.wait_one()
202 if options.retry and self.need_retry:
203 self.kill_kids()
204 print("retry needed")
205 return (0, None, None, None, "retry")
206 if b is None:
207 break
208 if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
209 self.kill_kids()
210 return (b.status, b.name, b.stage, b.tag, "%s: [%s] failed '%s' with status %d" % (b.name, b.stage, b.cmd, b.status))
211 b.start_next()
212 self.kill_kids()
213 return (0, None, None, None, "All OK")
215 def tarlogs(self, fname):
216 tar = tarfile.open(fname, "w:gz")
217 for b in self.tlist:
218 tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
219 tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
220 if os.path.exists("autobuild.log"):
221 tar.add("autobuild.log")
222 tar.close()
224 def remove_logs(self):
225 for b in self.tlist:
226 os.unlink(b.stdout_path)
227 os.unlink(b.stderr_path)
229 def start_tail(self):
230 cwd = os.getcwd()
231 cmd = "tail -f *.stdout *.stderr"
232 os.chdir(gitroot)
233 self.tail_proc = Popen(cmd, shell=True)
234 os.chdir(cwd)
237 def cleanup():
238 if options.nocleanup:
239 return
240 print("Cleaning up ....")
241 for d in cleanup_list:
242 run_cmd("rm -rf %s" % d)
245 def find_git_root():
246 '''get to the top of the git repo'''
247 p=os.getcwd()
248 while p != '/':
249 if os.path.isdir(os.path.join(p, ".git")):
250 return p
251 p = os.path.abspath(os.path.join(p, '..'))
252 return None
255 def daemonize(logfile):
256 pid = os.fork()
257 if pid == 0: # Parent
258 os.setsid()
259 pid = os.fork()
260 if pid != 0: # Actual daemon
261 os._exit(0)
262 else: # Grandparent
263 os._exit(0)
265 import resource # Resource usage information.
266 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
267 if maxfd == resource.RLIM_INFINITY:
268 maxfd = 1024 # Rough guess at maximum number of open file descriptors.
269 for fd in range(0, maxfd):
270 try:
271 os.close(fd)
272 except OSError:
273 pass
274 os.open(logfile, os.O_RDWR | os.O_CREAT)
275 os.dup2(0, 1)
276 os.dup2(0, 2)
278 def write_pidfile(fname):
279 '''write a pid file, cleanup on exit'''
280 f = open(fname, mode='w')
281 f.write("%u\n" % os.getpid())
282 f.close()
285 def rebase_tree(url):
286 print("Rebasing on %s" % url)
287 run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
288 run_cmd("git fetch master", show=True, dir=test_master)
289 if options.fix_whitespace:
290 run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
291 else:
292 run_cmd("git rebase master/master", show=True, dir=test_master)
293 diff = run_cmd("git --no-pager diff HEAD master/master", dir=test_master, output=True)
294 if diff == '':
295 print("No differences between HEAD and master/master - exiting")
296 sys.exit(0)
298 def push_to(url):
299 print("Pushing to %s" % url)
300 if options.mark:
301 run_cmd("git config --replace-all core.editor script/commit_mark.sh", dir=test_master)
302 run_cmd("git commit --amend -c HEAD", dir=test_master)
303 # the notes method doesn't work yet, as metze hasn't allowed refs/notes/* in master
304 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD", dir=test_master)
305 run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
306 run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
308 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
310 parser = OptionParser()
311 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
312 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
313 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
314 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
315 default=def_testbase)
316 parser.add_option("", "--passcmd", help="command to run on success", default=None)
317 parser.add_option("", "--verbose", help="show all commands as they are run",
318 default=False, action="store_true")
319 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
320 default=None, type='str')
321 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
322 default=False, action='store_true')
323 parser.add_option("", "--pushto", help="push to a git url on success",
324 default=None, type='str')
325 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
326 default=False, action='store_true')
327 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
328 default=False, action="store_true")
329 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
330 default=False, action="store_true")
331 parser.add_option("", "--retry", help="automatically retry if master changes",
332 default=False, action="store_true")
333 parser.add_option("", "--email", help="send email to the given address on failure",
334 type='str', default=None)
335 parser.add_option("", "--always-email", help="always send email, even on success",
336 action="store_true")
337 parser.add_option("", "--daemon", help="daemonize after initial setup",
338 action="store_true")
341 def email_failure(status, failed_task, failed_stage, failed_tag, errstr):
342 '''send an email to options.email about the failure'''
343 user = os.getenv("USER")
344 text = '''
345 Dear Developer,
347 Your autobuild failed when trying to test %s with the following error:
350 the autobuild has been abandoned. Please fix the error and resubmit.
352 A summary of the autobuild process is here:
354 http://git.samba.org/%s/samba-autobuild/autobuild.log
355 ''' % (failed_task, errstr, user)
357 if failed_task != 'rebase':
358 text += '''
359 You can see logs of the failed task here:
361 http://git.samba.org/%s/samba-autobuild/%s.stdout
362 http://git.samba.org/%s/samba-autobuild/%s.stderr
364 or you can get full logs of all tasks in this job here:
366 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
368 The top commit for the tree that was built was:
372 ''' % (user, failed_tag, user, failed_tag, user, top_commit_msg)
373 msg = MIMEText(text)
374 msg['Subject'] = 'autobuild failure for task %s during %s' % (failed_task, failed_stage)
375 msg['From'] = 'autobuild@samba.org'
376 msg['To'] = options.email
378 s = smtplib.SMTP()
379 s.connect()
380 s.sendmail(msg['From'], [msg['To']], msg.as_string())
381 s.quit()
383 def email_success():
384 '''send an email to options.email about a successful build'''
385 user = os.getenv("USER")
386 text = '''
387 Dear Developer,
389 Your autobuild has succeeded.
393 if options.keeplogs:
394 text += '''
396 you can get full logs of all tasks in this job here:
398 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
400 ''' % user
402 text += '''
403 The top commit for the tree that was built was:
406 ''' % top_commit_msg
408 msg = MIMEText(text)
409 msg['Subject'] = 'autobuild success'
410 msg['From'] = 'autobuild@samba.org'
411 msg['To'] = options.email
413 s = smtplib.SMTP()
414 s.connect()
415 s.sendmail(msg['From'], [msg['To']], msg.as_string())
416 s.quit()
419 (options, args) = parser.parse_args()
421 if options.retry:
422 if not options.rebase_master and options.rebase is None:
423 raise Exception('You can only use --retry if you also rebase')
425 testbase = "%s/b%u" % (options.testbase, os.getpid())
426 test_master = "%s/master" % testbase
428 gitroot = find_git_root()
429 if gitroot is None:
430 raise Exception("Failed to find git root")
432 # get the top commit message, for emails
433 top_commit_msg = run_cmd("git log -1", dir=gitroot, output=True)
435 try:
436 os.makedirs(testbase)
437 except Exception, reason:
438 raise Exception("Unable to create %s : %s" % (testbase, reason))
439 cleanup_list.append(testbase)
441 if options.daemon:
442 logfile = os.path.join(testbase, "log")
443 print "Forking into the background, writing progress to %s" % logfile
444 daemonize(logfile)
446 write_pidfile(gitroot + "/autobuild.pid")
448 while True:
449 try:
450 run_cmd("rm -rf %s" % test_master)
451 cleanup_list.append(test_master)
452 run_cmd("git clone --shared %s %s" % (gitroot, test_master))
453 except:
454 cleanup()
455 raise
457 try:
458 try:
459 if options.rebase is not None:
460 rebase_tree(options.rebase)
461 elif options.rebase_master:
462 rebase_tree(samba_master)
463 except:
464 email_failure(-1, 'rebase', 'rebase', 'rebase', 'rebase on master failed')
465 sys.exit(1)
466 blist = buildlist(tasks, args)
467 if options.tail:
468 blist.start_tail()
469 (status, failed_task, failed_stage, failed_tag, errstr) = blist.run()
470 if status != 0 or errstr != "retry":
471 break
472 cleanup()
473 except:
474 cleanup()
475 raise
477 cleanup_list.append(gitroot + "/autobuild.pid")
479 blist.kill_kids()
480 if options.tail:
481 print("waiting for tail to flush")
482 time.sleep(1)
484 if status == 0:
485 print errstr
486 if options.passcmd is not None:
487 print("Running passcmd: %s" % options.passcmd)
488 run_cmd(options.passcmd, dir=test_master)
489 if options.pushto is not None:
490 push_to(options.pushto)
491 elif options.push_master:
492 push_to(samba_master_ssh)
493 if options.keeplogs:
494 blist.tarlogs("logs.tar.gz")
495 print("Logs in logs.tar.gz")
496 if options.always_email:
497 email_success()
498 blist.remove_logs()
499 cleanup()
500 print(errstr)
501 sys.exit(0)
503 # something failed, gather a tar of the logs
504 blist.tarlogs("logs.tar.gz")
506 if options.email is not None:
507 email_failure(status, failed_task, failed_stage, failed_tag, errstr)
509 cleanup()
510 print(errstr)
511 print("Logs in logs.tar.gz")
512 sys.exit(status)