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