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