]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
Debug suites might also miss the source package
[dak.git] / dak / rm.py
1 #!/usr/bin/env python
2
3 """ General purpose package removal tool for ftpmaster """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5 # Copyright (C) 2010 Alexander Reichle-Schmehl <tolimar@debian.org>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
24 #    respond.
25 # o Ask again -> No respond. Darren coder supreme.
26 # o OpenBSD decide to make changes, but only in OpenBSD source
27 #    tree. Darren hears, gets angry! Decides: "LICENSE NO ALLOW!"
28 # o Insert Flame War.
29 # o OpenBSD team decide to switch to different packet filter under BSD
30 #    license. Because Project Goal: Every user should be able to make
31 #    changes to source tree. IPF license bad!!
32 # o Darren try get back: says, NetBSD, FreeBSD allowed! MUAHAHAHAH!!!
33 # o Theo say: no care, pf much better than ipf!
34 # o Darren changes mind: changes license. But OpenBSD will not change
35 #    back to ipf. Darren even much more bitter.
36 # o Darren so bitterbitter. Decides: I'LL GET BACK BY FORKING OPENBSD AND
37 #    RELEASING MY OWN VERSION. HEHEHEHEHE.
38
39 #                        http://slashdot.org/comments.pl?sid=26697&cid=2883271
40
41 ################################################################################
42
43 import commands
44 import os
45 import sys
46 import apt_pkg
47 import apt_inst
48 from re import sub
49
50 from daklib.config import Config
51 from daklib.dbconn import *
52 from daklib import utils
53 from daklib.dak_exceptions import *
54 from daklib.rm import remove
55 from daklib.regexes import re_strip_source_version, re_bin_only_nmu
56 import debianbts as bts
57
58 ################################################################################
59
60 Options = None
61
62 ################################################################################
63
64 def usage (exit_code=0):
65     print """Usage: dak rm [OPTIONS] PACKAGE[...]
66 Remove PACKAGE(s) from suite(s).
67
68   -A, --no-arch-all-rdeps    Do not report breaking arch:all packages
69                              or Build-Depends-Indep
70   -a, --architecture=ARCH    only act on this architecture
71   -b, --binary               PACKAGE are binary packages to remove
72   -B, --binary-only          remove binaries only
73   -c, --component=COMPONENT  act on this component
74   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
75   -d, --done=BUG#            send removal message as closure to bug#
76   -D, --do-close             also close all bugs associated to that package
77   -h, --help                 show this help and exit
78   -m, --reason=MSG           reason for removal
79   -n, --no-action            don't do anything
80   -p, --partial              don't affect override files
81   -R, --rdep-check           check reverse dependencies
82   -s, --suite=SUITE          act on this suite
83   -S, --source-only          remove source only
84
85 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
86     --architecture=amd64,i386"""
87
88     sys.exit(exit_code)
89
90 ################################################################################
91
92 # "Hudson: What that's great, that's just fucking great man, now what
93 #  the fuck are we supposed to do? We're in some real pretty shit now
94 #  man...That's it man, game over man, game over, man! Game over! What
95 #  the fuck are we gonna do now? What are we gonna do?"
96
97 def game_over():
98     answer = utils.our_raw_input("Continue (y/N)? ").lower()
99     if answer != "y":
100         print "Aborted."
101         sys.exit(1)
102
103 ################################################################################
104
105 def reverse_depends_check(removals, suite, arches=None, session=None, include_arch_all=True):
106     print "Checking reverse dependencies..."
107     if utils.check_reverse_depends(removals, suite, arches, session, include_arch_all=include_arch_all):
108         print "Dependency problem found."
109         if not Options["No-Action"]:
110             game_over()
111     else:
112         print "No dependency problem found."
113     print
114
115 ################################################################################
116
117 def main ():
118     global Options
119
120     cnf = Config()
121
122     Arguments = [('h',"help","Rm::Options::Help"),
123                  ('A','no-arch-all-rdeps','Rm::Options::NoArchAllRdeps'),
124                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
125                  ('b',"binary", "Rm::Options::Binary"),
126                  ('B',"binary-only", "Rm::Options::Binary-Only"),
127                  ('c',"component", "Rm::Options::Component", "HasArg"),
128                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
129                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
130                  ('D',"do-close","Rm::Options::Do-Close"),
131                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
132                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
133                  ('n',"no-action","Rm::Options::No-Action"),
134                  ('p',"partial", "Rm::Options::Partial"),
135                  ('s',"suite","Rm::Options::Suite", "HasArg"),
136                  ('S',"source-only", "Rm::Options::Source-Only"),
137                  ]
138
139     for i in [ 'NoArchAllRdeps',
140                "architecture", "binary", "binary-only", "carbon-copy", "component",
141                "done", "help", "no-action", "partial", "rdep-check", "reason",
142                "source-only", "Do-Close" ]:
143         if not cnf.has_key("Rm::Options::%s" % (i)):
144             cnf["Rm::Options::%s" % (i)] = ""
145     if not cnf.has_key("Rm::Options::Suite"):
146         cnf["Rm::Options::Suite"] = "unstable"
147
148     arguments = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
149     Options = cnf.subtree("Rm::Options")
150
151     if Options["Help"]:
152         usage()
153
154     session = DBConn().session()
155
156     # Sanity check options
157     if not arguments:
158         utils.fubar("need at least one package name as an argument.")
159     if Options["Architecture"] and Options["Source-Only"]:
160         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
161     if ((Options["Binary"] and Options["Source-Only"])
162             or (Options["Binary"] and Options["Binary-Only"])
163             or (Options["Binary-Only"] and Options["Source-Only"])):
164         utils.fubar("Only one of -b/--binary, -B/--binary-only and -S/--source-only can be used.")
165     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
166         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
167     if Options["Architecture"] and not Options["Partial"]:
168         utils.warn("-a/--architecture implies -p/--partial.")
169         Options["Partial"] = "true"
170     if Options["Do-Close"] and not Options["Done"]:
171         utils.fubar("No.")
172     if (Options["Do-Close"]
173            and (Options["Binary"] or Options["Binary-Only"] or Options["Source-Only"])):
174         utils.fubar("No.")
175
176     # Force the admin to tell someone if we're not doing a 'dak
177     # cruft-report' inspired removal (or closing a bug, which counts
178     # as telling someone).
179     if not Options["No-Action"] and not Options["Carbon-Copy"] \
180            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
181         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
182
183     # Process -C/--carbon-copy
184     #
185     # Accept 3 types of arguments (space separated):
186     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
187     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
188     #  3) contains a '@' - assumed to be an email address, used unmodified
189     #
190     carbon_copy = []
191     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
192         if copy_to.isdigit():
193             if cnf.has_key("Dinstall::BugServer"):
194                 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
195             else:
196                 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
197         elif copy_to == 'package':
198             for package in arguments:
199                 if cnf.has_key("Dinstall::PackagesServer"):
200                     carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
201                 if cnf.has_key("Dinstall::TrackingServer"):
202                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
203         elif '@' in copy_to:
204             carbon_copy.append(copy_to)
205         else:
206             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
207
208     if Options["Binary"]:
209         field = "b.package"
210     else:
211         field = "s.source"
212     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
213
214     (con_suites, con_architectures, con_components, check_source) = \
215                  utils.parse_args(Options)
216
217     # Additional suite checks
218     suite_ids_list = []
219     whitelists = []
220     suites = utils.split_args(Options["Suite"])
221     suites_list = utils.join_with_commas_and(suites)
222     if not Options["No-Action"]:
223         for suite in suites:
224             s = get_suite(suite, session=session)
225             if s is not None:
226                 suite_ids_list.append(s.suite_id)
227                 whitelists.append(s.mail_whitelist)
228             if suite in ("oldstable", "stable"):
229                 print "**WARNING** About to remove from the (old)stable suite!"
230                 print "This should only be done just prior to a (point) release and not at"
231                 print "any other time."
232                 game_over()
233             elif suite == "testing":
234                 print "**WARNING About to remove from the testing suite!"
235                 print "There's no need to do this normally as removals from unstable will"
236                 print "propogate to testing automagically."
237                 game_over()
238
239     # Additional architecture checks
240     if Options["Architecture"] and check_source:
241         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
242
243     # Don't do dependency checks on multiple suites
244     if Options["Rdep-Check"] and len(suites) > 1:
245         utils.fubar("Reverse dependency check on multiple suites is not implemented.")
246
247     to_remove = []
248     maintainers = {}
249
250     # We have 3 modes of package selection: binary, source-only, binary-only
251     # and source+binary.
252
253     # XXX: TODO: This all needs converting to use placeholders or the object
254     #            API. It's an SQL injection dream at the moment
255
256     if Options["Binary"]:
257         # Removal by binary package name
258         q = session.execute("SELECT b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, files f, files_archive_map af, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND af.file_id = f.id AND af.archive_id = su.archive_id AND af.component_id = c.id %s %s %s %s" % (con_packages, con_suites, con_components, con_architectures))
259         to_remove.extend(q)
260     else:
261         # Source-only
262         if not Options["Binary-Only"]:
263             q = session.execute("SELECT s.source, s.version, 'source', s.id, s.maintainer FROM source s, src_associations sa, suite su, archive, files f, files_archive_map af, component c WHERE sa.source = s.id AND sa.suite = su.id AND archive.id = su.archive_id AND s.file = f.id AND af.file_id = f.id AND af.archive_id = su.archive_id AND af.component_id = c.id %s %s %s" % (con_packages, con_suites, con_components))
264             to_remove.extend(q)
265         if not Options["Source-Only"]:
266             # Source + Binary
267             q = session.execute("""
268                     SELECT b.package, b.version, a.arch_string, b.id, b.maintainer
269                     FROM binaries b
270                          JOIN bin_associations ba ON b.id = ba.bin
271                          JOIN architecture a ON b.architecture = a.id
272                          JOIN suite su ON ba.suite = su.id
273                          JOIN archive ON archive.id = su.archive_id
274                          JOIN files_archive_map af ON b.file = af.file_id AND af.archive_id = archive.id
275                          JOIN component c ON af.component_id = c.id
276                          JOIN source s ON b.source = s.id
277                          JOIN src_associations sa ON s.id = sa.source AND sa.suite = su.id
278                     WHERE TRUE %s %s %s %s""" % (con_packages, con_suites, con_components, con_architectures))
279             to_remove.extend(q)
280
281     if not to_remove:
282         print "Nothing to do."
283         sys.exit(0)
284
285     # If we don't have a reason; spawn an editor so the user can add one
286     # Write the rejection email out as the <foo>.reason file
287     if not Options["Reason"] and not Options["No-Action"]:
288         (fd, temp_filename) = utils.temp_filename()
289         editor = os.environ.get("EDITOR","vi")
290         result = os.system("%s %s" % (editor, temp_filename))
291         if result != 0:
292             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
293         temp_file = utils.open_file(temp_filename)
294         for line in temp_file.readlines():
295             Options["Reason"] += line
296         temp_file.close()
297         os.unlink(temp_filename)
298
299     # Generate the summary of what's to be removed
300     d = {}
301     for i in to_remove:
302         package = i[0]
303         version = i[1]
304         architecture = i[2]
305         maintainer = i[4]
306         maintainers[maintainer] = ""
307         if not d.has_key(package):
308             d[package] = {}
309         if not d[package].has_key(version):
310             d[package][version] = []
311         if architecture not in d[package][version]:
312             d[package][version].append(architecture)
313
314     maintainer_list = []
315     for maintainer_id in maintainers.keys():
316         maintainer_list.append(get_maintainer(maintainer_id).name)
317     summary = ""
318     removals = d.keys()
319     removals.sort()
320     for package in removals:
321         versions = d[package].keys()
322         versions.sort(apt_pkg.version_compare)
323         for version in versions:
324             d[package][version].sort(utils.arch_compare_sw)
325             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
326     print "Will remove the following packages from %s:" % (suites_list)
327     print
328     print summary
329     print "Maintainer: %s" % ", ".join(maintainer_list)
330     if Options["Done"]:
331         print "Will also close bugs: "+Options["Done"]
332     if carbon_copy:
333         print "Will also send CCs to: " + ", ".join(carbon_copy)
334     if Options["Do-Close"]:
335         print "Will also close associated bug reports."
336     print
337     print "------------------- Reason -------------------"
338     print Options["Reason"]
339     print "----------------------------------------------"
340     print
341
342     if Options["Rdep-Check"]:
343         arches = utils.split_args(Options["Architecture"])
344         include_arch_all = Options['NoArchAllRdeps'] == ''
345         reverse_depends_check(removals, suites[0], arches, session, include_arch_all=include_arch_all)
346
347     # If -n/--no-action, drop out here
348     if Options["No-Action"]:
349         sys.exit(0)
350
351     print "Going to remove the packages now."
352     game_over()
353
354     # Do the actual deletion
355     print "Deleting...",
356     sys.stdout.flush()
357
358     try:
359         bugs = utils.split_args(Options["Done"])
360         remove(session, Options["Reason"], suites, to_remove,
361                partial=Options["Partial"], components=utils.split_args(Options["Component"]),
362                done_bugs=bugs, carbon_copy=carbon_copy, close_related_bugs=Options["Do-Close"]
363                )
364     except ValueError as ex:
365         utils.fubar(ex.message)
366     else:
367         print "done."
368
369 #######################################################################################
370
371 if __name__ == '__main__':
372     main()