2 # run tests on all Samba subprojects and push to a git tree on success
3 # Copyright Andrew Tridgell 2010
4 # Copyright Jelmer Vernooij 2010
5 # released under GNU GPL v3 or later
7 from cStringIO
import StringIO
9 from subprocess
import call
, check_call
, Popen
, PIPE
10 import os
, tarfile
, sys
, time
11 from optparse
import OptionParser
13 sys
.path
.insert(0, os
.path
.join(os
.path
.dirname(__file__
), "../selftest"))
14 sys
.path
.insert(0, os
.path
.join(os
.path
.dirname(__file__
), "../lib/testtools"))
15 sys
.path
.insert(0, os
.path
.join(os
.path
.dirname(__file__
), "../lib/subunit/python"))
19 from email
.mime
.application
import MIMEApplication
20 from email
.mime
.text
import MIMEText
21 from email
.mime
.multipart
import MIMEMultipart
23 samba_master
= os
.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
24 samba_master_ssh
= os
.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
28 os
.putenv('CC', "ccache gcc")
31 "source3" : [ ("autogen", "./autogen.sh", "text/plain"),
32 ("configure", "./configure.developer ${PREFIX}", "text/plain"),
33 ("make basics", "make basics", "text/plain"),
34 ("make", "make -j 4 everything", "text/plain"), # don't use too many processes
35 ("install", "make install", "text/plain"),
36 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
38 "source4" : [ ("configure", "./configure.developer ${PREFIX}", "text/plain"),
39 ("make", "make -j", "text/plain"),
40 ("install", "make install", "text/plain"),
41 ("test", "TDB_NO_FSYNC=1 make subunit-test", "text/x-subunit") ],
43 "source4/lib/ldb" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
44 ("make", "make -j", "text/plain"),
45 ("install", "make install", "text/plain"),
46 ("test", "make test", "text/plain") ],
48 "lib/tdb" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
49 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
50 ("make", "make -j", "text/plain"),
51 ("install", "make install", "text/plain"),
52 ("test", "make test", "text/plain") ],
54 "lib/talloc" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
55 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
56 ("make", "make -j", "text/plain"),
57 ("install", "make install", "text/plain"),
58 ("test", "make test", "text/x-subunit"), ],
60 "lib/replace" : [ ("autogen", "./autogen-waf.sh", "text/plain"),
61 ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
62 ("make", "make -j", "text/plain"),
63 ("install", "make install", "text/plain"),
64 ("test", "make test", "text/plain"), ],
66 "lib/tevent" : [ ("configure", "./configure --enable-developer -C ${PREFIX}", "text/plain"),
67 ("make", "make -j", "text/plain"),
68 ("install", "make install", "text/plain"),
69 ("test", "make test", "text/plain"), ],
72 retry_task
= [ ( "retry",
74 git remote add -t master master %s
78 git describe master/master > old_master.desc
80 git describe master/master > master.desc
81 diff old_master.desc master.desc
83 ''' % samba_master
, "test/plain" ) ]
86 def run_cmd(cmd
, dir=None, show
=None, output
=False, checkfail
=True, shell
=False):
88 show
= options
.verbose
90 print("Running: '%s' in '%s'" % (cmd
, dir))
92 return Popen(cmd
, stdout
=PIPE
, cwd
=dir, shell
=shell
).communicate()[0]
94 return check_call(cmd
, cwd
=dir, shell
=shell
)
96 return call(cmd
, cwd
=dir, shell
=shell
)
99 def clone_gitroot(test_master
, revision
="HEAD"):
100 run_cmd(["git", "clone", "--shared", gitroot
, test_master
])
101 if revision
!= "HEAD":
102 run_cmd(["git", "checkout", revision
])
105 class TreeStageBuilder(object):
106 """Handle building of a particular stage for a tree.
109 def __init__(self
, tree
, name
, command
, fail_quickly
=False):
112 self
.command
= command
113 self
.fail_quickly
= fail_quickly
115 self
.stdin
= open(os
.devnull
, 'r')
118 raise NotImplementedError(self
.start
)
121 self
.status
= self
.proc
.poll()
125 if self
.proc
is not None:
127 run_cmd(["killbysubdir", self
.tree
.sdir
], checkfail
=False)
129 # killbysubdir doesn't exist ?
131 self
.proc
.terminate()
136 def failure_reason(self
):
137 return "failed '%s' with status %d" % (self
.cmd
, self
.status
)
141 return (os
.WIFSIGNALED(self
.status
) or os
.WEXITSTATUS(self
.status
) != 0)
144 class PlainTreeStageBuilder(TreeStageBuilder
):
147 print '%s: [%s] Running %s' % (self
.name
, self
.name
, self
.command
)
148 self
.proc
= Popen(self
.command
, shell
=True, cwd
=self
.tree
.dir,
149 stdout
=self
.tree
.stdout
, stderr
=self
.tree
.stderr
,
153 class AbortingTestResult(subunithelper
.TestsuiteEnabledTestResult
):
155 def __init__(self
, stage
):
156 super(AbortingTestResult
, self
).__init
__()
159 def addError(self
, test
, details
=None):
160 self
.stage
.proc
.terminate()
162 def addFailure(self
, test
, details
=None):
163 self
.stage
.proc
.terminate()
166 class SubunitTreeStageBuilder(TreeStageBuilder
):
168 def __init__(self
, tree
, name
, command
, fail_quickly
=False):
169 super(SubunitTreeStageBuilder
, self
).__init
__(tree
, name
, command
,
171 self
.failed_tests
= []
172 self
.subunit_path
= os
.path
.join(gitroot
,
173 "%s.%s.subunit" % (self
.tree
.tag
, self
.name
))
174 self
.tree
.logfiles
.append(
175 (self
.subunit_path
, os
.path
.basename(self
.subunit_path
),
177 self
.subunit
= open(self
.subunit_path
, 'w')
179 formatter
= subunithelper
.PlainFormatter(False, True, {})
180 clients
= [formatter
, subunit
.TestProtocolClient(self
.subunit
)]
182 clients
.append(AbortingTestResult(self
))
183 self
.subunit_server
= subunit
.TestProtocolServer(
184 testtools
.MultiTestResult(*clients
),
189 print '%s: [%s] Running' % (self
.tree
.name
, self
.name
)
190 self
.proc
= Popen(self
.command
, shell
=True, cwd
=self
.tree
.dir,
191 stdout
=PIPE
, stderr
=self
.tree
.stderr
, stdin
=self
.stdin
)
192 fd
= self
.proc
.stdout
.fileno()
193 fl
= fcntl
.fcntl(fd
, fcntl
.F_GETFL
)
194 fcntl
.fcntl(fd
, fcntl
.F_SETFL
, fl | os
.O_NONBLOCK
)
198 data
= self
.proc
.stdout
.read()
202 self
.buffered
+= data
204 for l
in self
.buffered
.splitlines(True):
206 self
.subunit_server
.lineReceived(l
)
209 self
.buffered
= buffered
210 self
.status
= self
.proc
.poll()
211 if self
.status
is not None:
216 class TreeBuilder(object):
217 '''handle build of one directory'''
219 def __init__(self
, name
, sequence
, fail_quickly
=False):
221 self
.fail_quickly
= fail_quickly
223 self
.tag
= self
.name
.replace('/', '_')
224 self
.sequence
= sequence
226 self
.stdout_path
= os
.path
.join(gitroot
, "%s.stdout" % (self
.tag
, ))
227 self
.stderr_path
= os
.path
.join(gitroot
, "%s.stderr" % (self
.tag
, ))
229 (self
.stdout_path
, os
.path
.basename(self
.stdout_path
), "text/plain"),
230 (self
.stderr_path
, os
.path
.basename(self
.stderr_path
), "text/plain"),
233 print("stdout for %s in %s" % (self
.name
, self
.stdout_path
))
234 print("stderr for %s in %s" % (self
.name
, self
.stderr_path
))
235 if os
.path
.exists(self
.stdout_path
):
236 os
.unlink(self
.stdout_path
)
237 if os
.path
.exists(self
.stderr_path
):
238 os
.unlink(self
.stderr_path
)
239 self
.stdout
= open(self
.stdout_path
, 'w')
240 self
.stderr
= open(self
.stderr_path
, 'w')
241 self
.sdir
= os
.path
.join(testbase
, self
.tag
)
242 if name
in ['pass', 'fail', 'retry']:
245 self
.dir = os
.path
.join(self
.sdir
, self
.name
)
246 self
.prefix
= os
.path
.join(testbase
, "prefix", self
.tag
)
247 run_cmd(["rm", "-rf", self
.sdir
])
248 cleanup_list
.append(self
.sdir
)
249 cleanup_list
.append(self
.prefix
)
250 os
.makedirs(self
.sdir
)
251 run_cmd(["rm", "-rf", self
.sdir
])
252 clone_gitroot(self
.sdir
, revision
)
255 def start_next(self
):
256 if self
.next
== len(self
.sequence
):
257 print '%s: Completed OK' % self
.name
262 (stage_name
, cmd
, output_mime_type
) = self
.sequence
[self
.next
]
263 cmd
= cmd
.replace("${PREFIX}", "--prefix=%s" % self
.prefix
)
264 if output_mime_type
== "text/plain":
265 self
.stage
= PlainTreeStageBuilder(self
, stage_name
, cmd
,
267 elif output_mime_type
== "text/x-subunit":
268 self
.stage
= SubunitTreeStageBuilder(self
, stage_name
, cmd
,
271 raise Exception("Unknown output mime type %s" % output_mime_type
)
275 def remove_logs(self
):
276 for path
, name
, mime_type
in self
.logfiles
:
281 return self
.stage
.status
284 return self
.stage
.poll()
287 if self
.stage
is not None:
293 if self
.stage
is None:
295 return self
.stage
.failed
298 def failure_reason(self
):
299 return "%s: [%s] %s" % (self
.name
, self
.stage
.name
,
300 self
.stage
.failure_reason
)
303 class BuildList(object):
304 '''handle build of multiple directories'''
306 def __init__(self
, tasklist
, tasknames
):
309 self
.tail_proc
= None
311 if tasknames
== ['pass']:
312 tasks
= { 'pass' : [ ("pass", '/bin/true', "text/plain") ]}
313 if tasknames
== ['fail']:
314 tasks
= { 'fail' : [ ("fail", '/bin/false', "text/plain") ]}
318 b
= TreeBuilder(n
, tasks
[n
], not options
.fail_slowly
)
321 self
.retry
= TreeBuilder('retry', retry_task
,
322 not options
.fail_slowly
)
323 self
.need_retry
= False
326 if self
.tail_proc
is not None:
327 self
.tail_proc
.terminate()
328 self
.tail_proc
.wait()
329 self
.tail_proc
= None
330 if self
.retry
is not None:
331 self
.retry
.proc
.terminate()
332 self
.retry
.proc
.wait()
349 ret
= self
.retry
.proc
.poll()
351 self
.need_retry
= True
361 if options
.retry
and self
.need_retry
:
363 print("retry needed")
364 return (0, None, None, None, "retry")
369 return (b
.status
, b
.name
, b
.stage
, b
.tag
, b
.failure_reason
)
372 return (0, None, None, None, "All OK")
374 def tarlogs(self
, name
=None, fileobj
=None):
375 tar
= tarfile
.open(name
=name
, fileobj
=fileobj
, mode
="w:gz")
377 for (path
, name
, mime_type
) in b
.logfiles
:
378 tar
.add(path
, arcname
=name
)
379 if os
.path
.exists("autobuild.log"):
380 tar
.add("autobuild.log")
383 def attach_logs(self
, outer
):
385 self
.tarlogs(fileobj
=f
)
386 msg
= MIMEApplication(f
.getvalue(), "x-gzip")
387 msg
.add_header('Content-Disposition', 'attachment',
388 filename
="logs.tar.gz")
391 def remove_logs(self
):
395 def start_tail(self
):
396 cmd
= "tail -f *.stdout *.stderr"
397 self
.tail_proc
= Popen(cmd
, shell
=True, cwd
=gitroot
)
401 if options
.nocleanup
:
403 print("Cleaning up ....")
404 for d
in cleanup_list
:
405 run_cmd(["rm", "-rf", d
])
408 def find_git_root(p
):
409 '''get to the top of the git repo'''
411 if os
.path
.isdir(os
.path
.join(p
, ".git")):
413 p
= os
.path
.abspath(os
.path
.join(p
, '..'))
417 def daemonize(logfile
):
419 if pid
== 0: # Parent
422 if pid
!= 0: # Actual daemon
427 import resource
# Resource usage information.
428 maxfd
= resource
.getrlimit(resource
.RLIMIT_NOFILE
)[1]
429 if maxfd
== resource
.RLIM_INFINITY
:
430 maxfd
= 1024 # Rough guess at maximum number of open file descriptors.
431 for fd
in range(0, maxfd
):
436 os
.open(logfile
, os
.O_RDWR | os
.O_CREAT
)
441 def rebase_tree(url
):
442 print("Rebasing on %s" % url
)
443 run_cmd(["git", "remote", "add", "-t", "master", "master", url
], show
=True,
445 run_cmd(["git", "fetch", "master"], show
=True, dir=test_master
)
446 if options
.fix_whitespace
:
447 run_cmd(["git", "rebase", "--whitespace=fix", "master/master"],
448 show
=True, dir=test_master
)
450 run_cmd(["git", "rebase", "master/master"], show
=True, dir=test_master
)
451 diff
= run_cmd(["git", "--no-pager", "diff", "HEAD", "master/master"],
452 dir=test_master
, output
=True)
454 print("No differences between HEAD and master/master - exiting")
458 print("Pushing to %s" % url
)
460 run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD",
461 dir=test_master
, shell
=True)
462 # the notes method doesn't work yet, as metze hasn't allowed
463 # refs/notes/* in master
464 # run_cmd("EDITOR=script/commit_mark.sh git notes edit HEAD",
466 run_cmd(["git", "remote", "add", "-t", "master", "pushto", url
], show
=True,
468 run_cmd(["git", "push", "pushto", "+HEAD:master"], show
=True,
471 def_testbase
= os
.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os
.getenv('USER'))
473 parser
= OptionParser()
474 parser
.add_option("--repository", help="repository to run tests for", default
=None, type=str)
475 parser
.add_option("--revision", help="revision to compile if not HEAD", default
=None, type=str)
476 parser
.add_option("--tail", help="show output while running", default
=False, action
="store_true")
477 parser
.add_option("--keeplogs", help="keep logs", default
=False, action
="store_true")
478 parser
.add_option("--nocleanup", help="don't remove test tree", default
=False, action
="store_true")
479 parser
.add_option("--testbase", help="base directory to run tests in (default %s)" % def_testbase
,
480 default
=def_testbase
)
481 parser
.add_option("--passcmd", help="command to run on success", default
=None)
482 parser
.add_option("--verbose", help="show all commands as they are run",
483 default
=False, action
="store_true")
484 parser
.add_option("--rebase", help="rebase on the given tree before testing",
485 default
=None, type='str')
486 parser
.add_option("--rebase-master", help="rebase on %s before testing" % samba_master
,
487 default
=False, action
='store_true')
488 parser
.add_option("--pushto", help="push to a git url on success",
489 default
=None, type='str')
490 parser
.add_option("--push-master", help="push to %s on success" % samba_master_ssh
,
491 default
=False, action
='store_true')
492 parser
.add_option("--mark", help="add a Tested-By signoff before pushing",
493 default
=False, action
="store_true")
494 parser
.add_option("--fix-whitespace", help="fix whitespace on rebase",
495 default
=False, action
="store_true")
496 parser
.add_option("--retry", help="automatically retry if master changes",
497 default
=False, action
="store_true")
498 parser
.add_option("--email", help="send email to the given address on failure",
499 type='str', default
=None)
500 parser
.add_option("--always-email", help="always send email, even on success",
502 parser
.add_option("--daemon", help="daemonize after initial setup",
504 parser
.add_option("--fail-slowly", help="continue running tests even after one has already failed",
508 def email_failure(blist
, status
, failed_task
, failed_stage
, failed_tag
, errstr
):
509 '''send an email to options.email about the failure'''
510 user
= os
.getenv("USER")
514 Your autobuild failed when trying to test %s with the following error:
517 the autobuild has been abandoned. Please fix the error and resubmit.
519 You can see logs of the failed task here:
521 http://git.samba.org/%s/samba-autobuild/%s.stdout
522 http://git.samba.org/%s/samba-autobuild/%s.stderr
524 A summary of the autobuild process is here:
526 http://git.samba.org/%s/samba-autobuild/autobuild.log
528 or you can get full logs of all tasks in this job here:
530 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
532 The top commit for the tree that was built was:
536 ''' % (failed_task
, errstr
, user
, failed_tag
, user
, failed_tag
, user
, user
,
537 get_top_commit_msg(test_master
))
539 msg
= MIMEMultipart()
540 msg
['Subject'] = 'autobuild failure for task %s during %s' % (
541 failed_task
, failed_stage
)
542 msg
['From'] = 'autobuild@samba.org'
543 msg
['To'] = options
.email
545 main
= MIMEText(text
)
548 blist
.attach_logs(msg
)
552 s
.sendmail(msg
['From'], [msg
['To']], msg
.as_string())
555 def email_success(blist
):
556 '''send an email to options.email about a successful build'''
557 user
= os
.getenv("USER")
561 Your autobuild has succeeded.
568 you can get full logs of all tasks in this job here:
570 http://git.samba.org/%s/samba-autobuild/logs.tar.gz
575 The top commit for the tree that was built was:
578 ''' % (get_top_commit_msg(test_master
),)
580 msg
= MIMEMultipart()
581 msg
['Subject'] = 'autobuild success'
582 msg
['From'] = 'autobuild@samba.org'
583 msg
['To'] = options
.email
585 main
= MIMEText(text
, 'plain')
588 blist
.attach_logs(msg
)
592 s
.sendmail(msg
['From'], [msg
['To']], msg
.as_string())
596 (options
, args
) = parser
.parse_args()
599 if not options
.rebase_master
and options
.rebase
is None:
600 raise Exception('You can only use --retry if you also rebase')
602 testbase
= os
.path
.join(options
.testbase
, "b%u" % (os
.getpid(),))
603 test_master
= os
.path
.join(testbase
, "master")
605 if options
.repository
is not None:
606 repository
= options
.repository
608 repository
= os
.getcwd()
610 gitroot
= find_git_root(repository
)
612 raise Exception("Failed to find git root under %s" % repository
)
614 # get the top commit message, for emails
615 if options
.revision
is not None:
616 revision
= options
.revision
620 def get_top_commit_msg(reporoot
):
621 return run_cmd(["git", "log", "-1"], dir=reporoot
, output
=True)
624 os
.makedirs(testbase
)
625 except Exception, reason
:
626 raise Exception("Unable to create %s : %s" % (testbase
, reason
))
627 cleanup_list
.append(testbase
)
630 logfile
= os
.path
.join(testbase
, "log")
631 print "Forking into the background, writing progress to %s" % logfile
636 run_cmd(["rm", "-rf", test_master
])
637 cleanup_list
.append(test_master
)
638 clone_gitroot(test_master
, revision
)
644 if options
.rebase
is not None:
645 rebase_tree(options
.rebase
)
646 elif options
.rebase_master
:
647 rebase_tree(samba_master
)
648 blist
= BuildList(tasks
, args
)
651 (status
, failed_task
, failed_stage
, failed_tag
, errstr
) = blist
.run()
652 if status
!= 0 or errstr
!= "retry":
661 print("waiting for tail to flush")
666 if options
.passcmd
is not None:
667 print("Running passcmd: %s" % options
.passcmd
)
668 run_cmd(options
.passcmd
, dir=test_master
, shell
=True)
669 if options
.pushto
is not None:
670 push_to(options
.pushto
)
671 elif options
.push_master
:
672 push_to(samba_master_ssh
)
674 blist
.tarlogs("logs.tar.gz")
675 print("Logs in logs.tar.gz")
676 if options
.always_email
:
682 # something failed, gather a tar of the logs
683 blist
.tarlogs("logs.tar.gz")
685 if options
.email
is not None:
686 email_failure(blist
, status
, failed_task
, failed_stage
, failed_tag
,
691 print("Logs in logs.tar.gz")