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