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