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