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