]> git.decadent.org.uk Git - dak.git/blob - dak/cruft_report.py
convert cruft_report to new DB API
[dak.git] / dak / cruft_report.py
1 #!/usr/bin/env python
2
3 """ Check for obsolete binary packages """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 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 # ``If you're claiming that's a "problem" that needs to be "fixed",
23 #   you might as well write some letters to God about how unfair entropy
24 #   is while you're at it.'' -- 20020802143104.GA5628@azure.humbug.org.au
25
26 ## TODO:  fix NBS looping for version, implement Dubious NBS, fix up output of
27 ##        duplicate source package stuff, improve experimental ?, add overrides,
28 ##        avoid ANAIS for duplicated packages
29
30 ################################################################################
31
32 import commands, os, sys, time, re
33 import apt_pkg
34
35 from daklib.config import Config
36 from daklib.dbconn import *
37 from daklib import utils
38 from daklib.regexes import re_extract_src_version
39
40 ################################################################################
41
42 no_longer_in_suite = {}; # Really should be static to add_nbs, but I'm lazy
43
44 source_binaries = {}
45 source_versions = {}
46
47 ################################################################################
48
49 def usage(exit_code=0):
50     print """Usage: dak cruft-report
51 Check for obsolete or duplicated packages.
52
53   -h, --help                show this help and exit.
54   -m, --mode=MODE           chose the MODE to run in (full or daily).
55   -s, --suite=SUITE         check suite SUITE.
56   -w, --wanna-build-dump    where to find the copies of http://buildd.debian.org/stats/*.txt"""
57     sys.exit(exit_code)
58
59 ################################################################################
60
61 def add_nbs(nbs_d, source, version, package, suite_id, session):
62     # Ensure the package is still in the suite (someone may have already removed it)
63     if no_longer_in_suite.has_key(package):
64         return
65     else:
66         q = session.execute("""SELECT b.id FROM binaries b, bin_associations ba
67                                 WHERE ba.bin = b.id AND ba.suite = :suite_id
68                                   AND b.package = suite_id LIMIT 1""" % (suite_id, package))
69         if not q.fetchall():
70             no_longer_in_suite[package] = ""
71             return
72
73     nbs_d.setdefault(source, {})
74     nbs_d[source].setdefault(version, {})
75     nbs_d[source][version][package] = ""
76
77 ################################################################################
78
79 # Check for packages built on architectures they shouldn't be.
80 def do_anais(architecture, binaries_list, source, session):
81     if architecture == "any" or architecture == "all":
82         return ""
83
84     anais_output = ""
85     architectures = {}
86     for arch in architecture.split():
87         architectures[arch.strip()] = ""
88     for binary in binaries_list:
89         q = session.execute("""SELECT a.arch_string, b.version
90                                 FROM binaries b, bin_associations ba, architecture a
91                                WHERE ba.suite = :suiteid AND ba.bin = b.id
92                                  AND b.architecture = a.id AND b.package = :package""",
93                              {'suiteid': suite_id, 'package': binary})
94         versions = []
95         for i in q.fetchall():
96             arch = i[0]
97             version = i[1]
98             if architectures.has_key(arch):
99                 versions.append(version)
100         versions.sort(apt_pkg.VersionCompare)
101         if versions:
102             latest_version = versions.pop()
103         else:
104             latest_version = None
105         # Check for 'invalid' architectures
106         versions_d = {}
107         for i in ql:
108             arch = i[0]
109             version = i[1]
110             if not architectures.has_key(arch):
111                 versions_d.setdefault(version, [])
112                 versions_d[version].append(arch)
113
114         if versions_d != {}:
115             anais_output += "\n (*) %s_%s [%s]: %s\n" % (binary, latest_version, source, architecture)
116             versions = versions_d.keys()
117             versions.sort(apt_pkg.VersionCompare)
118             for version in versions:
119                 arches = versions_d[version]
120                 arches.sort()
121                 anais_output += "    o %s: %s\n" % (version, ", ".join(arches))
122     return anais_output
123
124
125 ################################################################################
126
127 # Check for out-of-date binaries on architectures that do not want to build that
128 # package any more, and have them listed as Not-For-Us
129 def do_nfu(nfu_packages):
130     output = ""
131     
132     a2p = {}
133
134     for architecture in nfu_packages:
135         a2p[architecture] = []
136         for (package,bver,sver) in nfu_packages[architecture]:
137             output += "  * [%s] does not want %s (binary %s, source %s)\n" % (architecture, package, bver, sver)
138             a2p[architecture].append(package)
139
140
141     if output:
142         print "Obsolete by Not-For-Us"
143         print "----------------------"
144         print
145         print output
146
147         print "Suggested commands:"
148         for architecture in a2p:
149             if a2p[architecture]:
150                 print (" dak rm -m \"[auto-cruft] NFU\" -s %s -a %s -b %s" % 
151                     (suite, architecture, " ".join(a2p[architecture])))
152         print
153
154 def parse_nfu(architecture):
155     cnf = Config()
156     # utils/hpodder_1.1.5.0: Not-For-Us [optional:out-of-date]
157     r = re.compile("^\w+/([^_]+)_.*: Not-For-Us")
158
159     ret = set()
160     
161     filename = "%s/%s-all.txt" % (cnf["Cruft-Report::Options::Wanna-Build-Dump"], architecture)
162
163     # Not all architectures may have a wanna-build dump, so we want to ignore missin
164     # files
165     if os.path.exists(filename):
166         f = utils.open_file(filename)
167         for line in f:
168             if line[0] == ' ':
169                 continue
170
171             m = r.match(line)
172             if m:
173                 ret.add(m.group(1))
174
175         f.close()
176     else:
177         utils.warn("No wanna-build dump file for architecture %s" % architecture)
178     return ret
179
180 ################################################################################
181
182 def do_newer_version(lowersuite_name, highersuite_name, code, session):
183     lowersuite = get_suite(lowersuite_name, session)
184     if not lowersuite:
185         return
186
187     highersuite = get_suite(highersuite_name, session)
188     if not highersuite:
189         return
190
191     # Check for packages in $highersuite obsoleted by versions in $lowersuite
192     q = session.execute("""
193 SELECT s.source, s.version AS lower, s2.version AS higher
194   FROM src_associations sa, source s, source s2, src_associations sa2
195   WHERE sa.suite = :highersuite_id AND sa2.suite = :lowersuite_id AND sa.source = s.id
196    AND sa2.source = s2.id AND s.source = s2.source
197    AND s.version < s2.version""" % {'lowersuite_id': lowersuite.suite_id,
198                                     'highersuite_id': highersuite.suite_id})
199     ql = q.fetchall()
200     if ql:
201         nv_to_remove = []
202         print "Newer version in %s" % lowersuite.suite_name
203         print "-----------------" + "-" * len(lowersuite.suite_name)
204         print
205         for i in ql:
206             (source, higher_version, lower_version) = i
207             print " o %s (%s, %s)" % (source, higher_version, lower_version)
208             nv_to_remove.append(source)
209         print
210         print "Suggested command:"
211         print " dak rm -m \"[auto-cruft] %s\" -s %s %s" % (code, highersuite.suite_name,
212                                                            " ".join(nv_to_remove))
213         print
214
215 ################################################################################
216
217 def do_nbs(real_nbs):
218     output = "Not Built from Source\n"
219     output += "---------------------\n\n"
220
221     cmd_output = ""
222     nbs_keys = real_nbs.keys()
223     nbs_keys.sort()
224     for source in nbs_keys:
225         output += " * %s_%s builds: %s\n" % (source,
226                                        source_versions.get(source, "??"),
227                                        source_binaries.get(source, "(source does not exist)"))
228         output += "      but no longer builds:\n"
229         versions = real_nbs[source].keys()
230         versions.sort(apt_pkg.VersionCompare)
231         all_packages = []
232         for version in versions:
233             packages = real_nbs[source][version].keys()
234             packages.sort()
235             all_packages.extend(packages)
236             output += "        o %s: %s\n" % (version, ", ".join(packages))
237         if all_packages:
238             all_packages.sort()
239             cmd_output += " dak rm -m \"[auto-cruft] NBS (was built by %s)\" -s %s -b %s\n\n" % (source, suite, " ".join(all_packages))
240
241         output += "\n"
242
243     if len(cmd_output):
244         print output
245         print "Suggested commands:\n"
246         print cmd_output
247
248 ################################################################################
249
250 def do_dubious_nbs(dubious_nbs):
251     print "Dubious NBS"
252     print "-----------"
253     print
254
255     dubious_nbs_keys = dubious_nbs.keys()
256     dubious_nbs_keys.sort()
257     for source in dubious_nbs_keys:
258         print " * %s_%s builds: %s" % (source,
259                                        source_versions.get(source, "??"),
260                                        source_binaries.get(source, "(source does not exist)"))
261         print "      won't admit to building:"
262         versions = dubious_nbs[source].keys()
263         versions.sort(apt_pkg.VersionCompare)
264         for version in versions:
265             packages = dubious_nbs[source][version].keys()
266             packages.sort()
267             print "        o %s: %s" % (version, ", ".join(packages))
268
269         print
270
271 ################################################################################
272
273 def do_obsolete_source(duplicate_bins, bin2source):
274     obsolete = {}
275     for key in duplicate_bins.keys():
276         (source_a, source_b) = key.split('_')
277         for source in [ source_a, source_b ]:
278             if not obsolete.has_key(source):
279                 if not source_binaries.has_key(source):
280                     # Source has already been removed
281                     continue
282                 else:
283                     obsolete[source] = [ i.strip() for i in source_binaries[source].split(',') ]
284             for binary in duplicate_bins[key]:
285                 if bin2source.has_key(binary) and bin2source[binary]["source"] == source:
286                     continue
287                 if binary in obsolete[source]:
288                     obsolete[source].remove(binary)
289
290     to_remove = []
291     output = "Obsolete source package\n"
292     output += "-----------------------\n\n"
293     obsolete_keys = obsolete.keys()
294     obsolete_keys.sort()
295     for source in obsolete_keys:
296         if not obsolete[source]:
297             to_remove.append(source)
298             output += " * %s (%s)\n" % (source, source_versions[source])
299             for binary in [ i.strip() for i in source_binaries[source].split(',') ]:
300                 if bin2source.has_key(binary):
301                     output += "    o %s (%s) is built by %s.\n" \
302                           % (binary, bin2source[binary]["version"],
303                              bin2source[binary]["source"])
304                 else:
305                     output += "    o %s is not built.\n" % binary
306             output += "\n"
307
308     if to_remove:
309         print output
310
311         print "Suggested command:"
312         print " dak rm -S -p -m \"[auto-cruft] obsolete source package\" %s" % (" ".join(to_remove))
313         print
314
315 def get_suite_binaries(suite, session):
316     # Initalize a large hash table of all binary packages
317     binaries = {}
318
319     print "Getting a list of binary packages in %s..." % suite.suite_name
320     q = session.execute("""SELECT distinct b.package
321                              FROM binaries b, bin_associations ba
322                             WHERE ba.suite = :suiteid AND ba.bin = b.id""",
323                            {'suiteid': suite.suite_id})
324     for i in q.fetchall():
325         binaries[i[0]] = ""
326
327     return binaries
328
329 ################################################################################
330
331 def main ():
332     global suite, suite_id, source_binaries, source_versions
333
334     cnf = Config()
335
336     Arguments = [('h',"help","Cruft-Report::Options::Help"),
337                  ('m',"mode","Cruft-Report::Options::Mode", "HasArg"),
338                  ('s',"suite","Cruft-Report::Options::Suite","HasArg"),
339                  ('w',"wanna-build-dump","Cruft-Report::Options::Wanna-Build-Dump","HasArg")]
340     for i in [ "help" ]:
341         if not cnf.has_key("Cruft-Report::Options::%s" % (i)):
342             cnf["Cruft-Report::Options::%s" % (i)] = ""
343     cnf["Cruft-Report::Options::Suite"] = cnf["Dinstall::DefaultSuite"]
344
345     if not cnf.has_key("Cruft-Report::Options::Mode"):
346         cnf["Cruft-Report::Options::Mode"] = "daily"
347
348     if not cnf.has_key("Cruft-Report::Options::Wanna-Build-Dump"):
349         cnf["Cruft-Report::Options::Wanna-Build-Dump"] = "/srv/ftp.debian.org/scripts/nfu"
350
351     apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
352
353     Options = cnf.SubTree("Cruft-Report::Options")
354     if Options["Help"]:
355         usage()
356
357     # Set up checks based on mode
358     if Options["Mode"] == "daily":
359         checks = [ "nbs", "nviu", "obsolete source" ]
360     elif Options["Mode"] == "full":
361         checks = [ "nbs", "nviu", "obsolete source", "nfu", "dubious nbs", "bnb", "bms", "anais" ]
362     else:
363         utils.warn("%s is not a recognised mode - only 'full' or 'daily' are understood." % (Options["Mode"]))
364         usage(1)
365
366     session = DBConn().session()
367
368     bin_pkgs = {}
369     src_pkgs = {}
370     bin2source = {}
371     bins_in_suite = {}
372     nbs = {}
373     source_versions = {}
374
375     anais_output = ""
376     duplicate_bins = {}
377
378     nfu_packages = {}
379
380     suite = get_suite(Options["Suite"].lower(), session)
381     suite_id = suite.suite_id
382
383     bin_not_built = {}
384
385     if "bnb" in checks:
386         bins_in_suite = get_suite_binaries(suite)
387
388     # Checks based on the Sources files
389     components = cnf.ValueList("Suite::%s::Components" % (suite))
390     for component in components:
391         filename = "%s/dists/%s/%s/source/Sources.gz" % (cnf["Dir::Root"], suite.suite_name, component)
392         # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
393         (fd, temp_filename) = utils.temp_filename()
394         (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
395         if (result != 0):
396             sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
397             sys.exit(result)
398         sources = utils.open_file(temp_filename)
399         Sources = apt_pkg.ParseTagFile(sources)
400         while Sources.Step():
401             source = Sources.Section.Find('Package')
402             source_version = Sources.Section.Find('Version')
403             architecture = Sources.Section.Find('Architecture')
404             binaries = Sources.Section.Find('Binary')
405             binaries_list = [ i.strip() for i in  binaries.split(',') ]
406
407             if "bnb" in checks:
408                 # Check for binaries not built on any architecture.
409                 for binary in binaries_list:
410                     if not bins_in_suite.has_key(binary):
411                         bin_not_built.setdefault(source, {})
412                         bin_not_built[source][binary] = ""
413
414             if "anais" in checks:
415                 anais_output += do_anais(architecture, binaries_list, source, session)
416
417             # Check for duplicated packages and build indices for checking "no source" later
418             source_index = component + '/' + source
419             if src_pkgs.has_key(source):
420                 print " %s is a duplicated source package (%s and %s)" % (source, source_index, src_pkgs[source])
421             src_pkgs[source] = source_index
422             for binary in binaries_list:
423                 if bin_pkgs.has_key(binary):
424                     key_list = [ source, bin_pkgs[binary] ]
425                     key_list.sort()
426                     key = '_'.join(key_list)
427                     duplicate_bins.setdefault(key, [])
428                     duplicate_bins[key].append(binary)
429                 bin_pkgs[binary] = source
430             source_binaries[source] = binaries
431             source_versions[source] = source_version
432
433         sources.close()
434         os.unlink(temp_filename)
435
436     # Checks based on the Packages files
437     check_components = components[:]
438     if suite.suite_name != "experimental":
439         check_components.append('main/debian-installer');
440
441     for component in check_components:
442         architectures = [ a.arch_string for a in get_suite_architectures(suite.suite_name,
443                                                                          skipsrc=True, skipall=True,
444                                                                          session=session) ]
445         for architecture in architectures:
446             if component == 'main/debian-installer' and re.match("kfreebsd", architecture):
447                 continue
448             filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (cnf["Dir::Root"], suite.suite_name, component, architecture)
449             # apt_pkg.ParseTagFile needs a real file handle
450             (fd, temp_filename) = utils.temp_filename()
451             (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
452             if (result != 0):
453                 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
454                 sys.exit(result)
455
456             if "nfu" in checks:
457                 nfu_packages.setdefault(architecture,[])
458                 nfu_entries = parse_nfu(architecture)
459
460             packages = utils.open_file(temp_filename)
461             Packages = apt_pkg.ParseTagFile(packages)
462             while Packages.Step():
463                 package = Packages.Section.Find('Package')
464                 source = Packages.Section.Find('Source', "")
465                 version = Packages.Section.Find('Version')
466                 if source == "":
467                     source = package
468                 if bin2source.has_key(package) and \
469                        apt_pkg.VersionCompare(version, bin2source[package]["version"]) > 0:
470                     bin2source[package]["version"] = version
471                     bin2source[package]["source"] = source
472                 else:
473                     bin2source[package] = {}
474                     bin2source[package]["version"] = version
475                     bin2source[package]["source"] = source
476                 if source.find("(") != -1:
477                     m = re_extract_src_version.match(source)
478                     source = m.group(1)
479                     version = m.group(2)
480                 if not bin_pkgs.has_key(package):
481                     nbs.setdefault(source,{})
482                     nbs[source].setdefault(package, {})
483                     nbs[source][package][version] = ""
484                 else:
485                     previous_source = bin_pkgs[package]
486                     if previous_source != source:
487                         key_list = [ source, previous_source ]
488                         key_list.sort()
489                         key = '_'.join(key_list)
490                         duplicate_bins.setdefault(key, [])
491                         if package not in duplicate_bins[key]:
492                             duplicate_bins[key].append(package)
493                     if "nfu" in checks:
494                         if package in nfu_entries and \
495                                version != source_versions[source]: # only suggest to remove out-of-date packages
496                             nfu_packages[architecture].append((package,version,source_versions[source]))
497                     
498             packages.close()
499             os.unlink(temp_filename)
500
501     if "obsolete source" in checks:
502         do_obsolete_source(duplicate_bins, bin2source)
503
504     # Distinguish dubious (version numbers match) and 'real' NBS (they don't)
505     dubious_nbs = {}
506     real_nbs = {}
507     for source in nbs.keys():
508         for package in nbs[source].keys():
509             versions = nbs[source][package].keys()
510             versions.sort(apt_pkg.VersionCompare)
511             latest_version = versions.pop()
512             source_version = source_versions.get(source,"0")
513             if apt_pkg.VersionCompare(latest_version, source_version) == 0:
514                 add_nbs(dubious_nbs, source, latest_version, package, suite_id, session)
515             else:
516                 add_nbs(real_nbs, source, latest_version, package, suite_id, session)
517
518     if "nviu" in checks:
519         do_newer_version('unstable', 'experimental', 'NVIU', session)
520
521     if "nbs" in checks:
522         do_nbs(real_nbs)
523
524     ###
525
526     if Options["Mode"] == "full":
527         print "="*75
528         print
529
530     if "nfu" in checks:
531         do_nfu(nfu_packages)
532
533     if "bnb" in checks:
534         print "Unbuilt binary packages"
535         print "-----------------------"
536         print
537         keys = bin_not_built.keys()
538         keys.sort()
539         for source in keys:
540             binaries = bin_not_built[source].keys()
541             binaries.sort()
542             print " o %s: %s" % (source, ", ".join(binaries))
543         print
544
545     if "bms" in checks:
546         print "Built from multiple source packages"
547         print "-----------------------------------"
548         print
549         keys = duplicate_bins.keys()
550         keys.sort()
551         for key in keys:
552             (source_a, source_b) = key.split("_")
553             print " o %s & %s => %s" % (source_a, source_b, ", ".join(duplicate_bins[key]))
554         print
555
556     if "anais" in checks:
557         print "Architecture Not Allowed In Source"
558         print "----------------------------------"
559         print anais_output
560         print
561
562     if "dubious nbs" in checks:
563         do_dubious_nbs(dubious_nbs)
564
565
566 ################################################################################
567
568 if __name__ == '__main__':
569     main()