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