autobuild: added --fix-whitespace option
[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 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         global tasks
120         self.tlist = []
121         self.tail_proc = None
122         if tasknames == ['pass']:
123             tasks = { 'pass' : [ '/bin/true' ]}
124         if tasknames == ['fail']:
125             tasks = { 'fail' : [ '/bin/false' ]}
126         if tasknames == []:
127             tasknames = tasklist
128         for n in tasknames:
129             b = builder(n, tasks[n])
130             self.tlist.append(b)
131
132     def kill_kids(self):
133         for b in self.tlist:
134             if b.proc is not None:
135                 b.proc.terminate()
136                 b.proc.wait()
137                 b.proc = None
138         if self.tail_proc is not None:
139             self.tail_proc.terminate()
140             self.tail_proc.wait()
141             self.tail_proc = None
142
143     def wait_one(self):
144         while True:
145             none_running = True
146             for b in self.tlist:
147                 if b.proc is None:
148                     continue
149                 none_running = False
150                 b.status = b.proc.poll()
151                 if b.status is None:
152                     continue
153                 b.proc = None
154                 return b
155             if none_running:
156                 return None
157             time.sleep(0.1)
158
159     def run(self):
160         while True:
161             b = self.wait_one()
162             if b is None:
163                 break
164             if os.WIFSIGNALED(b.status) or os.WEXITSTATUS(b.status) != 0:
165                 self.kill_kids()
166                 return (b.status, "%s: failed '%s' with status %d" % (b.name, b.cmd, b.status))
167             b.start_next()
168         self.kill_kids()
169         return (0, "All OK")
170
171     def tarlogs(self, fname):
172         tar = tarfile.open(fname, "w:gz")
173         for b in self.tlist:
174             tar.add(b.stdout_path, arcname="%s.stdout" % b.tag)
175             tar.add(b.stderr_path, arcname="%s.stderr" % b.tag)
176         tar.close()
177
178     def remove_logs(self):
179         for b in self.tlist:
180             os.unlink(b.stdout_path)
181             os.unlink(b.stderr_path)
182
183     def start_tail(self):
184         cwd = os.getcwd()
185         cmd = "tail -f *.stdout *.stderr"
186         os.chdir(testbase)
187         self.tail_proc = Popen(cmd, shell=True)
188         os.chdir(cwd)
189
190
191 def cleanup():
192     if options.nocleanup:
193         return
194     print("Cleaning up ....")
195     for d in cleanup_list:
196         run_cmd("rm -rf %s" % d)
197
198
199 def find_git_root():
200     '''get to the top of the git repo'''
201     cwd=os.getcwd()
202     while os.getcwd() != '/':
203         try:
204             os.stat(".git")
205             ret = os.getcwd()
206             os.chdir(cwd)
207             return ret
208         except:
209             os.chdir("..")
210             pass
211     os.chdir(cwd)
212     return None
213
214 def rebase_tree(url):
215     print("Rebasing on %s" % url)
216     run_cmd("git remote add -t master master %s" % url, show=True, dir=test_master)
217     run_cmd("git fetch master", show=True, dir=test_master)
218     if options.fix_whitespace:
219         run_cmd("git rebase --whitespace=fix master/master", show=True, dir=test_master)
220     else:
221         run_cmd("git rebase master/master", show=True, dir=test_master)
222
223 def push_to(url):
224     print("Pushing to %s" % url)
225     if options.mark:
226         run_cmd("EDITOR=script/commit_mark.sh git commit --amend -c HEAD", dir=test_master)
227     run_cmd("git remote add -t master pushto %s" % url, show=True, dir=test_master)
228     run_cmd("git push pushto +HEAD:master", show=True, dir=test_master)
229
230 def_testbase = os.getenv("AUTOBUILD_TESTBASE", "/memdisk/%s" % os.getenv('USER'))
231
232 parser = OptionParser()
233 parser.add_option("", "--tail", help="show output while running", default=False, action="store_true")
234 parser.add_option("", "--keeplogs", help="keep logs", default=False, action="store_true")
235 parser.add_option("", "--nocleanup", help="don't remove test tree", default=False, action="store_true")
236 parser.add_option("", "--testbase", help="base directory to run tests in (default %s)" % def_testbase,
237                   default=def_testbase)
238 parser.add_option("", "--passcmd", help="command to run on success", default=None)
239 parser.add_option("", "--verbose", help="show all commands as they are run",
240                   default=False, action="store_true")
241 parser.add_option("", "--rebase", help="rebase on the given tree before testing",
242                   default=None, type='str')
243 parser.add_option("", "--rebase-master", help="rebase on %s before testing" % samba_master,
244                   default=False, action='store_true')
245 parser.add_option("", "--pushto", help="push to a git url on success",
246                   default=None, type='str')
247 parser.add_option("", "--push-master", help="push to %s on success" % samba_master_ssh,
248                   default=False, action='store_true')
249 parser.add_option("", "--mark", help="add a Tested-By signoff before pushing",
250                   default=False, action="store_true")
251 parser.add_option("", "--fix-whitespace", help="fix whitespace on rebase",
252                   default=False, action="store_true")
253
254
255 (options, args) = parser.parse_args()
256
257 testbase = "%s/build.%u" % (options.testbase, os.getpid())
258 test_master = "%s/master" % testbase
259
260 gitroot = find_git_root()
261 if gitroot is None:
262     raise Exception("Failed to find git root")
263
264 try:
265     os.makedirs(testbase)
266 except Exception, reason:
267     raise Exception("Unable to create %s : %s" % (testbase, reason))
268 cleanup_list.append(testbase)
269
270 try:
271     run_cmd("rm -rf %s" % test_master)
272     cleanup_list.append(test_master)
273     run_cmd("git clone --shared %s %s" % (gitroot, test_master))
274 except:
275     cleanup()
276     raise
277
278 try:
279     if options.rebase is not None:
280         rebase_tree(options.rebase)
281     elif options.rebase_master:
282         rebase_tree(samba_master)
283     blist = buildlist(tasks, args)
284     if options.tail:
285         blist.start_tail()
286     (status, errstr) = blist.run()
287 except:
288     cleanup()
289     raise
290
291 blist.kill_kids()
292 if options.tail:
293     print("waiting for tail to flush")
294     time.sleep(1)
295
296 if status == 0:
297     print errstr
298     if options.passcmd is not None:
299         print("Running passcmd: %s" % options.passcmd)
300         run_cmd(options.passcmd, dir=test_master)
301     if options.pushto is not None:
302         push_to(options.pushto)
303     elif options.push_master:
304         push_to(samba_master_ssh)
305     if options.keeplogs:
306         blist.tarlogs("logs.tar.gz")
307         print("Logs in logs.tar.gz")
308     blist.remove_logs()
309     cleanup()
310     print(errstr)
311     sys.exit(0)
312
313 # something failed, gather a tar of the logs
314 blist.tarlogs("logs.tar.gz")
315 blist.remove_logs()
316 cleanup()
317 print(errstr)
318 print("Logs in logs.tar.gz")
319 sys.exit(os.WEXITSTATUS(status))