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