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