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