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