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