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