]> git.decadent.org.uk Git - dak.git/blob - dak/auto_decruft.py
Rewrite auto-decruft to group removals
[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 cruft-report
52 Check for obsolete or duplicated packages.
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     sys.exit(exit_code)
58
59 ################################################################################
60
61
62 def compute_sourceless_groups(suite_id, session):
63     """Find binaries without a source
64
65     @type suite_id: int
66     @param suite_id: The id of the suite donated by suite_name
67
68     @type session: SQLA Session
69     @param session: The database session in use
70     """""
71     rows = query_without_source(suite_id, session)
72     message = '[auto-cruft] no longer built from source, no reverse dependencies'
73     arch_all_id_tuple = tuple([get_architecture('all', session=session)])
74     arch_all_list = ["all"]
75     for row in rows:
76         package = row[0]
77         group_info = {
78             "name": "sourceless:%s" % package,
79             "packages": tuple([package]),
80             "architectures": arch_all_list,
81             "architecture_ids": arch_all_id_tuple,
82             "message": message,
83             "removal_request": {
84                 package: arch_all_list,
85             },
86         }
87         yield group_info
88
89
90 def compute_nbs_groups(suite_id, suite_name, session):
91     """Find binaries no longer built
92
93     @type suite_id: int
94     @param suite_id: The id of the suite donated by suite_name
95
96     @type suite_name: string
97     @param suite_name: The name of the suite to remove from
98
99     @type session: SQLA Session
100     @param session: The database session in use
101     """""
102     rows = queryNBS(suite_id, session)
103     arch2ids = dict((a.arch_string, a.arch_id) for a in get_suite_architectures(suite_name))
104
105     for row in rows:
106         (pkg_list, arch_list, source, _) = row
107         message = '[auto-cruft] NBS (no longer built by %s, no reverse dependencies)' % source
108         removal_request = dict((pkg, arch_list) for pkg in pkg_list)
109         group_info = {
110             "name": "NBS:%s" % source,
111             "packages": tuple(sorted(pkg_list)),
112             "architectures": sorted(arch_list, cmp=utils.arch_compare_sw),
113             "architecture_ids": tuple(arch2ids[arch] for arch in arch_list),
114             "message": message,
115             "removal_request": removal_request,
116         }
117         yield group_info
118
119
120 def remove_groups(groups, suite_id, suite_name, session):
121     for group in groups:
122         message = group["message"]
123         params = {
124             "architecture_ids": group["architecture_ids"],
125             "packages": group["packages"],
126             "suite_id": suite_id
127         }
128         q = session.execute("""
129             SELECT b.package, b.version, a.arch_string, b.id
130             FROM binaries b
131                 JOIN bin_associations ba ON b.id = ba.bin
132                 JOIN architecture a ON b.architecture = a.id
133                 JOIN suite su ON ba.suite = su.id
134             WHERE a.id IN :architecture_ids AND b.package IN :packages AND su.id = :suite_id
135             """, params)
136
137         remove(session, message, [suite_name], list(q), partial=True, whoami="DAK's auto-decrufter")
138
139
140 def auto_decruft_suite(suite_name, suite_id, session, dryrun, debug):
141     """Run the auto-decrufter on a given suite
142
143     @type suite_name: string
144     @param suite_name: The name of the suite to remove from
145
146     @type suite_id: int
147     @param suite_id: The id of the suite donated by suite_name
148
149     @type session: SQLA Session
150     @param session: The database session in use
151
152     @type dryrun: bool
153     @param dryrun: If True, just print the actions rather than actually doing them
154
155     @type debug: bool
156     @param debug: If True, print some extra information
157     """
158     all_architectures = [a.arch_string for a in get_suite_architectures(suite_name)]
159     pkg_arch2groups = defaultdict(set)
160     group_order = []
161     groups = {}
162     full_removal_request = []
163     group_generator = chain(
164         compute_sourceless_groups(suite_id, session),
165         compute_nbs_groups(suite_id, suite_name, session)
166     )
167     for group in group_generator:
168         group_name = group["name"]
169         pkgs = group["packages"]
170         affected_archs = group["architectures"]
171         removal_request = group["removal_request"]
172         # If we remove an arch:all package, then the breakage can occur on any
173         # of the architectures.
174         if "all" in affected_archs:
175             affected_archs = all_architectures
176         for pkg_arch in product(pkgs, affected_archs):
177             pkg_arch2groups[pkg_arch].add(group_name)
178         groups[group_name] = group
179         group_order.append(group_name)
180
181         full_removal_request.extend(removal_request.iteritems())
182
183     if not groups:
184         if debug:
185             print "N: Found no candidates"
186         return
187     if debug:
188         print "N: Considering to remove the following packages:"
189         for group_name in sorted(groups):
190             group_info = groups[group_name]
191             pkgs = group_info["packages"]
192             archs = group_info["architectures"]
193             print "N: * %s: %s [%s]" % (group_name, ", ".join(pkgs), " ".join(archs))
194
195     if debug:
196         print "N: Compiling ReverseDependencyChecker (RDC) - please hold ..."
197     rdc = ReverseDependencyChecker(session, suite_name)
198     if debug:
199         print "N: Computing initial breakage..."
200
201     breakage = rdc.check_reverse_depends(full_removal_request)
202     while breakage:
203         by_breakers = [(len(breakage[x]), x, breakage[x]) for x in breakage]
204         by_breakers.sort(reverse=True)
205         if debug:
206             print "N: - Removal would break %s (package, architecture)-pairs" % (len(breakage))
207             print "N: - full breakage:"
208             for _, breaker, broken in by_breakers:
209                 bname = "%s/%s" % breaker
210                 broken_str = ", ".join("%s/%s" % b for b in sorted(broken))
211                 print "N:    * %s => %s" % (bname, broken_str)
212
213         averted_breakage = set()
214
215         for _, package_arch, breakage in by_breakers:
216             if breakage <= averted_breakage:
217                 # We already avoided this break
218                 continue
219             guilty_groups = pkg_arch2groups[package_arch]
220
221             if not guilty_groups:
222                 utils.fubar("Cannot figure what group provided %s" % str(package_arch))
223
224             if debug:
225                 # Only output it, if it truly a new group being discarded
226                 # - a group can reach this part multiple times, if it breaks things on
227                 #   more than one architecture.  This being rather common in fact.
228                 already_discard = True
229                 if any(group_name for group_name in guilty_groups if group_name in groups):
230                     already_discard = False
231
232                 if not already_discard:
233                     avoided = sorted(breakage - averted_breakage)
234                     print "N: - skipping removal of %s (breakage: %s)" % (", ".join(sorted(guilty_groups)), str(avoided))
235
236             averted_breakage |= breakage
237             for group_name in guilty_groups:
238                 if group_name in groups:
239                     del groups[group_name]
240
241         if not groups:
242             if debug:
243                 print "N: Nothing left to remove"
244             return
245
246         if debug:
247             print "N: Now considering to remove: %s" % str(", ".join(sorted(groups.iterkeys())))
248
249         # Rebuild the removal request with the remaining groups and off
250         # we go to (not) break the world once more time
251         full_removal_request =  []
252         for group_info in groups.itervalues():
253             full_removal_request.extend(group_info["removal_request"].iteritems())
254         breakage = rdc.check_reverse_depends(full_removal_request)
255
256     if debug:
257         print "N: Removal looks good"
258
259     if dryrun:
260         print "Would remove the equivalent of:"
261         for group_name in group_order:
262             if group_name not in groups:
263                 continue
264             group_info = groups[group_name]
265             pkgs = group_info["packages"]
266             archs = group_info["architectures"]
267             message = group_info["message"]
268
269             # Embed the -R just in case someone wants to run it manually later
270             print '    dak rm -m "{message}" -s {suite} -a {architectures} -p -R -b {packages}'.format(
271                 message=message, suite=suite_name,
272                 architectures=",".join(archs), packages=" ".join(pkgs),
273             )
274
275         print
276         print "Note: The removals may be interdependent.  A non-breaking result may require the execution of all"
277         print "of the removals"
278     else:
279         remove_groups(groups.itervalues(), suite_id, suite_name, session)
280
281
282 ################################################################################
283
284 def main ():
285     global Options
286     cnf = Config()
287
288     Arguments = [('h',"help","Auto-Decruft::Options::Help"),
289                  ('n',"dry-run","Auto-Decruft::Options::Dry-Run"),
290                  ('d',"debug","Auto-Decruft::Options::Debug"),
291                  ('s',"suite","Auto-Decruft::Options::Suite","HasArg")]
292     for i in ["help", "Dry-Run", "Debug"]:
293         if not cnf.has_key("Auto-Decruft::Options::%s" % (i)):
294             cnf["Auto-Decruft::Options::%s" % (i)] = ""
295
296     cnf["Auto-Decruft::Options::Suite"] = cnf.get("Dinstall::DefaultSuite", "unstable")
297
298     apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
299
300     Options = cnf.subtree("Auto-Decruft::Options")
301     if Options["Help"]:
302         usage()
303
304     debug = False
305     dryrun = False
306     if Options["Dry-Run"]:
307         dryrun = True
308     if Options["Debug"]:
309         debug = True
310
311     session = DBConn().session()
312
313     suite = get_suite(Options["Suite"].lower(), session)
314     if not suite:
315         utils.fubar("Cannot find suite %s" % Options["Suite"].lower())
316
317     suite_id = suite.suite_id
318     suite_name = suite.suite_name.lower()
319
320     auto_decruft_suite(suite_name, suite_id, session, dryrun, debug)
321
322 ################################################################################
323
324 if __name__ == '__main__':
325     main()