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