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