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