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