2 # Simple database query script for the buildfarm
4 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2001-2005
5 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001
6 # Copyright (C) Vance Lankhaar <vance@samba.org> 2002-2005
7 # Copyright (C) Martin Pool <mbp@samba.org> 2001
8 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 from cStringIO import StringIO
29 from storm.locals import Int, RawStr
30 from storm.store import Store
31 from storm.expr import Desc
37 def __init__(self, name):
42 class TestResult(object):
44 def __init__(self, build, test, result):
50 class BuildSummary(object):
52 def __init__(self, host, tree, compiler, revision, status):
55 self.compiler = compiler
56 self.revision = revision
60 BuildStageResult = collections.namedtuple("BuildStageResult", "name result")
63 class MissingRevisionInfo(Exception):
64 """Revision info could not be found in the build log."""
66 def __init__(self, build=None):
70 class LogFileMissing(Exception):
71 """Log file missing."""
74 class BuildStatus(object):
76 def __init__(self, stages=None, other_failures=None):
77 if stages is not None:
78 self.stages = [BuildStageResult(n, r) for (n, r) in stages]
81 if other_failures is not None:
82 self.other_failures = other_failures
84 self.other_failures = set()
88 if self.other_failures:
90 return not all([x.result == 0 for x in self.stages])
92 def __serialize__(self):
96 def __deserialize__(cls, text):
100 if self.other_failures:
101 return ",".join(self.other_failures)
102 return "/".join([str(x.result) for x in self.stages])
104 def broken_host(self):
105 if "disk full" in self.other_failures:
109 def regressed_since(self, older):
110 """Check if this build has regressed since another build."""
111 if "disk full" in self.other_failures:
113 if ("timeout" in self.other_failures and
114 "timeout" in older.other_failures):
115 # When the timeout happens exactly can differ slightly, so it's
116 # okay if the numbers are a bit different..
118 if ("panic" in self.other_failures and
119 not "panic" in older.other_failures):
121 if len(self.stages) < len(older.stages):
122 # Less stages completed
124 for ((old_name, old_result), (new_name, new_result)) in zip(
125 older.stages, self.stages):
126 assert old_name == new_name
127 if new_result > old_result:
131 def __cmp__(self, other):
132 other_extra = other.other_failures - self.other_failures
133 self_extra = self.other_failures - other.other_failures
134 # Give more importance to other failures
140 la = len(self.stages)
141 lb = len(other.stages)
147 return cmp(other.stages, self.stages)
150 return "%s(%r, %r)" % (self.__class__.__name__, self.stages, self.other_failures)
153 def check_dir_exists(kind, path):
154 if not os.path.isdir(path):
155 raise Exception("%s directory %s does not exist" % (kind, path))
158 def build_status_from_logs(log, err):
159 """get status of build"""
160 # FIXME: Perhaps also extract revision here?
168 re_status = re.compile("^([A-Z_]+) STATUS:(\s*\d+)$")
169 re_action = re.compile("^ACTION (PASSED|FAILED):\s+test$")
172 if l.startswith("No space left on device"):
173 ret.other_failures.add("disk full")
175 if "Maximum time expired in timelimit" in l: # Ugh.
176 ret.other_failures.add("timeout")
178 if "maximum runtime exceeded" in l: # Ugh.
179 ret.other_failures.add("timeout")
181 if l.startswith("PANIC:") or l.startswith("INTERNAL ERROR:"):
182 ret.other_failures.add("panic")
184 if l.startswith("testsuite-failure: ") or l.startswith("testsuite-error: "):
187 if l.startswith("testsuite-success: "):
190 m = re_status.match(l)
192 stages.append(BuildStageResult(m.group(1), int(m.group(2).strip())))
193 if m.group(1) == "TEST":
196 m = re_action.match(l)
197 if m and not test_seen:
198 if m.group(1) == "PASSED":
199 stages.append(BuildStageResult("TEST", 0))
201 stages.append(BuildStageResult("TEST", 1))
204 # Scan err file for specific errors
206 if "No space left on device" in l:
207 ret.other_failures.add("disk full")
210 if sr.name != "TEST":
213 if test_successes + test_failures == 0:
214 # No granular test output
215 return BuildStageResult("TEST", sr.result)
216 if sr.result == 1 and test_failures == 0:
217 ret.other_failures.add("inconsistent test result")
218 return BuildStageResult("TEST", -1)
219 return BuildStageResult("TEST", test_failures)
221 ret.stages = map(map_stage, stages)
225 def revision_from_log(log):
228 if l.startswith("BUILD COMMIT REVISION: "):
229 revid = l.split(":", 1)[1].strip()
231 raise MissingRevisionInfo()
235 class NoSuchBuildError(Exception):
236 """The build with the specified name does not exist."""
238 def __init__(self, tree, host, compiler, rev=None):
241 self.compiler = compiler
246 """A single build of a tree on a particular host using a particular compiler.
249 def __init__(self, basename, tree, host, compiler, rev=None):
250 self.basename = basename
253 self.compiler = compiler
256 def __cmp__(self, other):
258 (self.upload_time, self.revision, self.host, self.tree, self.compiler),
259 (other.upload_time, other.revision, other.host, other.tree, other.compiler))
261 def __eq__(self, other):
262 return (isinstance(other, Build) and
263 self.log_checksum() == other.log_checksum())
266 if self.revision is not None:
267 return "<%s: revision %s of %s on %s using %s>" % (self.__class__.__name__, self.revision, self.tree, self.host, self.compiler)
269 return "<%s: %s on %s using %s>" % (self.__class__.__name__, self.tree, self.host, self.compiler)
271 def remove_logs(self):
272 # In general, basename.log should *always* exist.
273 if os.path.exists(self.basename+".log"):
274 os.unlink(self.basename + ".log")
275 if os.path.exists(self.basename+".err"):
276 os.unlink(self.basename+".err")
282 def upload_time(self):
283 """get timestamp of build"""
284 st = os.stat("%s.log" % self.basename)
289 """get the age of build"""
290 return time.time() - self.upload_time
293 """read full log file"""
295 return open(self.basename+".log", "r")
297 raise LogFileMissing()
300 """read full err file"""
302 return open(self.basename+".err", 'r')
307 def log_checksum(self):
310 return hashlib.sha1(f.read()).hexdigest()
315 revid = self.revision_details()
316 status = self.status()
317 return BuildSummary(self.host, self.tree, self.compiler, revid, status)
319 def revision_details(self):
320 """get the revision of build
326 return revision_from_log(f)
331 """get status of build
333 :return: tuple with build status
335 log = self.read_log()
337 err = self.read_err()
339 return build_status_from_logs(log, err)
346 """get status of build"""
347 file = self.read_err()
348 return len(file.readlines())
351 class UploadBuildResultStore(object):
353 def __init__(self, path):
354 """Open the database.
356 :param path: Build result base directory
360 def get_all_builds(self):
361 for name in os.listdir(self.path):
363 (build, tree, host, compiler, extension) = name.split(".")
366 if build != "build" or extension != "log":
368 yield self.get_build(tree, host, compiler)
370 def build_fname(self, tree, host, compiler):
371 return os.path.join(self.path, "build.%s.%s.%s" % (tree, host, compiler))
373 def has_host(self, host):
374 for name in os.listdir(self.path):
376 if name.split(".")[2] == host:
382 def get_build(self, tree, host, compiler):
383 basename = self.build_fname(tree, host, compiler)
384 logf = "%s.log" % basename
385 if not os.path.exists(logf):
386 raise NoSuchBuildError(tree, host, compiler)
387 return Build(basename, tree, host, compiler)
390 class StormBuild(Build):
391 __storm_table__ = "build"
393 id = Int(primary=True)
399 upload_time = Int(name="age")
400 status_str = RawStr(name="status")
407 return BuildStatus.__deserialize__(self.status_str)
409 def revision_details(self):
412 def log_checksum(self):
416 super(StormBuild, self).remove()
417 Store.of(self).remove(self)
419 def remove_logs(self):
420 super(StormBuild, self).remove_logs()
424 class BuildResultStore(object):
425 """The build farm build result database."""
427 def __init__(self, basedir, store=None):
428 from buildfarm.sqldb import memory_store
430 store = memory_store()
435 def __contains__(self, build):
437 self.get_by_checksum(build.log_checksum())
439 except NoSuchBuildError:
442 def get_build(self, tree, host, compiler, revision=None, checksum=None):
443 from buildfarm.sqldb import Cast
445 Cast(StormBuild.tree, "TEXT") == Cast(tree, "TEXT"),
446 Cast(StormBuild.host, "TEXT") == Cast(host, "TEXT"),
447 Cast(StormBuild.compiler, "TEXT") == Cast(compiler, "TEXT"),
449 if revision is not None:
450 expr.append(Cast(StormBuild.revision, "TEXT") == Cast(revision, "TEXT"))
451 if checksum is not None:
452 expr.append(Cast(StormBuild.checksum, "TEXT") == Cast(checksum, "TEXT"))
453 result = self.store.find(StormBuild, *expr).order_by(Desc(StormBuild.upload_time))
456 raise NoSuchBuildError(tree, host, compiler, revision)
459 def build_fname(self, tree, host, compiler, rev):
460 """get the name of the build file"""
461 return os.path.join(self.path, "build.%s.%s.%s-%s" % (tree, host, compiler, rev))
463 def get_all_builds(self):
464 for l in os.listdir(self.path):
465 m = re.match("^build\.([0-9A-Za-z]+)\.([0-9A-Za-z]+)\.([0-9A-Za-z]+)-([0-9A-Fa-f]+).log$", l)
470 compiler = m.group(3)
472 stat = os.stat(os.path.join(self.path, l))
473 # skip the current build
474 if stat.st_nlink == 2:
476 yield self.get_build(tree, host, compiler, rev)
478 def get_old_builds(self, tree, host, compiler):
479 result = self.store.find(StormBuild,
480 StormBuild.tree == tree,
481 StormBuild.host == host,
482 StormBuild.compiler == compiler)
483 return result.order_by(Desc(StormBuild.upload_time))
485 def upload_build(self, build):
486 from buildfarm.sqldb import Cast, StormHost
488 existing_build = self.get_by_checksum(build.log_checksum())
489 except NoSuchBuildError:
493 assert build.tree == existing_build.tree
494 assert build.host == existing_build.host
495 assert build.compiler == existing_build.compiler
496 return existing_build
497 rev = build.revision_details()
499 new_basename = self.build_fname(build.tree, build.host, build.compiler, rev)
501 existing_build = self.get_build(build.tree, build.host, build.compiler, rev)
502 except NoSuchBuildError:
503 if os.path.exists(new_basename+".log"):
504 os.remove(new_basename+".log")
505 if os.path.exists(new_basename+".err"):
506 os.remove(new_basename+".err")
508 existing_build.remove_logs()
509 os.link(build.basename+".log", new_basename+".log")
510 if os.path.exists(build.basename+".err"):
511 os.link(build.basename+".err", new_basename+".err")
512 new_basename = self.build_fname(build.tree, build.host, build.compiler,
514 new_build = StormBuild(new_basename, build.tree, build.host,
516 new_build.checksum = build.log_checksum()
517 new_build.upload_time = build.upload_time
518 new_build.status_str = build.status().__serialize__()
519 new_build.basename = new_basename
520 host = self.store.find(StormHost,
521 Cast(StormHost.name, "TEXT") == Cast(build.host, "TEXT")).one()
522 assert host is not None, "Unable to find host %r" % build.host
523 new_build.host_id = host.id
524 self.store.add(new_build)
527 def get_by_checksum(self, checksum):
528 from buildfarm.sqldb import Cast
529 result = self.store.find(StormBuild,
530 Cast(StormBuild.checksum, "TEXT") == checksum)
533 raise NoSuchBuildError(None, None, None, None)
536 def get_previous_revision(self, tree, host, compiler, revision):
537 from buildfarm.sqldb import Cast
538 cur_build = self.get_build(tree, host, compiler, revision)
540 result = self.store.find(StormBuild,
541 Cast(StormBuild.tree, "TEXT") == Cast(tree, "TEXT"),
542 Cast(StormBuild.host, "TEXT") == Cast(host, "TEXT"),
543 Cast(StormBuild.compiler, "TEXT") == Cast(compiler, "TEXT"),
544 Cast(StormBuild.revision, "TEXT") != Cast(revision, "TEXT"),
545 StormBuild.id < cur_build.id)
546 result = result.order_by(Desc(StormBuild.id))
547 prev_build = result.first()
548 if prev_build is None:
549 raise NoSuchBuildError(tree, host, compiler, revision)
550 return prev_build.revision
552 def get_latest_revision(self, tree, host, compiler):
553 result = self.store.find(StormBuild,
554 StormBuild.tree == tree,
555 StormBuild.host == host,
556 StormBuild.compiler == compiler)
557 result = result.order_by(Desc(StormBuild.id))
558 build = result.first()
560 raise NoSuchBuildError(tree, host, compiler)
561 return build.revision