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