Support searching for builds by checksum.
[build-farm.git] / buildfarm / web / __init__.py
1 #!/usr/bin/python
2 # This CGI script presents the results of the build_farm build
3
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org>     2010
5 # Copyright (C) Matthieu Patou <mat@matws.net>         2010
6 #
7 # Based on the original web/build.pl:
8 #
9 # Copyright (C) Andrew Tridgell <tridge@samba.org>     2001-2005
10 # Copyright (C) Andrew Bartlett <abartlet@samba.org>   2001
11 # Copyright (C) Vance Lankhaar  <vance@samba.org>      2002-2005
12 # Copyright (C) Martin Pool <mbp@samba.org>            2001
13 # Copyright (C) Jelmer Vernooij <jelmer@samba.org>     2007-2009
14 #
15 #   This program is free software; you can redistribute it and/or modify
16 #   it under the terms of the GNU General Public License as published by
17 #   the Free Software Foundation; either version 3 of the License, or
18 #   (at your option) any later version.
19 #
20 #   This program is distributed in the hope that it will be useful,
21 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
22 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 #   GNU General Public License for more details.
24 #
25 #   You should have received a copy of the GNU General Public License
26 #   along with this program; if not, write to the Free Software
27 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28
29 """Buildfarm web frontend."""
30
31 # TODO: Allow filtering of the "Recent builds" list to show
32 # e.g. only broken builds or only builds that you care about.
33
34 from collections import defaultdict
35 import os
36
37 from buildfarm import (
38     data,
39     hostdb,
40     util,
41     )
42
43 import cgi
44 from pygments import highlight
45 from pygments.lexers.text import DiffLexer
46 from pygments.formatters import HtmlFormatter
47 import re
48 import time
49
50 import wsgiref.util
51 webdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "web"))
52
53 GITWEB_BASE = "http://gitweb.samba.org"
54 HISTORY_HORIZON = 1000
55
56 # this is automatically filled in
57 deadhosts = []
58
59 def get_param(form, param):
60     """get a param from the request, after sanitizing it"""
61     if param not in form:
62         return None
63
64     result = [s.replace(" ", "_") for s in form.getlist(param)]
65
66     for entry in result:
67         if re.match("[^a-zA-Z0-9\-\_\.]", entry):
68             raise Exception("Parameter %s is invalid" % param)
69
70     return result[0]
71
72
73 def html_build_status(status):
74     def span(classname, contents):
75         return "<span class=\"%s\">%s</span>" % (classname, contents)
76
77     def span_status(stage):
78         if stage.name == "CC_CHECKER":
79             if stage.result == 0:
80                 return span("status checker", "ok")
81             else:
82                 return span("status checker", stage.result)
83
84         if stage.result is None:
85             return span("status unknown", "?")
86         elif stage.result == 0:
87             return span("status passed", "ok")
88         else:
89             return span("status failed", stage.result)
90
91     ostatus = ""
92     if "panic" in status.other_failures:
93         ostatus += "/"+span("status panic", "PANIC")
94     if "disk full" in status.other_failures:
95         ostatus += "/"+span("status failed", "disk full")
96     if "timeout" in status.other_failures:
97         ostatus += "/"+span("status failed", "timeout")
98     if "inconsistent test result" in status.other_failures:
99         ostatus += "/"+span("status failed", "unexpected return code")
100     bstatus = "/".join([span_status(s) for s in status.stages])
101     if bstatus == "":
102         bstatus = "?"
103     return bstatus + ostatus
104
105
106 def build_status_html(myself, build):
107     params = {
108         "host": build.host,
109         "tree": build.tree,
110         "compiler": build.compiler,
111         "checksum": build.log_checksum()
112         }
113     if build.revision:
114         params["revision"] = build.revision
115     return "<a href='%s?function=View+Build;%s'>%s</a>" % (myself, ";".join(["%s=%s" % k for k in params.iteritems()]), html_build_status(build.status()))
116
117
118 def build_status_vals(status):
119     """translate a status into a set of int representing status"""
120     status = util.strip_html(status)
121
122     status = status.replace("ok", "0")
123     status = status.replace("-", "0")
124     status = status.replace("?", "0.1")
125     status = status.replace("PANIC", "1")
126
127     return status.split("/")
128
129
130 def host_link(myself, host):
131     return "<a href='%s?function=View+Host;host=%s'>%s</a>" % (
132         myself, host, host)
133
134
135 def revision_link(myself, revision, tree):
136     """return a link to a particular revision"""
137
138     if revision is None:
139         return "unknown"
140
141     revision = revision.lstrip()
142     rev_short = revision
143     if len(revision) == 40:
144         rev_short = re.sub("(^.{7}).*", "\\1(git)", rev_short)
145
146     return "<a href='%s?function=diff;tree=%s;revision=%s' title='View Diff for %s'>%s</a>" % (myself, tree, revision, revision, rev_short)
147
148
149 def subunit_to_buildfarm_result(subunit_result):
150     if subunit_result == "success":
151         return "passed"
152     elif subunit_result == "error":
153         return "error"
154     elif subunit_result == "skip":
155         return "skipped"
156     elif subunit_result == "failure":
157         return "failed"
158     elif subunit_result == "xfail":
159         return "xfailed"
160     else:
161         return "unknown"
162
163 def format_subunit_reason(reason):
164     reason = re.sub("^\[\n+(.*?)\n+\]$", "\\1", reason)
165     return "<div class=\"reason\">%s</div>" % reason
166
167
168 class LogPrettyPrinter(object):
169
170     def __init__(self):
171         self.indice = 0
172
173     def _pretty_print(self, m):
174         output = m.group(1)
175         actionName = m.group(2)
176         status = m.group(3)
177         # handle pretty-printing of static-analysis tools
178         if actionName == 'cc_checker':
179              output = print_log_cc_checker(output)
180
181         self.indice += 1
182         return make_collapsible_html('action', actionName, output, self.indice, status)
183
184     # log is already CGI-escaped, so handle '>' in test name by handling &gt
185     def _format_stage(self, m):
186         self.indice += 1
187         return make_collapsible_html('test', m.group(1), m.group(2), self.indice, m.group(3))
188
189     def _format_skip_testsuite(self, m):
190         self.indice += 1
191         return make_collapsible_html('test', m.group(1), '', self.indice, 'skipped')
192
193     def _format_testsuite(self, m):
194         testName = m.group(1)
195         content = m.group(2)
196         status = subunit_to_buildfarm_result(m.group(3))
197         if m.group(4):
198             errorReason = format_subunit_reason(m.group(4))
199         else:
200             errorReason = ""
201         self.indice += 1
202         return make_collapsible_html('test', testName, content+errorReason, self.indice, status)
203
204     def _format_test(self, m):
205         self.indice += 1
206         return make_collapsible_html('test', m.group(1), m.group(2)+format_subunit_reason(m.group(4)), self.indice, subunit_to_buildfarm_result(m.group(3)))
207
208     def pretty_print(self, log):
209         # do some pretty printing for the actions
210         pattern = re.compile("(Running action\s+([\w\-]+)$(?:\s^.*$)*?\sACTION\ (PASSED|FAILED):\ ([\w\-]+)$)", re.M)
211         log = pattern.sub(self._pretty_print, log)
212
213         log = re.sub("""
214               --==--==--==--==--==--==--==--==--==--==--.*?
215               Running\ test\ ([\w\-=,_:\ /.&;]+).*?
216               --==--==--==--==--==--==--==--==--==--==--
217                   (.*?)
218               ==========================================.*?
219               TEST\ (FAILED|PASSED|SKIPPED):.*?
220               ==========================================\s+
221             """, self._format_stage, log)
222
223         log = re.sub("skip-testsuite: ([\w\-=,_:\ /.&; \(\)]+).*?",
224                 self._format_skip_testsuite, log)
225
226         pattern = re.compile("^testsuite: (.+)$\s((?:^.*$\s)*?)testsuite-(\w+): .*?(?:(\[$\s(?:^.*$\s)*?^\]$)|$)", re.M)
227         log = pattern.sub(self._format_testsuite, log)
228         log = re.sub("""
229               ^test: ([\w\-=,_:\ /.&; \(\)]+).*?
230               (.*?)
231               (success|xfail|failure|skip): [\w\-=,_:\ /.&; \(\)]+( \[.*?\])?.*?
232            """, self._format_test, log)
233
234         return "<pre>%s</pre>" % log
235
236
237 def print_log_pretty(log):
238     return LogPrettyPrinter().pretty_print(log)
239
240
241 def print_log_cc_checker(input):
242     # generate pretty-printed html for static analysis tools
243     output = ""
244
245     # for now, we only handle the IBM Checker's output style
246     if not re.search("^BEAM_VERSION", input):
247         return "here"
248         return input
249
250     content = ""
251     inEntry = False
252     title = None
253     status = None
254
255     for line in input.splitlines():
256         # for each line, check if the line is a new entry,
257         # otherwise, store the line under the current entry.
258
259         if line.startswith("-- "):
260             # got a new entry
261             if inEntry:
262                 output += make_collapsible_html('cc_checker', title, content, id, status)
263             else:
264                 output += content
265
266             # clear maintenance vars
267             (inEntry, content) = (True, "")
268
269             # parse the line
270             m = re.match("^-- ((ERROR|WARNING|MISTAKE).*?)\s+&gt;&gt;&gt;([a-zA-Z0-9]+_(\w+)_[a-zA-Z0-9]+)", line)
271
272             # then store the result
273             (title, status, id) = ("%s %s" % (m.group(1), m.group(4)), m.group(2), m.group(3))
274         elif line.startswith("CC_CHECKER STATUS"):
275             if inEntry:
276                 output += make_collapsible_html('cc_checker', title, content, id, status)
277
278             inEntry = False
279             content = ""
280
281         # not a new entry, so part of the current entry's output
282         content += "%s\n" % line
283
284     output += content
285
286     # This function does approximately the same as the following, following
287     # commented-out regular expression except that the regex doesn't quite
288     # handle IBM Checker's newlines quite right.
289     #   $output =~ s{
290     #                 --\ ((ERROR|WARNING|MISTAKE).*?)\s+
291     #                        &gt;&gt;&gt
292     #                 (.*?)
293     #                 \n{3,}
294     #               }{make_collapsible_html('cc_checker', "$1 $4", $5, $3, $2)}exgs
295     return output
296
297
298 def make_collapsible_html(type, title, output, id, status=""):
299     """generate html for a collapsible section
300
301     :param type: the logical type of it. e.g. "test" or "action"
302     :param title: the title to be displayed
303     """
304     if ((status == "" or "failed" == status.lower())):
305         icon = 'icon_hide_16.png'
306     else:
307         icon = 'icon_unhide_16.png'
308
309     # trim leading and trailing whitespace
310     output = output.strip()
311
312     # note that we may be inside a <pre>, so we don't put any extra whitespace
313     # in this html
314     ret = "<div class='%s unit %s' id='%s-%s'>" % (type, status, type, id)
315     ret += "<a href=\"javascript:handle('%s');\">" % id
316     ret += "<img id='img-%s' name='img-%s' alt='%s' src='%s' />" %(id, id, status, icon)
317     ret += "<div class='%s title'>%s</div></a>" % (type, title)
318     #ret += " "
319     ret += "<div class='%s status %s'>%s</div>" % (type, status, status)
320     ret += "<div class='%s output' id='output-%s'>" % (type, id)
321     if output and len(output):
322         ret += "<pre>%s</pre>>" % (output)
323     ret += "</div></div>"
324     return ret
325
326
327 def web_paths(t, paths):
328     """change the given source paths into links"""
329     if t.scm == "git":
330         ret = ""
331         for path in paths:
332             ret += " <a href=\"%s/?p=%s;a=history;f=%s%s;h=%s;hb=%s\">%s</a>" % (GITWEB_BASE, t.repo, t.subdir, path, t.branch, t.branch, path)
333         return ret
334     else:
335         raise Exception("Unknown scm %s" % t.scm)
336
337
338 def history_row_html(myself, entry, tree, changes):
339     """show one row of history table"""
340     msg = cgi.escape(entry.message)
341     t = time.asctime(time.gmtime(entry.date))
342     age = util.dhm_time(time.time()-entry.date)
343
344     t = t.replace(" ", "&nbsp;")
345
346     yield """
347 <div class=\"history_row\">
348     <div class=\"datetime\">
349         <span class=\"date\">%s</span><br />
350         <span class=\"age\">%s ago</span>""" % (t, age)
351     if entry.revision:
352         yield " - <span class=\"revision\">%s</span><br/>" % entry.revision
353         revision_url = "revision=%s" % entry.revision
354     else:
355         revision_url = "author=%s" % entry.author
356     yield """    </div>
357     <div class=\"diff\">
358         <span class=\"html\"><a href=\"%s?function=diff;tree=%s;date=%s;%s\">show diffs</a></span>
359     <br />
360         <span class=\"text\"><a href=\"%s?function=text_diff;tree=%s;date=%s;%s\">download diffs</a></span>
361         <br />
362         <div class=\"history_log_message\">
363             <pre>%s</pre>
364         </div>
365     </div>
366     <div class=\"author\">
367     <span class=\"label\">Author: </span>%s
368     </div>""" % (myself, tree.name, entry.date, revision_url,
369                  myself, tree.name, entry.date, revision_url,
370                  msg, entry.author)
371
372     (added, modified, removed) = changes
373
374     if modified:
375         yield "<div class=\"files\"><span class=\"label\">Modified: </span>"
376         yield web_paths(tree, modified)
377         yield "</div>\n"
378
379     if added:
380         yield "<div class=\"files\"><span class=\"label\">Added: </span>"
381         yield web_paths(tree, added)
382         yield "</div>\n"
383
384     if removed:
385         yield "<div class=\"files\"><span class=\"label\">Removed: </span>"
386         yield web_paths(tree, removed)
387         yield "</div>\n"
388
389     yield "</div>\n"
390
391
392 def history_row_text(entry, tree, changes):
393     """show one row of history table"""
394     msg = cgi.escape(entry.message)
395     t = time.asctime(time.gmtime(entry.date))
396     age = util.dhm_time(time.time()-entry.date)
397
398     yield "Author: %s\n" % entry.author
399     if entry.revision:
400         yield "Revision: %s\n" % entry.revision
401     (added, modified, removed) = changes
402     yield "Modified: %s\n" % modified
403     yield "Added: %s\n" % added
404     yield "Removed: %s\n" % removed
405     yield "\n\n%s\n\n\n" % msg
406
407
408 class BuildFarmPage(object):
409
410     def __init__(self, buildfarm):
411         self.buildfarm = buildfarm
412
413     def red_age(self, age):
414         """show an age as a string"""
415         if age > self.buildfarm.OLDAGE:
416             return "<span clsas='old'>%s</span>" % util.dhm_time(age)
417         return util.dhm_time(age)
418
419     def tree_link(self, myself, tree):
420         # return a link to a particular tree
421         branch = ""
422         if tree in self.buildfarm.trees:
423             branch = ":%s" % self.buildfarm.trees[tree].branch
424
425         return "<a href='%s?function=Recent+Builds;tree=%s' title='View recent builds for %s'>%s%s</a>" % (myself, tree, tree, tree, branch)
426
427     def render(self, output_type):
428         raise NotImplementedError(self.render)
429
430
431 class ViewBuildPage(BuildFarmPage):
432
433     def show_oldrevs(self, myself, tree, host, compiler):
434         """show the available old revisions, if any"""
435         old_rev_builds  = self.buildfarm.builds.get_old_revs(tree, host, compiler)
436
437         if not old_rev_builds:
438             return
439
440         yield "<h2>Older builds:</h2>\n"
441
442         yield "<table class='real'>\n"
443         yield "<thead><tr><th>Revision</th><th>Status</th></tr></thead>\n"
444         yield "<tbody>\n"
445
446         for build in old_rev_builds:
447             yield "<tr><td>%s</td><td>%s</td></tr>\n" % (
448                 revision_link(myself, build.revision, tree),
449                 build_status_html(myself, build))
450
451         yield "</tbody></table>\n"
452
453     def render(self, myself, tree, host, compiler, rev, checksum=None,
454             plain_logs=False):
455         """view one build in detail"""
456
457         uname = None
458         cflags = None
459         config = None
460         try:
461             build = self.buildfarm.get_build(tree, host, compiler, rev,
462                 checksum=checksum)
463         except data.NoSuchBuildError:
464             yield "No such build: %s on %s with %s, rev %r, checksum %r" % (
465                 tree, host, compiler, rev, checksum)
466             return
467         try:
468             (revision, revision_time) = build.revision_details()
469         except data.MissingRevisionInfo:
470             revision = None
471
472         try:
473             f = build.read_log()
474             try:
475                 log = f.read()
476             finally:
477                 f.close()
478         except data.LogFileMissing:
479             log = None
480         f = build.read_err()
481         try:
482             err = f.read()
483         finally:
484             f.close()
485
486         if log:
487             log = cgi.escape(log)
488
489             m = re.search("(.*)", log)
490             if m:
491                 uname = m.group(1)
492             m = re.search("CFLAGS=(.*)", log)
493             if m:
494                 cflags = m.group(1)
495             m = re.search("configure options: (.*)", log)
496             if m:
497                 config = m.group(1)
498
499         if err:
500             err = cgi.escape(err)
501         yield '<h2>Host information:</h2>'
502
503         host_web_file = "../web/%s.html" % host
504         if os.path.exists(host_web_file):
505             yield util.FileLoad(host_web_file)
506
507         yield "<table class='real'>\n"
508         yield "<tr><td>Host:</td><td><a href='%s?function=View+Host;host=%s;tree=%s;"\
509               "compiler=%s#'>%s</a> - %s</td></tr>\n" %\
510                 (myself, host, tree, compiler, host, self.buildfarm.hostdb[host].platform.encode("utf-8"))
511         if uname is not None:
512             yield "<tr><td>Uname:</td><td>%s</td></tr>\n" % uname
513         yield "<tr><td>Tree:</td><td>%s</td></tr>\n" % self.tree_link(myself, tree)
514         yield "<tr><td>Build Revision:</td><td>%s</td></tr>\n" % revision_link(myself, revision, tree)
515         yield "<tr><td>Build age:</td><td><div class='age'>%s</div></td></tr>\n" % self.red_age(build.age)
516         yield "<tr><td>Status:</td><td>%s</td></tr>\n" % build_status_html(myself, build)
517         yield "<tr><td>Compiler:</td><td>%s</td></tr>\n" % compiler
518         if cflags is not None:
519             yield "<tr><td>CFLAGS:</td><td>%s</td></tr>\n" % cflags
520         if config is not None:
521             yield "<tr><td>configure options:</td><td>%s</td></tr>\n" % config
522         yield "</table>\n"
523
524         yield "".join(self.show_oldrevs(myself, tree, host, compiler))
525
526         # check the head of the output for our magic string
527         rev_var = ""
528         if rev:
529             rev_var = ";revision=%s" % rev
530
531         yield "<div id='log'>"
532
533         if not plain_logs:
534             yield "<p>Switch to the <a href='%s?function=View+Build;host=%s;tree=%s"\
535                   ";compiler=%s%s;plain=true' title='Switch to bland, non-javascript,"\
536                   " unstyled view'>Plain View</a></p>" % (myself, host, tree, compiler, rev_var)
537
538             yield "<div id='actionList'>"
539             # These can be pretty wide -- perhaps we need to
540             # allow them to wrap in some way?
541             if err == "":
542                 yield "<h2>No error log available</h2>\n"
543             else:
544                 yield "<h2>Error log:</h2>"
545                 yield make_collapsible_html('action', "Error Output", "\n%s" % err, "stderr-0", "errorlog")
546
547             if log is None:
548                 yield "<h2>No build log available</h2>"
549             else:
550                 yield "<h2>Build log:</h2>\n"
551                 yield print_log_pretty(log)
552
553             yield "<p><small>Some of the above icons derived from the <a href='http://www.gnome.org'>Gnome Project</a>'s stock icons.</small></p>"
554             yield "</div>"
555         else:
556             yield "<p>Switch to the <a href='%s?function=View+Build;host=%s;tree=%s;"\
557                   "compiler=%s%s' title='Switch to colourful, javascript-enabled, styled"\
558                   " view'>Enhanced View</a></p>" % (myself, host, tree, compiler, rev_var)
559             if err == "":
560                 yield "<h2>No error log available</h2>"
561             else:
562                 yield '<h2>Error log:</h2>\n'
563                 yield '<div id="errorLog"><pre>%s</pre></div>' % err
564             if log == "":
565                 yield '<h2>No build log available</h2>'
566             else:
567                 yield '<h2>Build log:</h2>\n'
568                 yield '<div id="buildLog"><pre>%s</pre></div>' % log
569
570         yield '</div>'
571
572
573 class ViewRecentBuildsPage(BuildFarmPage):
574
575     def render(self, myself, tree, sort_by=None):
576         """Draw the "recent builds" view"""
577         all_builds = []
578
579         def build_platform(build):
580             try:
581                 host = self.buildfarm.hostdb[build.host]
582             except hostdb.NoSuchHost:
583                 return "UNKNOWN"
584             else:
585                 return host.platform.encode("utf-8")
586
587         cmp_funcs = {
588             "revision": lambda a, b: cmp(a.revision, b.revision),
589             "age": lambda a, b: cmp(a.age, b.age),
590             "host": lambda a, b: cmp(a.host, b.host),
591             "platform": lambda a, b: cmp(build_platform(a), build_platform(b)),
592             "compiler": lambda a, b: cmp(a.compiler, b.compiler),
593             "status": lambda a, b: cmp(a.status(), b.status()),
594             }
595
596         if sort_by is None:
597             sort_by = "age"
598
599         if sort_by not in cmp_funcs:
600             yield "not a valid sort mechanism: %r" % sort_by
601             return
602
603         all_builds = list(self.buildfarm.get_tree_builds(tree))
604
605         all_builds.sort(cmp_funcs[sort_by])
606
607         t = self.buildfarm.trees[tree]
608
609         sorturl = "%s?tree=%s;function=Recent+Builds" % (myself, tree)
610
611         yield "<div id='recent-builds' class='build-section'>"
612         yield "<h2>Recent builds of %s (%s branch %s)</h2>" % (tree, t.scm, t.branch)
613         yield "<table class='real'>"
614         yield "<thead>"
615         yield "<tr>"
616         yield "<th><a href='%s;sortby=age' title='Sort by build age'>Age</a></th>" % sorturl
617         yield "<th><a href='%s;sortby=revision' title='Sort by build revision'>Revision</a></th>" % sorturl
618         yield "<th>Tree</th>"
619         yield "<th><a href='%s;sortby=platform' title='Sort by platform'>Platform</a></th>" % sorturl
620         yield "<th><a href='%s;sortby=host' title='Sort by host'>Host</a></th>" % sorturl
621         yield "<th><a href='%s;sortby=compiler' title='Sort by compiler'>Compiler</a></th>" % sorturl
622         yield "<th><a href='%s;sortby=status' title='Sort by status'>Status</a></th>" % sorturl
623         yield "<tbody>"
624
625         for build in all_builds:
626             yield "<tr>"
627             yield "<td>%s</td>" % util.dhm_time(build.age)
628             yield "<td>%s</td>" % revision_link(myself, build.revision, build.tree)
629             yield "<td>%s</td>" % build.tree
630             yield "<td>%s</td>" % build_platform(build)
631             yield "<td>%s</td>" % host_link(myself, build.host)
632             yield "<td>%s</td>" % build.compiler
633             yield "<td>%s</td>" % build_status_html(myself, build)
634             yield "</tr>"
635         yield "</tbody></table>"
636         yield "</div>"
637
638
639 class ViewHostPage(BuildFarmPage):
640
641     def _render_build_list_header(self, host):
642         yield "<div class='host summary'>"
643         yield "<a id='host' name='host'/>"
644         yield "<h3>%s - %s</h3>" % (host.name, host.platform.encode("utf-8"))
645         yield "<table class='real'>"
646         yield "<thead><tr><th>Target</th><th>Build<br/>Revision</th><th>Build<br />Age</th><th>Status<br />config/build<br />install/test</th><th>Warnings</th></tr></thead>"
647         yield "<tbody>"
648
649     def _render_build_html(self, myself, build):
650         try:
651             (revision, revision_time) = build.revision_details()
652         except data.MissingRevisionInfo:
653             revision = None
654         warnings = build.err_count()
655         yield "<tr>"
656         yield "<td><span class='tree'>" + self.tree_link(myself, build.tree) +"</span>/" + build.compiler + "</td>"
657         yield "<td>" + revision_link(myself, revision, build.tree) + "</td>"
658         yield "<td><div class='age'>" + self.red_age(build.age) + "</div></td>"
659         yield "<td><div class='status'>%s</div></td>" % build_status_html(myself, build)
660         yield "<td>%s</td>" % warnings
661         yield "</tr>"
662
663     def render_html(self, myself, *requested_hosts):
664         yield "<div class='build-section' id='build-summary'>"
665         yield '<h2>Host summary:</h2>'
666         for hostname in requested_hosts:
667             try:
668                 host = self.buildfarm.hostdb[hostname]
669             except hostdb.NoSuchHost:
670                 deadhosts.append(hostname)
671                 continue
672             builds = list(self.buildfarm.get_host_builds(hostname))
673             if len(builds) > 0:
674                 yield "".join(self._render_build_list_header(host))
675                 for build in builds:
676                     yield "".join(self._render_build_html(myself, build))
677                 yield "</tbody></table>"
678                 yield "</div>"
679             else:
680                 deadhosts.append(hostname)
681
682         yield "</div>"
683         yield "".join(self.draw_dead_hosts(*deadhosts))
684
685     def render_text(self, myself, *requested_hosts):
686         """print the host's table of information"""
687         yield "Host summary:\n"
688
689         for host in requested_hosts:
690             # make sure we have some data from it
691             try:
692                 self.buildfarm.hostdb[host]
693             except hostdb.NoSuchHost:
694                 continue
695
696             builds = list(self.buildfarm.get_host_builds(host))
697             if len(builds) > 0:
698                 yield "%-12s %-10s %-10s %-10s %-10s\n" % (
699                         "Tree", "Compiler", "Build Age", "Status", "Warnings")
700                 for build in builds:
701                     yield "%-12s %-10s %-10s %-10s %-10s\n" % (
702                             build.tree, build.compiler,
703                             util.dhm_time(build.age),
704                             str(build.status()), build.err_count())
705                 yield "\n"
706
707     def draw_dead_hosts(self, *deadhosts):
708         """Draw the "dead hosts" table"""
709
710         # don't output anything if there are no dead hosts
711         if len(deadhosts) == 0:
712             return
713
714         yield "<div class='build-section' id='dead-hosts'>"
715         yield "<h2>Dead Hosts:</h2>"
716         yield "<table class='real'>"
717         yield "<thead><tr><th>Host</th><th>OS</th><th>Min Age</th></tr></thead>"
718         yield "<tbody>"
719
720         for host in deadhosts:
721             last_build = self.buildfarm.host_last_build(host)
722             age = time.time() - last_build
723             try:
724                 platform = self.buildfarm.hostdb[host].platform.encode("utf-8")
725             except hostdb.NoSuchHost:
726                 platform = "UNKNOWN"
727             yield "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %\
728                     (host, platform, util.dhm_time(age))
729
730         yield "</tbody></table>"
731         yield "</div>"
732
733
734 class ViewSummaryPage(BuildFarmPage):
735
736     def _get_counts(self):
737         broken_count = defaultdict(lambda: 0)
738         panic_count = defaultdict(lambda: 0)
739         host_count = defaultdict(lambda: 0)
740
741         # set up a variable to store the broken builds table's code, so we can
742         # output when we want
743         broken_table = ""
744
745         builds = self.buildfarm.get_last_builds()
746
747         for build in builds:
748             host_count[build.tree]+=1
749             status = build.status()
750
751             if status.failed:
752                 broken_count[build.tree]+=1
753                 if "panic" in status.other_failures:
754                     panic_count[build.tree]+=1
755         return (host_count, broken_count, panic_count)
756
757     def render_text(self, myself):
758
759         (host_count, broken_count, panic_count) = self._get_counts()
760         # for the text report, include the current time
761         t = time.gmtime()
762         yield "Build status as of %s\n\n" % t
763
764         yield "Build counts:\n"
765         yield "%-12s %-6s %-6s %-6s\n" % ("Tree", "Total", "Broken", "Panic")
766
767         for tree in sorted(self.buildfarm.trees.keys()):
768             yield "%-12s %-6s %-6s %-6s\n" % (tree, host_count[tree],
769                     broken_count[tree], panic_count[tree])
770
771         yield "\n"
772
773     def render_html(self, myself):
774         """view build summary"""
775
776         (host_count, broken_count, panic_count) = self._get_counts()
777
778         yield "<div id='build-counts' class='build-section'>"
779         yield "<h2>Build counts:</h2>"
780         yield "<table class='real'>"
781         yield "<thead><tr><th>Tree</th><th>Total</th><th>Broken</th><th>Panic</th><th>Test coverage</th></tr></thead>"
782         yield "<tbody>"
783
784         for tree in sorted(self.buildfarm.trees.keys()):
785             yield "<tr>"
786             yield "<td>%s</td>" % self.tree_link(myself, tree)
787             yield "<td>%s</td>" % host_count[tree]
788             yield "<td>%s</td>" % broken_count[tree]
789             if panic_count[tree]:
790                     yield "<td class='panic'>"
791             else:
792                     yield "<td>"
793             yield "%d</td>" % panic_count[tree]
794             try:
795                 lcov_status = self.buildfarm.lcov_status(tree)
796             except data.NoSuchBuildError:
797                 yield "<td></td>"
798             else:
799                 if lcov_status is not None:
800                     yield "<td><a href=\"/lcov/data/%s/%s\">%s %%</a></td>" % (
801                         self.buildfarm.LCOVHOST, tree, lcov_status)
802                 else:
803                     yield "<td></td>"
804             yield "</tr>"
805
806         yield "</tbody></table>"
807         yield "</div>"
808
809
810 class DiffPage(BuildFarmPage):
811
812     def render(self, myself, tree, revision):
813         t = self.buildfarm.trees[tree]
814         branch = t.get_branch()
815         (entry, diff) = branch.diff(revision)
816         # get information about the current diff
817         title = "GIT Diff in %s:%s for revision %s" % (
818             tree, t.branch, revision)
819         yield "<h2>%s</h2>" % title
820         changes = branch.changes_summary(revision)
821         yield "".join(history_row_html(myself, entry, t, changes))
822         diff = highlight(diff, DiffLexer(), HtmlFormatter())
823         yield "<pre>%s</pre>\n" % diff.encode("utf-8")
824
825
826 class RecentCheckinsPage(BuildFarmPage):
827
828     limit = 40
829
830     def render(self, myself, tree, author=None):
831         t = self.buildfarm.trees[tree]
832         interesting = list()
833         authors = {"ALL": "ALL"}
834         branch = t.get_branch()
835         re_author = re.compile("^(.*) <(.*)>$")
836         for entry in branch.log(limit=HISTORY_HORIZON):
837             m = re_author.match(entry.author)
838             authors[m.group(2)] = m.group(1)
839             if author in ("ALL", "", m.group(2)):
840                 interesting.append(entry)
841
842         yield "<h2>Recent checkins for %s (%s branch %s)</h2>\n" % (
843             tree, t.scm, t.branch)
844         yield "<form method='GET'>"
845         yield "Select Author: "
846         yield "<select name='author'>"
847         for email in sorted(authors):
848             yield "<option value='%s'>%s</option>" % (email, authors[email])
849         yield "</select>"
850         yield "<input type='submit' name='sub_function' value='Refresh'/>"
851         yield "<input type='hidden' name='tree' value='%s'/>" % tree
852         yield "<input type='hidden' name='function', value='Recent Checkins'/>"
853         yield "</form>"
854
855         for entry in interesting[:self.limit]:
856             changes = branch.changes_summary(entry.revision)
857             yield "".join(history_row_html(myself, entry, t, changes))
858         yield "\n"
859
860
861 class BuildFarmApp(object):
862
863     def __init__(self, buildfarm):
864         self.buildfarm = buildfarm
865
866     def main_menu(self):
867         """main page"""
868
869         yield "<form method='GET'>\n"
870         yield "<div id='build-menu'>\n"
871         yield "<select name='host'>\n"
872         for  host in self.buildfarm.hostdb.hosts():
873             yield "<option value='%s'>%s -- %s</option>\n" % (
874                 host.name, host.platform.encode("utf-8"), host.name)
875         yield "</select>\n"
876         yield "<select name='tree'>\n"
877         for tree, t in self.buildfarm.trees.iteritems():
878             yield "<option value='%s'>%s:%s</option>\n" % (tree, tree, t.branch)
879         yield "</select>\n"
880         yield "<select name='compiler'>\n"
881         for compiler in self.buildfarm.compilers:
882             yield "<option>%s</option>\n" % compiler
883         yield "</select>\n"
884         yield "<br/>\n"
885         yield "<input type='submit' name='function' value='View Build'/>\n"
886         yield "<input type='submit' name='function' value='View Host'/>\n"
887         yield "<input type='submit' name='function' value='Recent Checkins'/>\n"
888         yield "<input type='submit' name='function' value='Summary'/>\n"
889         yield "<input type='submit' name='function' value='Recent Builds'/>\n"
890         yield "</div>\n"
891         yield "</form>\n"
892
893     def __call__(self, environ, start_response):
894         form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
895         fn_name = get_param(form, 'function') or ''
896         myself = wsgiref.util.application_uri(environ)
897
898         if fn_name == 'text_diff':
899             start_response('200 OK', [('Content-type', 'application/x-diff')])
900             tree = get_param(form, 'tree')
901             t = self.buildfarm.trees[tree]
902             branch = t.get_branch()
903             revision = get_param(form, 'revision')
904             (entry, diff) = branch.diff(revision)
905             changes = branch.changes_summary(revision)
906             yield "".join(history_row_text(entry, tree, changes))
907             yield "%s\n" % diff
908         elif fn_name == 'Text_Summary':
909             start_response('200 OK', [('Content-type', 'text/plain')])
910             page = ViewSummaryPage(self.buildfarm)
911             yield "".join(page.render_text(myself))
912         else:
913             start_response('200 OK', [('Content-type', 'text/html')])
914
915             yield "<html>\n"
916             yield "  <head>\n"
917             yield "    <title>samba.org build farm</title>\n"
918             yield "    <script language='javascript' src='/build_farm.js'></script>\n"
919             yield "    <meta name='keywords' contents='Samba SMB CIFS Build Farm'/>\n"
920             yield "    <meta name='description' contents='Home of the Samba Build Farm, the automated testing facility.'/>\n"
921             yield "    <meta name='robots' contents='noindex'/>"
922             yield "    <link rel='stylesheet' href='/build_farm.css' type='text/css' media='all'/>"
923             yield "    <link rel='stylesheet' href='http://master.samba.org/samba/style/common.css' type='text/css' media='all'/>"
924             yield "    <link rel='shortcut icon' href='http://www.samba.org/samba/images/favicon.ico'/>"
925             yield "  </head>"
926             yield "<body>"
927
928             yield util.FileLoad(os.path.join(webdir, "header2.html"))
929             yield "".join(self.main_menu())
930             yield util.FileLoad(os.path.join(webdir, "header3.html"))
931             if fn_name == "View_Build":
932                 plain_logs = (get_param(form, "plain") is not None and get_param(form, "plain").lower() in ("yes", "1", "on", "true", "y"))
933                 tree = get_param(form, "tree")
934                 host = get_param(form, "host")
935                 compiler = get_param(form, "compiler")
936                 revision = get_param(form, "revision")
937                 checksum = get_param(form, "checksum")
938                 page = ViewBuildPage(self.buildfarm)
939                 yield "".join(page.render(myself, tree, host, compiler, revision, checksum, plain_logs))
940             elif fn_name == "View_Host":
941                 page = ViewHostPage(self.buildfarm)
942                 yield "".join(page.render_html(myself, get_param(form, 'host')))
943             elif fn_name == "Recent_Builds":
944                 page = ViewRecentBuildsPage(self.buildfarm)
945                 yield "".join(page.render(myself, get_param(form, "tree"), get_param(form, "sortby") or "revision"))
946             elif fn_name == "Recent_Checkins":
947                 # validate the tree
948                 tree =  get_param(form, "tree")
949                 author = get_param(form, 'author')
950                 page = RecentCheckinsPage(self.buildfarm)
951                 yield "".join(page.render(myself, tree, author))
952             elif fn_name == "diff":
953                 tree =  get_param(form, "tree")
954                 revision = get_param(form, 'revision')
955                 page = DiffPage(self.buildfarm)
956                 yield "".join(page.render(myself, tree, revision))
957             elif os.getenv("PATH_INFO") not in (None, "", "/"):
958                 paths = os.getenv("PATH_INFO").split('/')
959                 if paths[1] == "recent":
960                     page = ViewRecentBuildsPage(self.buildfarm)
961                     yield "".join(page.render(myself, paths[2], get_param(form, 'sortby') or 'age'))
962                 elif paths[1] == "host":
963                     page = ViewHostPage(self.buildfarm)
964                     yield "".join(page.render_html(myself, paths[2]))
965             else:
966                 page = ViewSummaryPage(self.buildfarm)
967                 yield "".join(page.render_html(myself))
968             yield util.FileLoad(os.path.join(webdir, "footer.html"))
969             yield "</body>"
970             yield "</html>"
971
972
973 if __name__ == '__main__':
974     import optparse
975     parser = optparse.OptionParser("[options]")
976     parser.add_option("--port", help="Port to listen on [localhost:8000]", default="localhost:8000", type=str)
977     opts, args = parser.parse_args()
978     from buildfarm.sqldb import StormCachingBuildFarm
979     buildfarm = StormCachingBuildFarm()
980     buildApp = BuildFarmApp(buildfarm)
981     from wsgiref.simple_server import make_server
982     import mimetypes
983     mimetypes.init()
984
985     def standaloneApp(environ, start_response):
986         if environ['PATH_INFO']:
987             m = re.match("^/([a-zA-Z0-9_-]+)(\.[a-zA-Z0-9_-]+)?", environ['PATH_INFO'])
988             if m:
989                 static_file = os.path.join(webdir, m.group(1)+m.group(2))
990                 if os.path.exists(static_file):
991                     type = mimetypes.types_map[m.group(2)]
992                     start_response('200 OK', [('Content-type', type)])
993                     data = open(static_file, 'rb').read()
994                     yield data
995                     return
996         yield "".join(buildApp(environ, start_response))
997     try:
998         (address, port) = opts.port.rsplit(":", 1)
999     except ValueError:
1000         address = "localhost"
1001         port = opts.port
1002     httpd = make_server(address, int(port), standaloneApp)
1003     print "Serving on %s:%d..." % (address, int(port))
1004     httpd.serve_forever()