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