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