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