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