]> git.decadent.org.uk Git - dak.git/blob - dak/cruft_report.py
let's use pythonesque imports, shall we?
[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
31 import apt_pkg
32 from daklib import database
33 from daklib import utils
34
35 ################################################################################
36
37 Cnf = None
38 projectB = None
39 suite = "unstable" # Default
40 suite_id = None
41 no_longer_in_suite = {}; # Really should be static to add_nbs, but I'm lazy
42
43 source_binaries = {}
44 source_versions = {}
45
46 ################################################################################
47
48 def usage(exit_code=0):
49     print """Usage: dak cruft-report
50 Check for obsolete or duplicated packages.
51
52   -h, --help                show this help and exit.
53   -m, --mode=MODE           chose the MODE to run in (full or daily).
54   -s, --suite=SUITE         check suite SUITE."""
55     sys.exit(exit_code)
56
57 ################################################################################
58
59 def add_nbs(nbs_d, source, version, package):
60     # Ensure the package is still in the suite (someone may have already removed it)
61     if no_longer_in_suite.has_key(package):
62         return
63     else:
64         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))
65         if not q.getresult():
66             no_longer_in_suite[package] = ""
67             return
68
69     nbs_d.setdefault(source, {})
70     nbs_d[source].setdefault(version, {})
71     nbs_d[source][version][package] = ""
72
73 ################################################################################
74
75 # Check for packages built on architectures they shouldn't be.
76 def do_anais(architecture, binaries_list, source):
77     if architecture == "any" or architecture == "all":
78         return ""
79
80     anais_output = ""
81     architectures = {}
82     for arch in architecture.split():
83         architectures[arch.strip()] = ""
84     for binary in binaries_list:
85         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))
86         ql = q.getresult()
87         versions = []
88         for i in ql:
89             arch = i[0]
90             version = i[1]
91             if architectures.has_key(arch):
92                 versions.append(version)
93         versions.sort(apt_pkg.VersionCompare)
94         if versions:
95             latest_version = versions.pop()
96         else:
97             latest_version = None
98         # Check for 'invalid' architectures
99         versions_d = {}
100         for i in ql:
101             arch = i[0]
102             version = i[1]
103             if not architectures.has_key(arch):
104                 versions_d.setdefault(version, [])
105                 versions_d[version].append(arch)
106
107         if versions_d != {}:
108             anais_output += "\n (*) %s_%s [%s]: %s\n" % (binary, latest_version, source, architecture)
109             versions = versions_d.keys()
110             versions.sort(apt_pkg.VersionCompare)
111             for version in versions:
112                 arches = versions_d[version]
113                 arches.sort()
114                 anais_output += "    o %s: %s\n" % (version, ", ".join(arches))
115     return anais_output
116
117 ################################################################################
118
119 def do_nviu():
120     experimental_id = database.get_suite_id("experimental")
121     if experimental_id == -1:
122         return
123     # Check for packages in experimental obsoleted by versions in unstable
124     q = projectB.query("""
125 SELECT s.source, s.version AS experimental, s2.version AS unstable
126   FROM src_associations sa, source s, source s2, src_associations sa2
127   WHERE sa.suite = %s AND sa2.suite = %d AND sa.source = s.id
128    AND sa2.source = s2.id AND s.source = s2.source
129    AND versioncmp(s.version, s2.version) < 0""" % (experimental_id,
130                                                    database.get_suite_id("unstable")))
131     ql = q.getresult()
132     if ql:
133         nviu_to_remove = []
134         print "Newer version in unstable"
135         print "-------------------------"
136         print
137         for i in ql:
138             (source, experimental_version, unstable_version) = i
139             print " o %s (%s, %s)" % (source, experimental_version, unstable_version)
140             nviu_to_remove.append(source)
141         print
142         print "Suggested command:"
143         print " dak rm -m \"[auto-cruft] NVIU\" -s experimental %s" % (" ".join(nviu_to_remove))
144         print
145
146 ################################################################################
147
148 def do_nbs(real_nbs):
149     output = "Not Built from Source\n"
150     output += "---------------------\n\n"
151
152     nbs_to_remove = []
153     nbs_keys = real_nbs.keys()
154     nbs_keys.sort()
155     for source in nbs_keys:
156         output += " * %s_%s builds: %s\n" % (source,
157                                        source_versions.get(source, "??"),
158                                        source_binaries.get(source, "(source does not exist)"))
159         output += "      but no longer builds:\n"
160         versions = real_nbs[source].keys()
161         versions.sort(apt_pkg.VersionCompare)
162         for version in versions:
163             packages = real_nbs[source][version].keys()
164             packages.sort()
165             for pkg in packages:
166                 nbs_to_remove.append(pkg)
167             output += "        o %s: %s\n" % (version, ", ".join(packages))
168
169         output += "\n"
170
171     if nbs_to_remove:
172         print output
173
174         print "Suggested command:"
175         print " dak rm -m \"[auto-cruft] NBS\" -s %s -b %s" % (suite, " ".join(nbs_to_remove))
176         print
177
178 ################################################################################
179
180 def do_dubious_nbs(dubious_nbs):
181     print "Dubious NBS"
182     print "-----------"
183     print
184
185     dubious_nbs_keys = dubious_nbs.keys()
186     dubious_nbs_keys.sort()
187     for source in dubious_nbs_keys:
188         print " * %s_%s builds: %s" % (source,
189                                        source_versions.get(source, "??"),
190                                        source_binaries.get(source, "(source does not exist)"))
191         print "      won't admit to building:"
192         versions = dubious_nbs[source].keys()
193         versions.sort(apt_pkg.VersionCompare)
194         for version in versions:
195             packages = dubious_nbs[source][version].keys()
196             packages.sort()
197             print "        o %s: %s" % (version, ", ".join(packages))
198
199         print
200
201 ################################################################################
202
203 def do_obsolete_source(duplicate_bins, bin2source):
204     obsolete = {}
205     for key in duplicate_bins.keys():
206         (source_a, source_b) = key.split('_')
207         for source in [ source_a, source_b ]:
208             if not obsolete.has_key(source):
209                 if not source_binaries.has_key(source):
210                     # Source has already been removed
211                     continue
212                 else:
213                     obsolete[source] = [ i.strip() for i in source_binaries[source].split(',') ]
214             for binary in duplicate_bins[key]:
215                 if bin2source.has_key(binary) and bin2source[binary]["source"] == source:
216                     continue
217                 if binary in obsolete[source]:
218                     obsolete[source].remove(binary)
219
220     to_remove = []
221     output = "Obsolete source package\n"
222     output += "-----------------------\n\n"
223     obsolete_keys = obsolete.keys()
224     obsolete_keys.sort()
225     for source in obsolete_keys:
226         if not obsolete[source]:
227             to_remove.append(source)
228             output += " * %s (%s)\n" % (source, source_versions[source])
229             for binary in [ i.strip() for i in source_binaries[source].split(',') ]:
230                 if bin2source.has_key(binary):
231                     output += "    o %s (%s) is built by %s.\n" \
232                           % (binary, bin2source[binary]["version"],
233                              bin2source[binary]["source"])
234                 else:
235                     output += "    o %s is not built.\n" % binary
236             output += "\n"
237
238     if to_remove:
239         print output
240
241         print "Suggested command:"
242         print " dak rm -S -p -m \"[auto-cruft] obsolete source package\" %s" % (" ".join(to_remove))
243         print
244
245 def get_suite_binaries():
246     # Initalize a large hash table of all binary packages
247     binaries = {}
248     before = time.time()
249
250     sys.stderr.write("[Getting a list of binary packages in %s..." % (suite))
251     q = projectB.query("SELECT distinct b.package FROM binaries b, bin_associations ba WHERE ba.suite = %s AND ba.bin = b.id" % (suite_id))
252     ql = q.getresult()
253     sys.stderr.write("done. (%d seconds)]\n" % (int(time.time()-before)))
254     for i in ql:
255         binaries[i[0]] = ""
256
257     return binaries
258
259 ################################################################################
260
261 def main ():
262     global Cnf, projectB, suite, suite_id, source_binaries, source_versions
263
264     Cnf = utils.get_conf()
265
266     Arguments = [('h',"help","Cruft-Report::Options::Help"),
267                  ('m',"mode","Cruft-Report::Options::Mode", "HasArg"),
268                  ('s',"suite","Cruft-Report::Options::Suite","HasArg")]
269     for i in [ "help" ]:
270         if not Cnf.has_key("Cruft-Report::Options::%s" % (i)):
271             Cnf["Cruft-Report::Options::%s" % (i)] = ""
272     Cnf["Cruft-Report::Options::Suite"] = Cnf["Dinstall::DefaultSuite"]
273
274     if not Cnf.has_key("Cruft-Report::Options::Mode"):
275         Cnf["Cruft-Report::Options::Mode"] = "daily"
276
277     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
278
279     Options = Cnf.SubTree("Cruft-Report::Options")
280     if Options["Help"]:
281         usage()
282
283     # Set up checks based on mode
284     if Options["Mode"] == "daily":
285         checks = [ "nbs", "nviu", "obsolete source" ]
286     elif Options["Mode"] == "full":
287         checks = [ "nbs", "nviu", "obsolete source", "dubious nbs", "bnb", "bms", "anais" ]
288     else:
289         utils.warn("%s is not a recognised mode - only 'full' or 'daily' are understood." % (Options["Mode"]))
290         usage(1)
291
292     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
293     database.init(Cnf, projectB)
294
295     bin_pkgs = {}
296     src_pkgs = {}
297     bin2source = {}
298     bins_in_suite = {}
299     nbs = {}
300     source_versions = {}
301
302     anais_output = ""
303     duplicate_bins = {}
304
305     suite = Options["Suite"]
306     suite_id = database.get_suite_id(suite)
307
308     bin_not_built = {}
309
310     if "bnb" in checks:
311         bins_in_suite = get_suite_binaries()
312
313     # Checks based on the Sources files
314     components = Cnf.ValueList("Suite::%s::Components" % (suite))
315     for component in components:
316         filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
317         # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
318         temp_filename = utils.temp_filename()
319         (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
320         if (result != 0):
321             sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
322             sys.exit(result)
323         sources = utils.open_file(temp_filename)
324         Sources = apt_pkg.ParseTagFile(sources)
325         while Sources.Step():
326             source = Sources.Section.Find('Package')
327             source_version = Sources.Section.Find('Version')
328             architecture = Sources.Section.Find('Architecture')
329             binaries = Sources.Section.Find('Binary')
330             binaries_list = [ i.strip() for i in  binaries.split(',') ]
331
332             if "bnb" in checks:
333                 # Check for binaries not built on any architecture.
334                 for binary in binaries_list:
335                     if not bins_in_suite.has_key(binary):
336                         bin_not_built.setdefault(source, {})
337                         bin_not_built[source][binary] = ""
338
339             if "anais" in checks:
340                 anais_output += do_anais(architecture, binaries_list, source)
341
342             # Check for duplicated packages and build indices for checking "no source" later
343             source_index = component + '/' + source
344             if src_pkgs.has_key(source):
345                 print " %s is a duplicated source package (%s and %s)" % (source, source_index, src_pkgs[source])
346             src_pkgs[source] = source_index
347             for binary in binaries_list:
348                 if bin_pkgs.has_key(binary):
349                     key_list = [ source, bin_pkgs[binary] ]
350                     key_list.sort()
351                     key = '_'.join(key_list)
352                     duplicate_bins.setdefault(key, [])
353                     duplicate_bins[key].append(binary)
354                 bin_pkgs[binary] = source
355             source_binaries[source] = binaries
356             source_versions[source] = source_version
357
358         sources.close()
359         os.unlink(temp_filename)
360
361     # Checks based on the Packages files
362     check_components = components[:]
363     if suite != "experimental":
364         check_components.append('main/debian-installer');
365     for component in check_components:
366         architectures = filter(utils.real_arch, Cnf.ValueList("Suite::%s::Architectures" % (suite)))
367         for architecture in architectures:
368             filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (Cnf["Dir::Root"], suite, component, architecture)
369             # apt_pkg.ParseTagFile needs a real file handle
370             temp_filename = utils.temp_filename()
371             (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
372             if (result != 0):
373                 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
374                 sys.exit(result)
375             packages = utils.open_file(temp_filename)
376             Packages = apt_pkg.ParseTagFile(packages)
377             while Packages.Step():
378                 package = Packages.Section.Find('Package')
379                 source = Packages.Section.Find('Source', "")
380                 version = Packages.Section.Find('Version')
381                 if source == "":
382                     source = package
383                 if bin2source.has_key(package) and \
384                        apt_pkg.VersionCompare(version, bin2source[package]["version"]) > 0:
385                     bin2source[package]["version"] = version
386                     bin2source[package]["source"] = source
387                 else:
388                     bin2source[package] = {}
389                     bin2source[package]["version"] = version
390                     bin2source[package]["source"] = source
391                 if source.find("(") != -1:
392                     m = utils.re_extract_src_version.match(source)
393                     source = m.group(1)
394                     version = m.group(2)
395                 if not bin_pkgs.has_key(package):
396                     nbs.setdefault(source,{})
397                     nbs[source].setdefault(package, {})
398                     nbs[source][package][version] = ""
399                 else:
400                     previous_source = bin_pkgs[package]
401                     if previous_source != source:
402                         key_list = [ source, previous_source ]
403                         key_list.sort()
404                         key = '_'.join(key_list)
405                         duplicate_bins.setdefault(key, [])
406                         if package not in duplicate_bins[key]:
407                             duplicate_bins[key].append(package)
408             packages.close()
409             os.unlink(temp_filename)
410
411     if "obsolete source" in checks:
412         do_obsolete_source(duplicate_bins, bin2source)
413
414     # Distinguish dubious (version numbers match) and 'real' NBS (they don't)
415     dubious_nbs = {}
416     real_nbs = {}
417     for source in nbs.keys():
418         for package in nbs[source].keys():
419             versions = nbs[source][package].keys()
420             versions.sort(apt_pkg.VersionCompare)
421             latest_version = versions.pop()
422             source_version = source_versions.get(source,"0")
423             if apt_pkg.VersionCompare(latest_version, source_version) == 0:
424                 add_nbs(dubious_nbs, source, latest_version, package)
425             else:
426                 add_nbs(real_nbs, source, latest_version, package)
427
428     if "nviu" in checks:
429         do_nviu()
430
431     if "nbs" in checks:
432         do_nbs(real_nbs)
433
434     ###
435
436     if Options["Mode"] == "full":
437         print "="*75
438         print
439
440     if "bnb" in checks:
441         print "Unbuilt binary packages"
442         print "-----------------------"
443         print
444         keys = bin_not_built.keys()
445         keys.sort()
446         for source in keys:
447             binaries = bin_not_built[source].keys()
448             binaries.sort()
449             print " o %s: %s" % (source, ", ".join(binaries))
450         print
451
452     if "bms" in checks:
453         print "Built from multiple source packages"
454         print "-----------------------------------"
455         print
456         keys = duplicate_bins.keys()
457         keys.sort()
458         for key in keys:
459             (source_a, source_b) = key.split("_")
460             print " o %s & %s => %s" % (source_a, source_b, ", ".join(duplicate_bins[key]))
461         print
462
463     if "anais" in checks:
464         print "Architecture Not Allowed In Source"
465         print "----------------------------------"
466         print anais_output
467         print
468
469     if "dubious nbs" in checks:
470         do_dubious_nbs(dubious_nbs)
471
472
473 ################################################################################
474
475 if __name__ == '__main__':
476     main()