autobuild: added --rebase-master and --push-master
[kai/samba-autobuild/.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 Popen, PIPE
7 import os, signal, tarfile, sys, time
8 from optparse import OptionParser
9
10
11 samba_master = os.getenv('SAMBA_MASTER', 'git://git.samba.org/samba.git')
12 samba_master_ssh = os.getenv('SAMBA_MASTER_SSH', 'git+ssh://git.samba.org/data/git/samba.git')
13
14 cleanup_list = []
15
16 tasks = {
17     "source3" : [ "./autogen.sh",
18                   "./configure.developer ${PREFIX}",
19                   "make basics",
20                   "make -j 4 everything", # don't use too many processes
21                   "make install",
22                   "TDB_NO_FSYNC=1 make test" ],
23
24     "source4" : [ "./autogen.sh",
25                   "./configure.developer ${PREFIX}",
26                   "make -j",
27                   "make install",
28                   "TDB_NO_FSYNC=1 make test" ],
29
30     "source4/lib/ldb" : [ "./autogen-waf.sh",
31                           "./configure --enable-developer -C ${PREFIX}",
32                           "make -j",
33                           "make install",
34                           "make test" ],
35
36     "lib/tdb" : [ "./autogen-waf.sh",
37                   "./configure --enable-developer -C ${PREFIX}",
38                   "make -j",
39                   "make install",
40                   "make test" ],
41
42     "lib/talloc" : [ "./autogen-waf.sh",
43                      "./configure --enable-developer -C ${PREFIX}",
44                      "make -j",
45                      "make install",
46                      "make test" ],
47
48     "lib/replace" : [ "./autogen-waf.sh",
49                       "./configure --enable-developer -C ${PREFIX}",
50                       "make -j",
51                       "make install",
52                       "make test" ],
53
54     "lib/tevent" : [ "./autogen-waf.sh",
55                      "./configure --enable-developer -C ${PREFIX}",
56                      "make -j",
57                      "make install",
58                      "make test" ],
59 }
60
61 def run_cmd(cmd, dir=".", show=None):
62     cwd = os.getcwd()
63     os.chdir(dir)
64     if show is None:
65         show = options.verbose
66     if show:
67         print("Running: '%s' in '%s'" % (cmd, dir))
68     ret = os.system(cmd)
69     os.chdir(cwd)
70     if ret != 0:
71         raise Exception("FAILED %s: %d" % (cmd, ret))
72
73 class builder:
74     '''handle build of one directory'''
75     def __init__(self, name, sequence):
76         self.name = name
77         self.dir = self.name
78         if name == 'pass' or name == 'fail':
79             self.dir = "."
80         self.tag = self.name.replace('/', '_')
81         self.sequence = sequence
82         self.next = 0
83         self.stdout_path = "%s/%s.stdout" % (testbase, self.tag)
84         self.stderr_path = "%s/%s.stderr" % (testbase, self.tag)
85         cleanup_list.append(self.stdout_path)
86         cleanup_list.append(self.stderr_path)
87         run_cmd("rm -f %s %s" % (self.stdout_path, self.stderr_path))
88         self.stdout = open(self.stdout_path, 'w')
89         self.stderr = open(self.stderr_path, 'w')
90         self.stdin  = open("/dev/null", 'r')
91         self.sdir = "%s/%s" % (testbase, self.tag)
92         self.prefix = "%s/prefix/%s" % (testbase, self.tag)
93         run_cmd("rm -rf %s" % self.sdir)
94         cleanup_list.append(self.sdir)
95         cleanup_list.append(self.prefix)
96         os.makedirs(self.sdir)
97         run_cmd("rm -rf %s" % self.sdir)
98         run_cmd("git clone --shared %s %s" % (gitroot, self.sdir))
99         self.start_next()
100
101     def start_next(self):
102         if self.next == len(self.sequence):
103             print '%s: Completed OK' % self.name
104             self.done = True
105             return
106         self.cmd = self.sequence[self.next].replace("${PREFIX}", "--prefix=%s" % self.prefix)
107         print '%s: Running %s' % (self.name, self.cmd)
108         cwd = os.getcwd()
109         os.chdir("%s/%s" % (self.sdir, self.dir))
110         self.proc = Popen(self.cmd, shell=True,
111                           stdout=self.stdout, stderr=self.stderr, stdin=self.stdin)
112         os.chdir(cwd)
113         self.next += 1
114
115
116 class buildlist:
117     '''handle build of multiple directories'''
118     def __init__(self, tasklist, tasknames):
119         self.tlist = []
120         self.tail_proc = None
121         if tasknames == ['pass']:
122             tasks = { 'pass' : [ '/bin/true' ]}
123         if tasknames == ['fail']:
124             tasks = { 'fail' : [ '/bin/false' ]}
125         if tasknames == []:
126             tasknames = tasklist
127         for n in tasknames:
128             b = builder(n, tasks[n])
129             self.tlist.append(b)
130
131     def kill_kids(self):
132         for b in self.tlist:
133             if b.proc is not None:
134                 b.proc.terminate()
135                 b.proc.wait()
136                 b.proc = None
137         if self.tail_proc is not None:
138             self.tail_proc.terminate()
139             self.tail_proc.wait()
140             self.tail_proc = None
141
142     def wait_one(self):
143         while True:
144             none_running = True
145             for b in self.tlist:
146                 if b.proc is None:
147                     continue
148                 none_running = False
149                 b.status = b.proc.poll()
150                 if b.status is None:
151                     continue
152                 b.proc = None
153                 return b
154             if none_running:
155                 return None
156             time.sleep(0.1)
157
158     def run(self):
159         while True:
160             b = self.wait_one()
161             if b is None:
162                 break
163             if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
164                 self.kill_kids()
165                 return (b.status, "%s: failed '%s' with status %d" % (b.name, b.cmd, b.status))
166             b.start_next()
167         self.kill_kids()
168         return (0, "All OK")
169
170     def tarlogs(self, fname):
171         tar = tarfile.open(fname, "w:gz")
172         for b in self.tlist:
173             tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
174             tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
175         tar.close()
176
177     def remove_logs(self):
178         for b in self.tlist:
179             os.unlink(b.stdout_path)
180             os.unlink(b.stderr_path)
181
182     def start_tail(self):
183         cwd = os.getcwd()
184         cmd = "tail -f *.stdout *.stderr"
185         os.chdir(testbase)
186         self.tail_proc = Popen(cmd, shell=True)
187         os.chdir(cwd)
188
189
190 def cleanup():
191     if options.nocleanup:
192         return
193     print("Cleaning up ....")
194     for d in cleanup_list:
195         run_cmd("rm -rf %s" % d)
196
197
198 def find_git_root():
199     '''get to the top of the git repo'''
200     cwd=os.getcwd()
201     while os.getcwd() != '/':
202         try:
203             os.stat(".git")
204             ret = os.getcwd()
205             os.chdir(cwd)
206             return ret
207         except:
208             os.chdir("..")
209             pass
210     os.chdir(cwd)
211     return None
212
213 def rebase_tree(url):
214     print("Rebasing on %s" % url)
215     run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
216     run_cmd("git fetch master", show=True, dir=test_master)
217     run_cmd("git rebase master/master", show=True, dir=test_master)
218
219 def push_to(url):
220     print("Pushing to %s" % url)
221     if options.mark:
222         run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD", dir=test_master)
223     run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
224     run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
225
226 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
227
228 parser = OptionParser()
229 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
230 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
231 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
232 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
233                   default=def_testbase)
234 parser.add_option("", "--passcmd", help="command to run on success", default=None)
235 parser.add_option("", "--verbose", help="show all commands as they are run",
236                   default=False, action="store_true")
237 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
238                   default=None, type='str')
239 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
240                   default=False, action='store_true')
241 parser.add_option("", "--pushto", help="push to a git url on success",
242                   default=None, type='str')
243 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
244                   default=False, action='store_true')
245 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
246                   default=False, action="store_true")
247
248
249 (options, args) = parser.parse_args()
250
251 testbase = "%s/build.%u" % (options.testbase, os.getpid())
252 test_master = "%s/master" % testbase
253
254 gitroot = find_git_root()
255 if gitroot is None:
256     raise Exception("Failed to find git root")
257
258 try:
259     os.makedirs(testbase)
260 except Exception, reason:
261     raise Exception("Unable to create %s : %s" % (testbase, reason))
262 cleanup_list.append(testbase)
263
264 try:
265     run_cmd("rm -rf %s" % test_master)
266     cleanup_list.append(test_master)
267     run_cmd("git clone --shared %s %s" % (gitroot, test_master))
268 except:
269     cleanup()
270     raise
271
272 try:
273     if options.rebase is not None:
274         rebase_tree(options.rebase)
275     elif options.rebase_master:
276         rebase_tree(samba_master)
277     blist = buildlist(tasks, args)
278     if options.tail:
279         blist.start_tail()
280     (status, errstr) = blist.run()
281 except:
282     cleanup()
283     raise
284
285 blist.kill_kids()
286 if options.tail:
287     print("waiting for tail to flush")
288     time.sleep(1)
289
290 if status == 0:
291     print errstr
292     if options.passcmd is not None:
293         print("Running passcmd: %s" % options.passcmd)
294         run_cmd(options.passcmd, dir=test_master)
295     if options.pushto is not None:
296         push_to(options.pushto)
297     elif options.push_master:
298         push_to(samba_master_ssh)
299     if options.keeplogs:
300         blist.tarlogs("logs.tar.gz")
301         print("Logs in logs.tar.gz")
302     blist.remove_logs()
303     cleanup()
304     print(errstr)
305     sys.exit(0)
306
307 # something failed, gather a tar of the logs
308 blist.tarlogs("logs.tar.gz")
309 blist.remove_logs()
310 cleanup()
311 print(errstr)
312 print("Logs in logs.tar.gz")
313 sys.exit(os.WEXITSTATUS(status))