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