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