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