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