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