]> git.decadent.org.uk Git - dak.git/blob - dak/auto_decruft.py
e16850d61457e527e9d9846cb4923bbf8a97468d
[dak.git] / dak / auto_decruft.py
1 #!/usr/bin/env python
2
3 """
4 Check for obsolete binary packages
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2000-2006 James Troup <james@nocrew.org>
8 @copyright: 2009      Torsten Werner <twerner@debian.org>
9 @copyright: 2015      Niels Thykier <niels@thykier.net>
10 @license: GNU General Public License version 2 or later
11 """
12
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
17
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
22
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
27 ################################################################################
28
29 # | priviledged positions? What privilege? The honour of working harder
30 # | than most people for absolutely no recognition?
31 #
32 # Manoj Srivastava <srivasta@debian.org> in <87lln8aqfm.fsf@glaurung.internal.golden-gryphon.com>
33
34 ################################################################################
35
36 import sys
37 import apt_pkg
38 from itertools import chain, product
39 from collections import defaultdict
40
41 from daklib.config import Config
42 from daklib.dbconn import *
43 from daklib import utils
44 from daklib.cruft import *
45 from daklib.rm import remove, ReverseDependencyChecker
46
47 ################################################################################
48
49
50 def usage(exit_code=0):
51     print """Usage: dak auto-decruft
52 Automatic removal of common kinds of cruft
53
54   -h, --help                show this help and exit.
55   -n, --dry-run             don't do anything, just show what would have been done
56   -s, --suite=SUITE         check suite SUITE.
57   --if-NVI OSUITE           remove all packages in SUITE with a lower version than
58                             in OSUITE (e.g. -s experimental --if-NVI unstable)
59   --if-NVI-rm-tag RMTAG     use RMTAG in the removal message (e.g. "NVIU")
60   """
61     sys.exit(exit_code)
62
63 ################################################################################
64
65
66 def compute_sourceless_groups(suite_id, session):
67     """Find binaries without a source
68
69     @type suite_id: int
70     @param suite_id: The id of the suite denoted by suite_name
71
72     @type session: SQLA Session
73     @param session: The database session in use
74     """""
75     rows = query_without_source(suite_id, session)
76     message = '[auto-cruft] no longer built from source, no reverse dependencies'
77     arch_all_id_tuple = tuple([get_architecture('all', session=session)])
78     arch_all_list = ["all"]
79     for row in rows:
80         package = row[0]
81         group_info = {
82             "name": "sourceless:%s" % package,
83             "packages": tuple([package]),
84             "architectures": arch_all_list,
85             "architecture_ids": arch_all_id_tuple,
86             "message": message,
87             "removal_request": {
88                 package: arch_all_list,
89             },
90         }
91         yield group_info
92
93
94 def compute_nbs_groups(suite_id, suite_name, session):
95     """Find binaries no longer built
96
97     @type suite_id: int
98     @param suite_id: The id of the suite denoted by suite_name
99
100     @type suite_name: string
101     @param suite_name: The name of the suite to remove from
102
103     @type session: SQLA Session
104     @param session: The database session in use
105     """""
106     rows = queryNBS(suite_id, session)
107     arch2ids = dict((a.arch_string, a.arch_id) for a in get_suite_architectures(suite_name))
108
109     for row in rows:
110         (pkg_list, arch_list, source, _) = row
111         message = '[auto-cruft] NBS (no longer built by %s, no reverse dependencies)' % source
112         removal_request = dict((pkg, arch_list) for pkg in pkg_list)
113         group_info = {
114             "name": "NBS:%s" % source,
115             "packages": tuple(sorted(pkg_list)),
116             "architectures": sorted(arch_list, cmp=utils.arch_compare_sw),
117             "architecture_ids": tuple(arch2ids[arch] for arch in arch_list),
118             "message": message,
119             "removal_request": removal_request,
120         }
121         yield group_info
122
123
124 def remove_groups(groups, suite_id, suite_name, session):
125     for group in groups:
126         message = group["message"]
127         params = {
128             "architecture_ids": group["architecture_ids"],
129             "packages": group["packages"],
130             "suite_id": suite_id
131         }
132         q = session.execute("""
133             SELECT b.package, b.version, a.arch_string, b.id
134             FROM binaries b
135                 JOIN bin_associations ba ON b.id = ba.bin
136                 JOIN architecture a ON b.architecture = a.id
137                 JOIN suite su ON ba.suite = su.id
138             WHERE a.id IN :architecture_ids AND b.package IN :packages AND su.id = :suite_id
139             """, params)
140
141         remove(session, message, [suite_name], list(q), partial=True, whoami="DAK's auto-decrufter")
142
143
144 def auto_decruft_suite(suite_name, suite_id, session, dryrun, debug):
145     """Run the auto-decrufter on a given suite
146
147     @type suite_name: string
148     @param suite_name: The name of the suite to remove from
149
150     @type suite_id: int
151     @param suite_id: The id of the suite denoted by suite_name
152
153     @type session: SQLA Session
154     @param session: The database session in use
155
156     @type dryrun: bool
157     @param dryrun: If True, just print the actions rather than actually doing them
158
159     @type debug: bool
160     @param debug: If True, print some extra information
161     """
162     all_architectures = [a.arch_string for a in get_suite_architectures(suite_name)]
163     pkg_arch2groups = defaultdict(set)
164     group_order = []
165     groups = {}
166     full_removal_request = []
167     group_generator = chain(
168         compute_sourceless_groups(suite_id, session),
169         compute_nbs_groups(suite_id, suite_name, session)
170     )
171     for group in group_generator:
172         group_name = group["name"]
173         pkgs = group["packages"]
174         affected_archs = group["architectures"]
175         removal_request = group["removal_request"]
176         # If we remove an arch:all package, then the breakage can occur on any
177         # of the architectures.
178         if "all" in affected_archs:
179             affected_archs = all_architectures
180         for pkg_arch in product(pkgs, affected_archs):
181             pkg_arch2groups[pkg_arch].add(group_name)
182         groups[group_name] = group
183         group_order.append(group_name)
184
185         full_removal_request.extend(removal_request.iteritems())
186
187     if not groups:
188         if debug:
189             print "N: Found no candidates"
190         return
191     if debug:
192         print "N: Considering to remove the following packages:"
193         for group_name in sorted(groups):
194             group_info = groups[group_name]
195             pkgs = group_info["packages"]
196             archs = group_info["architectures"]
197             print "N: * %s: %s [%s]" % (group_name, ", ".join(pkgs), " ".join(archs))
198
199     if debug:
200         print "N: Compiling ReverseDependencyChecker (RDC) - please hold ..."
201     rdc = ReverseDependencyChecker(session, suite_name)
202     if debug:
203         print "N: Computing initial breakage..."
204
205     breakage = rdc.check_reverse_depends(full_removal_request)
206     while breakage:
207         by_breakers = [(len(breakage[x]), x, breakage[x]) for x in breakage]
208         by_breakers.sort(reverse=True)
209         if debug:
210             print "N: - Removal would break %s (package, architecture)-pairs" % (len(breakage))
211             print "N: - full breakage:"
212             for _, breaker, broken in by_breakers:
213                 bname = "%s/%s" % breaker
214                 broken_str = ", ".join("%s/%s" % b for b in sorted(broken))
215                 print "N:    * %s => %s" % (bname, broken_str)
216
217         averted_breakage = set()
218
219         for _, package_arch, breakage in by_breakers:
220             if breakage <= averted_breakage:
221                 # We already avoided this break
222                 continue
223             guilty_groups = pkg_arch2groups[package_arch]
224
225             if not guilty_groups:
226                 utils.fubar("Cannot figure what group provided %s" % str(package_arch))
227
228             if debug:
229                 # Only output it, if it truly a new group being discarded
230                 # - a group can reach this part multiple times, if it breaks things on
231                 #   more than one architecture.  This being rather common in fact.
232                 already_discard = True
233                 if any(group_name for group_name in guilty_groups if group_name in groups):
234                     already_discard = False
235
236                 if not already_discard:
237                     avoided = sorted(breakage - averted_breakage)
238                     print "N: - skipping removal of %s (breakage: %s)" % (", ".join(sorted(guilty_groups)), str(avoided))
239
240             averted_breakage |= breakage
241             for group_name in guilty_groups:
242                 if group_name in groups:
243                     del groups[group_name]
244
245         if not groups:
246             if debug:
247                 print "N: Nothing left to remove"
248             return
249
250         if debug:
251             print "N: Now considering to remove: %s" % str(", ".join(sorted(groups.iterkeys())))
252
253         # Rebuild the removal request with the remaining groups and off
254         # we go to (not) break the world once more time
255         full_removal_request =  []
256         for group_info in groups.itervalues():
257             full_removal_request.extend(group_info["removal_request"].iteritems())
258         breakage = rdc.check_reverse_depends(full_removal_request)
259
260     if debug:
261         print "N: Removal looks good"
262
263     if dryrun:
264         print "Would remove the equivalent of:"
265         for group_name in group_order:
266             if group_name not in groups:
267                 continue
268             group_info = groups[group_name]
269             pkgs = group_info["packages"]
270             archs = group_info["architectures"]
271             message = group_info["message"]
272
273             # Embed the -R just in case someone wants to run it manually later
274             print '    dak rm -m "{message}" -s {suite} -a {architectures} -p -R -b {packages}'.format(
275                 message=message, suite=suite_name,
276                 architectures=",".join(archs), packages=" ".join(pkgs),
277             )
278
279         print
280         print "Note: The removals may be interdependent.  A non-breaking result may require the execution of all"
281         print "of the removals"
282     else:
283         remove_groups(groups.itervalues(), suite_id, suite_name, session)
284
285
286 def sources2removals(source_list, suite_id, session):
287     """Compute removals items given a list of names of source packages
288
289     @type source_list: list
290     @param source_list: A list of names of source packages
291
292     @type suite_id: int
293     @param suite_id: The id of the suite from which these sources should be removed
294
295     @type session: SQLA Session
296     @param session: The database session in use
297
298     @rtype: list
299     @return: A list of items to be removed to remove all sources and their binaries from the given suite
300     """
301     to_remove = []
302     params = {"suite_id": suite_id, "sources": tuple(source_list)}
303     q = session.execute("""
304                     SELECT s.source, s.version, 'source', s.id
305                     FROM source s,
306                          JOIN src_associations sa ON sa.source = s.id
307                          JOIN suite su ON sa.suite = su.id
308                     WHERE su.id = :suite_id AND s.source IN :sources""", params)
309     to_remove.extend(q)
310     q = session.execute("""
311                     SELECT b.package, b.version, a.arch_string, b.id
312                     FROM binaries b
313                          JOIN bin_associations ba ON b.id = ba.bin
314                          JOIN architecture a ON b.architecture = a.id
315                          JOIN suite su ON ba.suite = su.id
316                          JOIN source s ON b.source = s.id
317                          JOIN src_associations sa ON s.id = sa.source AND sa.suite = su.id
318                     WHERE su.id = :suite_id AND s.source IN :sources""", params)
319     to_remove.extend(q)
320     return to_remove
321
322
323 def decruft_newer_version_in(othersuite, suite_name, suite_id, rm_msg, session, dryrun):
324     """Compute removals items given a list of names of source packages
325
326     @type othersuite: str
327     @param othersuite: The name of the suite to compare with (e.g. "unstable" for "NVIU")
328
329     @type suite: str
330     @param suite: The name of the suite from which to do removals (e.g. "experimental" for "NVIU")
331
332     @type suite_id: int
333     @param suite_id: The id of the suite from which these sources should be removed
334
335     @type rm_msg: str
336     @param rm_msg: The removal message (or tag, e.g. "NVIU")
337
338     @type session: SQLA Session
339     @param session: The database session in use
340
341     @type dryrun: bool
342     @param dryrun: If True, just print the actions rather than actually doing them
343     """
344     nvi_list = [x[0] for x in newer_version(othersuite, suite_name, session)]
345     if nvi_list:
346         message = "[auto-cruft] %s" % rm_msg
347         if dryrun:
348             print "    dak rm -m \"%s\" -s %s %s" % (message, suite_name, " ".join(nvi_list))
349         else:
350             removals = sources2removals(nvi_list, suite_id, session)
351             remove(session, message, [suite_name], removals, whoami="DAK's auto-decrufter")
352
353 ################################################################################
354
355 def main ():
356     global Options
357     cnf = Config()
358
359     Arguments = [('h',"help","Auto-Decruft::Options::Help"),
360                  ('n',"dry-run","Auto-Decruft::Options::Dry-Run"),
361                  ('d',"debug","Auto-Decruft::Options::Debug"),
362                  ('s',"suite","Auto-Decruft::Options::Suite","HasArg"),
363                  ('z','if-NVI',"Auto-Decruft::Options::OtherSuite", "HasArg"),
364                  ('Z','if-NVI-rm-msg',"Auto-Decruft::Options::OtherSuiteRMMsg", "HasArg")]
365     for i in ["help", "Dry-Run", "Debug", "OtherSuite", "OtherSuiteRMMsg"]:
366         if not cnf.has_key("Auto-Decruft::Options::%s" % (i)):
367             cnf["Auto-Decruft::Options::%s" % (i)] = ""
368
369     cnf["Auto-Decruft::Options::Suite"] = cnf.get("Dinstall::DefaultSuite", "unstable")
370
371     apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
372
373     Options = cnf.subtree("Auto-Decruft::Options")
374     if Options["Help"]:
375         usage()
376
377     debug = False
378     dryrun = False
379     if Options["Dry-Run"]:
380         dryrun = True
381     if Options["Debug"]:
382         debug = True
383
384     if Options["OtherSuite"] and not Options["OtherSuiteRMMsg"]:
385         utils.fubar("--if-NVI requires --if-NVI-rm-msg")
386
387     session = DBConn().session()
388
389     suite = get_suite(Options["Suite"].lower(), session)
390     if not suite:
391         utils.fubar("Cannot find suite %s" % Options["Suite"].lower())
392
393     suite_id = suite.suite_id
394     suite_name = suite.suite_name.lower()
395
396     auto_decruft_suite(suite_name, suite_id, session, dryrun, debug)
397
398     if Options["OtherSuite"]:
399         osuite = get_suite(Options["OtherSuite"].lower(), session).suite_name
400         decruft_newer_version_in(osuite, suite_name, suite_id, Options["OtherSuiteRMMsg"], session, dryrun)
401
402 ################################################################################
403
404 if __name__ == '__main__':
405     main()