]> git.decadent.org.uk Git - dak.git/blob - dak/auto_decruft.py
auto-decruft: Fix and reduce two SQL statements
[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-newer-version-in OS  remove all packages in SUITE with a lower version than
58                             in OS (e.g. -s experimental --if-newer-version-in
59                             unstable)
60   --if-newer-version-in-rm-msg RMMSG
61                             use RMMSG in the removal message (e.g. "NVIU")
62   """
63     sys.exit(exit_code)
64
65 ################################################################################
66
67
68 def compute_sourceless_groups(suite_id, session):
69     """Find binaries without a source
70
71     @type suite_id: int
72     @param suite_id: The id of the suite denoted by suite_name
73
74     @type session: SQLA Session
75     @param session: The database session in use
76     """""
77     rows = query_without_source(suite_id, session)
78     message = '[auto-cruft] no longer built from source, no reverse dependencies'
79     arch_all_id_tuple = tuple([get_architecture('all', session=session)])
80     arch_all_list = ["all"]
81     for row in rows:
82         package = row[0]
83         group_info = {
84             "name": "sourceless:%s" % package,
85             "packages": tuple([package]),
86             "architectures": arch_all_list,
87             "architecture_ids": arch_all_id_tuple,
88             "message": message,
89             "removal_request": {
90                 package: arch_all_list,
91             },
92         }
93         yield group_info
94
95
96 def compute_nbs_groups(suite_id, suite_name, session):
97     """Find binaries no longer built
98
99     @type suite_id: int
100     @param suite_id: The id of the suite denoted by suite_name
101
102     @type suite_name: string
103     @param suite_name: The name of the suite to remove from
104
105     @type session: SQLA Session
106     @param session: The database session in use
107     """""
108     rows = queryNBS(suite_id, session)
109     arch2ids = dict((a.arch_string, a.arch_id) for a in get_suite_architectures(suite_name))
110
111     for row in rows:
112         (pkg_list, arch_list, source, _) = row
113         message = '[auto-cruft] NBS (no longer built by %s, no reverse dependencies)' % source
114         removal_request = dict((pkg, arch_list) for pkg in pkg_list)
115         group_info = {
116             "name": "NBS:%s" % source,
117             "packages": tuple(sorted(pkg_list)),
118             "architectures": sorted(arch_list, cmp=utils.arch_compare_sw),
119             "architecture_ids": tuple(arch2ids[arch] for arch in arch_list),
120             "message": message,
121             "removal_request": removal_request,
122         }
123         yield group_info
124
125
126 def remove_groups(groups, suite_id, suite_name, session):
127     for group in groups:
128         message = group["message"]
129         params = {
130             "architecture_ids": group["architecture_ids"],
131             "packages": group["packages"],
132             "suite_id": suite_id
133         }
134         q = session.execute("""
135             SELECT b.package, b.version, a.arch_string, b.id
136             FROM binaries b
137                 JOIN bin_associations ba ON b.id = ba.bin
138                 JOIN architecture a ON b.architecture = a.id
139                 JOIN suite su ON ba.suite = su.id
140             WHERE a.id IN :architecture_ids AND b.package IN :packages AND su.id = :suite_id
141             """, params)
142
143         remove(session, message, [suite_name], list(q), partial=True, whoami="DAK's auto-decrufter")
144
145
146 def dedup(*args):
147     seen = set()
148     for iterable in args:
149         for value in iterable:
150             if value not in seen:
151                 seen.add(value)
152                 yield value
153
154
155 def merge_group(groupA, groupB):
156     """Merges two removal groups into one
157
158     Note that some values are taken entirely from groupA (e.g. name and message)
159
160     @type groupA: dict
161     @param groupA: A removal group
162
163     @type groupB: dict
164     @param groupB: Another removal group
165
166     @rtype: dict
167     @returns: A merged group
168     """
169     pkg_list = sorted(dedup(groupA["packages"], groupB["packages"]))
170     arch_list = sorted(dedup(groupA["architectures"], groupB["architectures"]), cmp=utils.arch_compare_sw)
171     arch_list_id = dedup(groupA["architecture_ids"], groupB["architecture_ids"])
172     removalA = groupA["removal_request"]
173     removalB = groupB["removal_request"]
174     new_removal = {}
175     for pkg in dedup(removalA, removalB):
176         listA = removalA[pkg] if pkg in removalA else []
177         listB = removalB[pkg] if pkg in removalB else []
178         new_removal[pkg] = sorted(dedup(listA, listB), cmp=utils.arch_compare_sw)
179
180     merged_group = {
181         "name": groupA["name"],
182         "packages": tuple(pkg_list),
183         "architectures": arch_list,
184         "architecture_ids": tuple(arch_list_id),
185         "message": groupA["message"],
186         "removal_request": new_removal,
187     }
188
189     return merged_group
190
191
192 def auto_decruft_suite(suite_name, suite_id, session, dryrun, debug):
193     """Run the auto-decrufter on a given suite
194
195     @type suite_name: string
196     @param suite_name: The name of the suite to remove from
197
198     @type suite_id: int
199     @param suite_id: The id of the suite denoted by suite_name
200
201     @type session: SQLA Session
202     @param session: The database session in use
203
204     @type dryrun: bool
205     @param dryrun: If True, just print the actions rather than actually doing them
206
207     @type debug: bool
208     @param debug: If True, print some extra information
209     """
210     all_architectures = [a.arch_string for a in get_suite_architectures(suite_name)]
211     pkg_arch2groups = defaultdict(set)
212     group_order = []
213     groups = {}
214     full_removal_request = []
215     group_generator = chain(
216         compute_sourceless_groups(suite_id, session),
217         compute_nbs_groups(suite_id, suite_name, session)
218     )
219     for group in group_generator:
220         group_name = group["name"]
221         if group_name not in groups:
222             pkgs = group["packages"]
223             affected_archs = group["architectures"]
224             # If we remove an arch:all package, then the breakage can occur on any
225             # of the architectures.
226             if "all" in affected_archs:
227                 affected_archs = all_architectures
228             for pkg_arch in product(pkgs, affected_archs):
229                 pkg_arch2groups[pkg_arch].add(group_name)
230             groups[group_name] = group
231             group_order.append(group_name)
232         else:
233             # This case usually happens when versions differ between architectures...
234             if debug:
235                 print "N: Merging group %s" % (group_name)
236             groups[group_name] = merge_group(groups[group_name], group)
237
238     for group_name in group_order:
239         removal_request = groups[group_name]["removal_request"]
240         full_removal_request.extend(removal_request.iteritems())
241
242     if not groups:
243         if debug:
244             print "N: Found no candidates"
245         return
246
247     if debug:
248         print "N: Considering to remove the following packages:"
249         for group_name in sorted(groups):
250             group_info = groups[group_name]
251             pkgs = group_info["packages"]
252             archs = group_info["architectures"]
253             print "N: * %s: %s [%s]" % (group_name, ", ".join(pkgs), " ".join(archs))
254
255     if debug:
256         print "N: Compiling ReverseDependencyChecker (RDC) - please hold ..."
257     rdc = ReverseDependencyChecker(session, suite_name)
258     if debug:
259         print "N: Computing initial breakage..."
260
261     breakage = rdc.check_reverse_depends(full_removal_request)
262     while breakage:
263         by_breakers = [(len(breakage[x]), x, breakage[x]) for x in breakage]
264         by_breakers.sort(reverse=True)
265         if debug:
266             print "N: - Removal would break %s (package, architecture)-pairs" % (len(breakage))
267             print "N: - full breakage:"
268             for _, breaker, broken in by_breakers:
269                 bname = "%s/%s" % breaker
270                 broken_str = ", ".join("%s/%s" % b for b in sorted(broken))
271                 print "N:    * %s => %s" % (bname, broken_str)
272
273         averted_breakage = set()
274
275         for _, package_arch, breakage in by_breakers:
276             if breakage <= averted_breakage:
277                 # We already avoided this break
278                 continue
279             guilty_groups = pkg_arch2groups[package_arch]
280
281             if not guilty_groups:
282                 utils.fubar("Cannot figure what group provided %s" % str(package_arch))
283
284             if debug:
285                 # Only output it, if it truly a new group being discarded
286                 # - a group can reach this part multiple times, if it breaks things on
287                 #   more than one architecture.  This being rather common in fact.
288                 already_discard = True
289                 if any(group_name for group_name in guilty_groups if group_name in groups):
290                     already_discard = False
291
292                 if not already_discard:
293                     avoided = sorted(breakage - averted_breakage)
294                     print "N: - skipping removal of %s (breakage: %s)" % (", ".join(sorted(guilty_groups)), str(avoided))
295
296             averted_breakage |= breakage
297             for group_name in guilty_groups:
298                 if group_name in groups:
299                     del groups[group_name]
300
301         if not groups:
302             if debug:
303                 print "N: Nothing left to remove"
304             return
305
306         if debug:
307             print "N: Now considering to remove: %s" % str(", ".join(sorted(groups.iterkeys())))
308
309         # Rebuild the removal request with the remaining groups and off
310         # we go to (not) break the world once more time
311         full_removal_request =  []
312         for group_info in groups.itervalues():
313             full_removal_request.extend(group_info["removal_request"].iteritems())
314         breakage = rdc.check_reverse_depends(full_removal_request)
315
316     if debug:
317         print "N: Removal looks good"
318
319     if dryrun:
320         print "Would remove the equivalent of:"
321         for group_name in group_order:
322             if group_name not in groups:
323                 continue
324             group_info = groups[group_name]
325             pkgs = group_info["packages"]
326             archs = group_info["architectures"]
327             message = group_info["message"]
328
329             # Embed the -R just in case someone wants to run it manually later
330             print '    dak rm -m "{message}" -s {suite} -a {architectures} -p -R -b {packages}'.format(
331                 message=message, suite=suite_name,
332                 architectures=",".join(archs), packages=" ".join(pkgs),
333             )
334
335         print
336         print "Note: The removals may be interdependent.  A non-breaking result may require the execution of all"
337         print "of the removals"
338     else:
339         remove_groups(groups.itervalues(), suite_id, suite_name, session)
340
341
342 def sources2removals(source_list, suite_id, session):
343     """Compute removals items given a list of names of source packages
344
345     @type source_list: list
346     @param source_list: A list of names of source packages
347
348     @type suite_id: int
349     @param suite_id: The id of the suite from which these sources should be removed
350
351     @type session: SQLA Session
352     @param session: The database session in use
353
354     @rtype: list
355     @return: A list of items to be removed to remove all sources and their binaries from the given suite
356     """
357     to_remove = []
358     params = {"suite_id": suite_id, "sources": tuple(source_list)}
359     q = session.execute("""
360                     SELECT s.source, s.version, 'source', s.id
361                     FROM source s
362                          JOIN src_associations sa ON sa.source = s.id
363                     WHERE sa.suite = :suite_id AND s.source IN :sources""", params)
364     to_remove.extend(q)
365     q = session.execute("""
366                     SELECT b.package, b.version, a.arch_string, b.id
367                     FROM binaries b
368                          JOIN bin_associations ba ON b.id = ba.bin
369                          JOIN architecture a ON b.architecture = a.id
370                          JOIN source s ON b.source = s.id
371                     WHERE ba.suite = :suite_id AND s.source IN :sources""", params)
372     to_remove.extend(q)
373     return to_remove
374
375
376 def decruft_newer_version_in(othersuite, suite_name, suite_id, rm_msg, session, dryrun):
377     """Compute removals items given a list of names of source packages
378
379     @type othersuite: str
380     @param othersuite: The name of the suite to compare with (e.g. "unstable" for "NVIU")
381
382     @type suite: str
383     @param suite: The name of the suite from which to do removals (e.g. "experimental" for "NVIU")
384
385     @type suite_id: int
386     @param suite_id: The id of the suite from which these sources should be removed
387
388     @type rm_msg: str
389     @param rm_msg: The removal message (or tag, e.g. "NVIU")
390
391     @type session: SQLA Session
392     @param session: The database session in use
393
394     @type dryrun: bool
395     @param dryrun: If True, just print the actions rather than actually doing them
396     """
397     nvi_list = [x[0] for x in newer_version(othersuite, suite_name, session)]
398     if nvi_list:
399         message = "[auto-cruft] %s" % rm_msg
400         if dryrun:
401             print "    dak rm -m \"%s\" -s %s %s" % (message, suite_name, " ".join(nvi_list))
402         else:
403             removals = sources2removals(nvi_list, suite_id, session)
404             remove(session, message, [suite_name], removals, whoami="DAK's auto-decrufter")
405
406 ################################################################################
407
408 def main ():
409     global Options
410     cnf = Config()
411
412     Arguments = [('h',"help","Auto-Decruft::Options::Help"),
413                  ('n',"dry-run","Auto-Decruft::Options::Dry-Run"),
414                  ('d',"debug","Auto-Decruft::Options::Debug"),
415                  ('s',"suite","Auto-Decruft::Options::Suite","HasArg"),
416                  ('z','if-newer-version-in',"Auto-Decruft::Options::OtherSuite", "HasArg"),
417                  ('Z','if-newer-version-in-rm-msg',"Auto-Decruft::Options::OtherSuiteRMMsg", "HasArg")]
418     for i in ["help", "Dry-Run", "Debug", "OtherSuite", "OtherSuiteRMMsg"]:
419         if not cnf.has_key("Auto-Decruft::Options::%s" % (i)):
420             cnf["Auto-Decruft::Options::%s" % (i)] = ""
421
422     cnf["Auto-Decruft::Options::Suite"] = cnf.get("Dinstall::DefaultSuite", "unstable")
423
424     apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
425
426     Options = cnf.subtree("Auto-Decruft::Options")
427     if Options["Help"]:
428         usage()
429
430     debug = False
431     dryrun = False
432     if Options["Dry-Run"]:
433         dryrun = True
434     if Options["Debug"]:
435         debug = True
436
437     if Options["OtherSuite"] and not Options["OtherSuiteRMMsg"]:
438         utils.fubar("--if-newer-version-in requires --if-newer-version-in-rm-msg")
439
440     session = DBConn().session()
441
442     suite = get_suite(Options["Suite"].lower(), session)
443     if not suite:
444         utils.fubar("Cannot find suite %s" % Options["Suite"].lower())
445
446     suite_id = suite.suite_id
447     suite_name = suite.suite_name.lower()
448
449     auto_decruft_suite(suite_name, suite_id, session, dryrun, debug)
450
451     if Options["OtherSuite"]:
452         osuite = get_suite(Options["OtherSuite"].lower(), session).suite_name
453         decruft_newer_version_in(osuite, suite_name, suite_id, Options["OtherSuiteRMMsg"], session, dryrun)
454
455 ################################################################################
456
457 if __name__ == '__main__':
458     main()