]> git.decadent.org.uk Git - dak.git/blob - dak/queue_report.py
Merge branch 'master' into merge
[dak.git] / dak / queue_report.py
1 #!/usr/bin/env python
2
3 """ Produces a report on NEW and BYHAND packages """
4 # Copyright (C) 2001, 2002, 2003, 2005, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # <o-o> XP runs GCC, XFREE86, SSH etc etc,.,, I feel almost like linux....
23 # <o-o> I am very confident that I can replicate any Linux application on XP
24 # <willy> o-o: *boggle*
25 # <o-o> building from source.
26 # <o-o> Viiru: I already run GIMP under XP
27 # <willy> o-o: why do you capitalise the names of all pieces of software?
28 # <o-o> willy: because I want the EMPHASIZE them....
29 # <o-o> grr s/the/to/
30 # <willy> o-o: it makes you look like ZIPPY the PINHEAD
31 # <o-o> willy: no idea what you are talking about.
32 # <willy> o-o: do some research
33 # <o-o> willy: for what reason?
34
35 ################################################################################
36
37 from copy import copy
38 import glob, os, stat, sys, time
39 import apt_pkg
40
41 from daklib import utils
42 from daklib.queue import Upload
43 from daklib.dbconn import DBConn, has_new_comment, DBChange, DBSource, get_uid_from_fingerprint
44 from daklib.textutils import fix_maintainer
45 from daklib.dak_exceptions import *
46 import debianbts
47
48 Cnf = None
49 direction = []
50 row_number = 0
51
52 ################################################################################
53
54 def usage(exit_code=0):
55     print """Usage: dak queue-report
56 Prints a report of packages in queue directories (usually new and byhand).
57
58   -h, --help                show this help and exit.
59   -8, --822                 writes 822 formated output to the location set in dak.conf
60   -n, --new                 produce html-output
61   -s, --sort=key            sort output according to key, see below.
62   -a, --age=key             if using sort by age, how should time be treated?
63                             If not given a default of hours will be used.
64   -d, --directories=key     A comma seperated list of queues to be scanned
65
66      Sorting Keys: ao=age,   oldest first.   an=age,   newest first.
67                    na=name,  ascending       nd=name,  descending
68                    nf=notes, first           nl=notes, last
69
70      Age Keys: m=minutes, h=hours, d=days, w=weeks, o=months, y=years
71
72 """
73     sys.exit(exit_code)
74
75 ################################################################################
76
77 def plural(x):
78     if x > 1:
79         return "s"
80     else:
81         return ""
82
83 ################################################################################
84
85 def time_pp(x):
86     if x < 60:
87         unit="second"
88     elif x < 3600:
89         x /= 60
90         unit="minute"
91     elif x < 86400:
92         x /= 3600
93         unit="hour"
94     elif x < 604800:
95         x /= 86400
96         unit="day"
97     elif x < 2419200:
98         x /= 604800
99         unit="week"
100     elif x < 29030400:
101         x /= 2419200
102         unit="month"
103     else:
104         x /= 29030400
105         unit="year"
106     x = int(x)
107     return "%s %s%s" % (x, unit, plural(x))
108
109 ################################################################################
110
111 def sg_compare (a, b):
112     a = a[1]
113     b = b[1]
114     """Sort by have note, time of oldest upload."""
115     # Sort by have note
116     a_note_state = a["note_state"]
117     b_note_state = b["note_state"]
118     if a_note_state < b_note_state:
119         return -1
120     elif a_note_state > b_note_state:
121         return 1
122
123     # Sort by time of oldest upload
124     return cmp(a["oldest"], b["oldest"])
125
126 ############################################################
127
128 def sortfunc(a,b):
129     for sorting in direction:
130         (sortkey, way, time) = sorting
131         ret = 0
132         if time == "m":
133             x=int(a[sortkey]/60)
134             y=int(b[sortkey]/60)
135         elif time == "h":
136             x=int(a[sortkey]/3600)
137             y=int(b[sortkey]/3600)
138         elif time == "d":
139             x=int(a[sortkey]/86400)
140             y=int(b[sortkey]/86400)
141         elif time == "w":
142             x=int(a[sortkey]/604800)
143             y=int(b[sortkey]/604800)
144         elif time == "o":
145             x=int(a[sortkey]/2419200)
146             y=int(b[sortkey]/2419200)
147         elif time == "y":
148             x=int(a[sortkey]/29030400)
149             y=int(b[sortkey]/29030400)
150         else:
151             x=a[sortkey]
152             y=b[sortkey]
153         if x < y:
154             ret = -1
155         elif x > y:
156             ret = 1
157         if ret != 0:
158             if way < 0:
159                 ret = ret*-1
160             return ret
161     return 0
162
163 ############################################################
164
165 def header():
166     print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
167 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
168 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
169   <head>
170     <meta http-equiv="content-type" content="text/xhtml+xml; charset=utf-8" />
171     <link type="text/css" rel="stylesheet" href="style.css" />
172     <link rel="shortcut icon" href="http://www.debian.org/favicon.ico" />
173     <title>
174       Debian NEW and BYHAND Packages
175     </title>
176     <script type="text/javascript">
177     function togglePkg() {
178         var children = document.getElementsByTagName("*");
179         for (var i = 0; i < children.length; i++) {
180             if(!children[i].hasAttribute("class"))
181                 continue;
182             c = children[i].getAttribute("class").split(" ");
183             for(var j = 0; j < c.length; j++) {
184                 if(c[j] == "binNEW") {
185                     if (children[i].style.display == '')
186                         children[i].style.display = 'none';
187                     else children[i].style.display = '';
188                 }
189             }
190         }
191     }
192     </script>
193   </head>
194   <body id="NEW">
195     <div id="logo">
196       <a href="http://www.debian.org/">
197         <img src="http://www.debian.org/logos/openlogo-nd-50.png"
198         alt="debian logo" /></a>
199       <a href="http://www.debian.org/">
200         <img src="http://www.debian.org/Pics/debian.png"
201         alt="Debian Project" /></a>
202     </div>
203     <div id="titleblock">
204
205       <img src="http://www.debian.org/Pics/red-upperleft.png"
206       id="red-upperleft" alt="corner image"/>
207       <img src="http://www.debian.org/Pics/red-lowerleft.png"
208       id="red-lowerleft" alt="corner image"/>
209       <img src="http://www.debian.org/Pics/red-upperright.png"
210       id="red-upperright" alt="corner image"/>
211       <img src="http://www.debian.org/Pics/red-lowerright.png"
212       id="red-lowerright" alt="corner image"/>
213       <span class="title">
214         Debian NEW and BYHAND Packages
215       </span>
216     </div>
217     """
218
219 def footer():
220     print "<p class=\"timestamp\">Timestamp: %s (UTC)</p>" % (time.strftime("%d.%m.%Y / %H:%M:%S", time.gmtime()))
221
222     print """
223     <div class="footer">
224     <p>Hint: Age is the youngest upload of the package, if there is more than
225     one version.<br />
226     You may want to look at <a href="http://ftp-master.debian.org/REJECT-FAQ.html">the REJECT-FAQ</a>
227       for possible reasons why one of the above packages may get rejected.</p>
228       <p>
229       <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10"
230         alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
231       <a href="http://jigsaw.w3.org/css-validator/">
232         <img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss"
233         alt="Valid CSS!" />
234       </a>
235       </p>
236     </div> </body> </html>
237     """
238
239 def table_header(type, source_count, total_count):
240     print "<h1 class='binNEW'>Summary for: %s</h1>" % (type)
241     print "<h1 class='binNEW' style='display: none'>Summary for: binary-%s only</h1>" % (type)
242     print """
243     <table class="NEW">
244       <p class="togglepkg" onclick="togglePkg()">Click to toggle all/binary-NEW packages</p>
245       <caption class="binNEW">
246     """
247     print "Package count in <strong>%s</strong>: <em>%s</em>&nbsp;|&nbsp; Total Package count: <em>%s</em>" % (type, source_count, total_count)
248     print """
249       </caption>
250       <thead>
251         <tr>
252           <th>Package</th>
253           <th>Version</th>
254           <th>Arch</th>
255           <th>Distribution</th>
256           <th>Age</th>
257           <th>Upload info</th>
258           <th>Closes</th>
259         </tr>
260       </thead>
261       <tbody>
262     """
263
264 def table_footer(type):
265     print "</tbody></table>"
266
267
268 def find_bug_severities(bugnrs):
269     """Take a list of bug numbers and
270     return a dictionary with bug number - severity pairs."""
271     statuses = None
272     try: statuses = debianbts.get_status(bugnrs)
273     except Exception:
274         return None
275     severities = {}
276     for bug_status in statuses:
277         severities[bug_status.bug_num] = bug_status.severity
278     return severities
279
280 def rcbug_close_check(closes):
281     """Take a list of bug numbers and determine if at least one of them
282     is release critical."""
283     severity_list = find_bug_severities(closes)
284     if severity_list:
285         severities = severity_list.values()
286         return ('critical' in severities) or \
287                ('serious' in severities) or \
288                ('grave' in severities)
289     return False
290
291 def table_row(source, version, arch, last_mod, maint, distribution, closes, fingerprint, sponsor, changedby, fixes_rcbug):
292
293     global row_number
294
295     trclass = "sid"
296     session = DBConn().session()
297     for dist in distribution:
298         if dist == "experimental":
299             trclass = "exp"
300
301     if fixes_rcbug:
302         trclass = "rcfix"
303
304     if not len(session.query(DBSource).filter_by(source = source).all()):
305         trclass += " binNEW"
306     session.commit()
307
308     if row_number % 2 != 0:
309         print "<tr class=\"%s even\">" % (trclass)
310     else:
311         print "<tr class=\"%s odd\">" % (trclass)
312
313     print "<td class=\"package\">%s</td>" % (source)
314     print "<td class=\"version\">"
315     for vers in version.split():
316         print "<a href=\"new/%s_%s.html\">%s</a><br/>" % (source, utils.html_escape(vers), utils.html_escape(vers))
317     print "</td>"
318     print "<td class=\"arch\">%s</td>" % (arch)
319     print "<td class=\"distribution\">"
320     for dist in distribution:
321         print "%s<br/>" % (dist)
322     print "</td>"
323     print "<td class=\"age\">%s</td>" % (last_mod)
324     (name, mail) = maint.split(":", 1)
325
326     print "<td class=\"upload-data\">"
327     print "<span class=\"maintainer\">Maintainer: <a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></span><br/>" % (utils.html_escape(mail), utils.html_escape(name))
328     (name, mail) = changedby.split(":", 1)
329     print "<span class=\"changed-by\">Changed-By: <a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></span><br/>" % (utils.html_escape(mail), utils.html_escape(name))
330
331     if sponsor:
332         try:
333             (login, domain) = sponsor.split("@", 1)
334             print "<span class=\"sponsor\">Sponsor: <a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></span>@debian.org<br/>" % (utils.html_escape(login), utils.html_escape(login))
335         except Exception, e:
336             pass
337
338     print "<span class=\"signature\">Fingerprint: %s</span>" % (fingerprint)
339     print "</td>"
340
341     print "<td class=\"closes\">"
342     for close in closes:
343         print "<a href=\"http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s\">#%s</a><br/>" % (utils.html_escape(close), utils.html_escape(close))
344     print "</td></tr>"
345     row_number+=1
346
347 ############################################################
348
349 def process_changes_files(changes_files, type, log):
350     session = DBConn().session()
351     msg = ""
352     cache = {}
353     # Read in all the .changes files
354     for filename in changes_files:
355         try:
356             u = Upload()
357             u.load_changes(filename)
358             cache[filename] = copy(u.pkg.changes)
359             cache[filename]["filename"] = filename
360         except Exception, e:
361             print "WARNING: Exception %s" % e
362             continue
363     # Divide the .changes into per-source groups
364     per_source = {}
365     for filename in cache.keys():
366         source = cache[filename]["source"]
367         if not per_source.has_key(source):
368             per_source[source] = {}
369             per_source[source]["list"] = []
370         per_source[source]["list"].append(cache[filename])
371     # Determine oldest time and have note status for each source group
372     for source in per_source.keys():
373         source_list = per_source[source]["list"]
374         first = source_list[0]
375         oldest = os.stat(first["filename"])[stat.ST_MTIME]
376         have_note = 0
377         for d in per_source[source]["list"]:
378             mtime = os.stat(d["filename"])[stat.ST_MTIME]
379             if Cnf.has_key("Queue-Report::Options::New"):
380                 if mtime > oldest:
381                     oldest = mtime
382             else:
383                 if mtime < oldest:
384                     oldest = mtime
385             have_note += has_new_comment(d["source"], d["version"])
386         per_source[source]["oldest"] = oldest
387         if not have_note:
388             per_source[source]["note_state"] = 0; # none
389         elif have_note < len(source_list):
390             per_source[source]["note_state"] = 1; # some
391         else:
392             per_source[source]["note_state"] = 2; # all
393     per_source_items = per_source.items()
394     per_source_items.sort(sg_compare)
395
396     entries = []
397     max_source_len = 0
398     max_version_len = 0
399     max_arch_len = 0
400     for i in per_source_items:
401         maintainer = {}
402         maint=""
403         distribution=""
404         closes=""
405         fingerprint=""
406         changeby = {}
407         changedby=""
408         sponsor=""
409         filename=i[1]["list"][0]["filename"]
410         last_modified = time.time()-i[1]["oldest"]
411         source = i[1]["list"][0]["source"]
412         if len(source) > max_source_len:
413             max_source_len = len(source)
414         binary_list = i[1]["list"][0]["binary"].keys()
415         binary = ', '.join(binary_list)
416         arches = {}
417         versions = {}
418         for j in i[1]["list"]:
419             changesbase = os.path.basename(j["filename"])
420             try:
421                 dbc = session.query(DBChange).filter_by(changesname=changesbase).one()
422             except Exception, e:
423                 print "Can't find changes file in NEW for %s (%s)" % (changesbase, e)
424                 dbc = None
425
426             if Cnf.has_key("Queue-Report::Options::New") or Cnf.has_key("Queue-Report::Options::822"):
427                 try:
428                     (maintainer["maintainer822"], maintainer["maintainer2047"],
429                     maintainer["maintainername"], maintainer["maintaineremail"]) = \
430                     fix_maintainer (j["maintainer"])
431                 except ParseMaintError, msg:
432                     print "Problems while parsing maintainer address\n"
433                     maintainer["maintainername"] = "Unknown"
434                     maintainer["maintaineremail"] = "Unknown"
435                 maint="%s:%s" % (maintainer["maintainername"], maintainer["maintaineremail"])
436                 # ...likewise for the Changed-By: field if it exists.
437                 try:
438                     (changeby["changedby822"], changeby["changedby2047"],
439                      changeby["changedbyname"], changeby["changedbyemail"]) = \
440                      fix_maintainer (j["changed-by"])
441                 except ParseMaintError, msg:
442                     (changeby["changedby822"], changeby["changedby2047"],
443                      changeby["changedbyname"], changeby["changedbyemail"]) = \
444                      ("", "", "", "")
445                 changedby="%s:%s" % (changeby["changedbyname"], changeby["changedbyemail"])
446
447                 distribution=j["distribution"].keys()
448                 closes=j["closes"].keys()
449                 if dbc:
450                     fingerprint = dbc.fingerprint
451                     sponsor_name = get_uid_from_fingerprint(fingerprint).name
452                     sponsor_email = get_uid_from_fingerprint(fingerprint).uid + "@debian.org"
453                     if sponsor_name != maintainer["maintainername"] and sponsor_name != changeby["changedbyname"] and \
454                     sponsor_email != maintainer["maintaineremail"] and sponsor_name != changeby["changedbyemail"]:
455                         sponsor = sponsor_email
456
457             for arch in j["architecture"].keys():
458                 arches[arch] = ""
459             version = j["version"]
460             versions[version] = ""
461         arches_list = arches.keys()
462         arches_list.sort(utils.arch_compare_sw)
463         arch_list = " ".join(arches_list)
464         version_list = " ".join(versions.keys())
465         if len(version_list) > max_version_len:
466             max_version_len = len(version_list)
467         if len(arch_list) > max_arch_len:
468             max_arch_len = len(arch_list)
469         if i[1]["note_state"]:
470             note = " | [N]"
471         else:
472             note = ""
473         fixes_rcbug = rcbug_close_check(closes)
474         entries.append([source, binary, version_list, arch_list, note, last_modified, maint, distribution, closes, fingerprint, sponsor, changedby, filename, fixes_rcbug])
475
476     # direction entry consists of "Which field, which direction, time-consider" where
477     # time-consider says how we should treat last_modified. Thats all.
478
479     # Look for the options for sort and then do the sort.
480     age = "h"
481     if Cnf.has_key("Queue-Report::Options::Age"):
482         age =  Cnf["Queue-Report::Options::Age"]
483     if Cnf.has_key("Queue-Report::Options::New"):
484     # If we produce html we always have oldest first.
485         direction.append([5,-1,"ao"])
486     else:
487         if Cnf.has_key("Queue-Report::Options::Sort"):
488             for i in Cnf["Queue-Report::Options::Sort"].split(","):
489                 if i == "ao":
490                     # Age, oldest first.
491                     direction.append([5,-1,age])
492                 elif i == "an":
493                     # Age, newest first.
494                     direction.append([5,1,age])
495                 elif i == "na":
496                     # Name, Ascending.
497                     direction.append([0,1,0])
498                 elif i == "nd":
499                     # Name, Descending.
500                     direction.append([0,-1,0])
501                 elif i == "nl":
502                     # Notes last.
503                     direction.append([4,1,0])
504                 elif i == "nf":
505                     # Notes first.
506                     direction.append([4,-1,0])
507     entries.sort(lambda x, y: sortfunc(x, y))
508     # Yes, in theory you can add several sort options at the commandline with. But my mind is to small
509     # at the moment to come up with a real good sorting function that considers all the sidesteps you
510     # have with it. (If you combine options it will simply take the last one at the moment).
511     # Will be enhanced in the future.
512
513     if Cnf.has_key("Queue-Report::Options::822"):
514         # print stuff out in 822 format
515         for entry in entries:
516             (source, binary, version_list, arch_list, note, last_modified, maint, distribution, closes, fingerprint, sponsor, changedby, changes_file, fixes_rcbug) = entry
517
518             # We'll always have Source, Version, Arch, Mantainer, and Dist
519             # For the rest, check to see if we have them, then print them out
520             log.write("Source: " + source + "\n")
521             log.write("Binary: " + binary + "\n")
522             log.write("Version: " + version_list + "\n")
523             log.write("Architectures: ")
524             log.write( (", ".join(arch_list.split(" "))) + "\n")
525             log.write("Age: " + time_pp(last_modified) + "\n")
526             log.write("Last-Modified: " + str(int(time.time()) - int(last_modified)) + "\n")
527             log.write("Queue: " + type + "\n")
528
529             (name, mail) = maint.split(":", 1)
530             log.write("Maintainer: " + name + " <"+mail+">" + "\n")
531             if changedby:
532                (name, mail) = changedby.split(":", 1)
533                log.write("Changed-By: " + name + " <"+mail+">" + "\n")
534             if sponsor:
535                log.write("Sponsored-By: " + sponsor + "\n")
536             log.write("Distribution:")
537             for dist in distribution:
538                log.write(" " + dist)
539             log.write("\n")
540             log.write("Fingerprint: " + fingerprint + "\n")
541             if closes:
542                 bug_string = ""
543                 for bugs in closes:
544                     bug_string += "#"+bugs+", "
545                 log.write("Closes: " + bug_string[:-2] + "\n")
546             log.write("Changes-File: " + os.path.basename(changes_file) + "\n")
547             log.write("\n")
548
549     if Cnf.has_key("Queue-Report::Options::New"):
550         direction.append([5,1,"ao"])
551         entries.sort(lambda x, y: sortfunc(x, y))
552     # Output for a html file. First table header. then table_footer.
553     # Any line between them is then a <tr> printed from subroutine table_row.
554         if len(entries) > 0:
555             total_count = len(changes_files)
556             source_count = len(per_source_items)
557             table_header(type.upper(), source_count, total_count)
558             for entry in entries:
559                 (source, binary, version_list, arch_list, note, last_modified, maint, distribution, closes, fingerprint, sponsor, changedby, undef, fixes_rcbug) = entry
560                 table_row(source, version_list, arch_list, time_pp(last_modified), maint, distribution, closes, fingerprint, sponsor, changedby, entries, fixes_rcbug)
561             table_footer(type.upper())
562     elif not Cnf.has_key("Queue-Report::Options::822"):
563     # The "normal" output without any formatting.
564         format="%%-%ds | %%-%ds | %%-%ds%%s | %%s old\n" % (max_source_len, max_version_len, max_arch_len)
565
566         msg = ""
567         for entry in entries:
568             (source, binary, version_list, arch_list, note, last_modified, undef, undef, undef, undef, undef, undef, undef, fixes_rcbug) = entry
569             msg += format % (source, version_list, arch_list, note, time_pp(last_modified))
570
571         if msg:
572             total_count = len(changes_files)
573             source_count = len(per_source_items)
574             print type.upper()
575             print "-"*len(type)
576             print
577             print msg
578             print "%s %s source package%s / %s %s package%s in total." % (source_count, type, plural(source_count), total_count, type, plural(total_count))
579             print
580
581
582 ################################################################################
583
584 def main():
585     global Cnf
586
587     Cnf = utils.get_conf()
588     Arguments = [('h',"help","Queue-Report::Options::Help"),
589                  ('n',"new","Queue-Report::Options::New"),
590                  ('8','822',"Queue-Report::Options::822"),
591                  ('s',"sort","Queue-Report::Options::Sort", "HasArg"),
592                  ('a',"age","Queue-Report::Options::Age", "HasArg"),
593                  ('d',"directories","Queue-Report::Options::Directories", "HasArg")]
594     for i in [ "help" ]:
595         if not Cnf.has_key("Queue-Report::Options::%s" % (i)):
596             Cnf["Queue-Report::Options::%s" % (i)] = ""
597
598     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
599
600     Options = Cnf.SubTree("Queue-Report::Options")
601     if Options["Help"]:
602         usage()
603
604     if Cnf.has_key("Queue-Report::Options::New"):
605         header()
606
607     # Initialize db so we can get the NEW comments
608     dbconn = DBConn()
609
610     directories = [ ]
611
612     if Cnf.has_key("Queue-Report::Options::Directories"):
613         for i in Cnf["Queue-Report::Options::Directories"].split(","):
614             directories.append(i)
615     elif Cnf.has_key("Queue-Report::Directories"):
616         directories = Cnf.ValueList("Queue-Report::Directories")
617     else:
618         directories = [ "byhand", "new" ]
619
620     f = None
621     if Cnf.has_key("Queue-Report::Options::822"):
622         # Open the report file
623         f = open(Cnf["Queue-Report::ReportLocations::822Location"], "w")
624
625     for directory in directories:
626         changes_files = glob.glob("%s/*.changes" % (Cnf["Dir::Queue::%s" % (directory)]))
627         process_changes_files(changes_files, directory, f)
628
629     if Cnf.has_key("Queue-Report::Options::822"):
630         f.close()
631
632     if Cnf.has_key("Queue-Report::Options::New"):
633         footer()
634
635 ################################################################################
636
637 if __name__ == '__main__':
638     main()