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