]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
Adjust to deal with the new Debian supplementaryGid
[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, --architecture=ARCH    only act on this architecture
69   -b, --binary               PACKAGE are binary packages to remove
70   -B, --binary-only          remove binaries only
71   -c, --component=COMPONENT  act on this component
72   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
73   -d, --done=BUG#            send removal message as closure to bug#
74   -D, --do-close             also close all bugs associated to that package
75   -h, --help                 show this help and exit
76   -m, --reason=MSG           reason for removal
77   -n, --no-action            don't do anything
78   -p, --partial              don't affect override files
79   -R, --rdep-check           check reverse dependencies
80   -s, --suite=SUITE          act on this suite
81   -S, --source-only          remove source only
82
83 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
84     --architecture=amd64,i386"""
85
86     sys.exit(exit_code)
87
88 ################################################################################
89
90 # "Hudson: What that's great, that's just fucking great man, now what
91 #  the fuck are we supposed to do? We're in some real pretty shit now
92 #  man...That's it man, game over man, game over, man! Game over! What
93 #  the fuck are we gonna do now? What are we gonna do?"
94
95 def game_over():
96     answer = utils.our_raw_input("Continue (y/N)? ").lower()
97     if answer != "y":
98         print "Aborted."
99         sys.exit(1)
100
101 ################################################################################
102
103 def reverse_depends_check(removals, suite, arches=None, session=None):
104     print "Checking reverse dependencies..."
105     if utils.check_reverse_depends(removals, suite, arches, session):
106         print "Dependency problem found."
107         if not Options["No-Action"]:
108             game_over()
109     else:
110         print "No dependency problem found."
111     print
112
113 ################################################################################
114
115 def main ():
116     global Options
117
118     cnf = Config()
119
120     Arguments = [('h',"help","Rm::Options::Help"),
121                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
122                  ('b',"binary", "Rm::Options::Binary"),
123                  ('B',"binary-only", "Rm::Options::Binary-Only"),
124                  ('c',"component", "Rm::Options::Component", "HasArg"),
125                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
126                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
127                  ('D',"do-close","Rm::Options::Do-Close"),
128                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
129                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
130                  ('n',"no-action","Rm::Options::No-Action"),
131                  ('p',"partial", "Rm::Options::Partial"),
132                  ('s',"suite","Rm::Options::Suite", "HasArg"),
133                  ('S',"source-only", "Rm::Options::Source-Only"),
134                  ]
135
136     for i in [ "architecture", "binary", "binary-only", "carbon-copy", "component",
137                "done", "help", "no-action", "partial", "rdep-check", "reason",
138                "source-only", "Do-Close" ]:
139         if not cnf.has_key("Rm::Options::%s" % (i)):
140             cnf["Rm::Options::%s" % (i)] = ""
141     if not cnf.has_key("Rm::Options::Suite"):
142         cnf["Rm::Options::Suite"] = "unstable"
143
144     arguments = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
145     Options = cnf.subtree("Rm::Options")
146
147     if Options["Help"]:
148         usage()
149
150     session = DBConn().session()
151
152     # Sanity check options
153     if not arguments:
154         utils.fubar("need at least one package name as an argument.")
155     if Options["Architecture"] and Options["Source-Only"]:
156         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
157     if ((Options["Binary"] and Options["Source-Only"])
158             or (Options["Binary"] and Options["Binary-Only"])
159             or (Options["Binary-Only"] and Options["Source-Only"])):
160         utils.fubar("Only one of -b/--binary, -B/--binary-only and -S/--source-only can be used.")
161     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
162         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
163     if Options["Architecture"] and not Options["Partial"]:
164         utils.warn("-a/--architecture implies -p/--partial.")
165         Options["Partial"] = "true"
166     if Options["Do-Close"] and not Options["Done"]:
167         utils.fubar("No.")
168     if (Options["Do-Close"]
169            and (Options["Binary"] or Options["Binary-Only"] or Options["Source-Only"])):
170         utils.fubar("No.")
171
172     # Force the admin to tell someone if we're not doing a 'dak
173     # cruft-report' inspired removal (or closing a bug, which counts
174     # as telling someone).
175     if not Options["No-Action"] and not Options["Carbon-Copy"] \
176            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
177         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
178
179     # Process -C/--carbon-copy
180     #
181     # Accept 3 types of arguments (space separated):
182     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
183     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
184     #  3) contains a '@' - assumed to be an email address, used unmodified
185     #
186     carbon_copy = []
187     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
188         if copy_to.isdigit():
189             if cnf.has_key("Dinstall::BugServer"):
190                 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
191             else:
192                 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
193         elif copy_to == 'package':
194             for package in arguments:
195                 if cnf.has_key("Dinstall::PackagesServer"):
196                     carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
197                 if cnf.has_key("Dinstall::TrackingServer"):
198                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
199         elif '@' in copy_to:
200             carbon_copy.append(copy_to)
201         else:
202             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
203
204     if Options["Binary"]:
205         field = "b.package"
206     else:
207         field = "s.source"
208     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
209
210     (con_suites, con_architectures, con_components, check_source) = \
211                  utils.parse_args(Options)
212
213     # Additional suite checks
214     suite_ids_list = []
215     whitelists = []
216     suites = utils.split_args(Options["Suite"])
217     suites_list = utils.join_with_commas_and(suites)
218     if not Options["No-Action"]:
219         for suite in suites:
220             s = get_suite(suite, session=session)
221             if s is not None:
222                 suite_ids_list.append(s.suite_id)
223                 whitelists.append(s.mail_whitelist)
224             if suite in ("oldstable", "stable"):
225                 print "**WARNING** About to remove from the (old)stable suite!"
226                 print "This should only be done just prior to a (point) release and not at"
227                 print "any other time."
228                 game_over()
229             elif suite == "testing":
230                 print "**WARNING About to remove from the testing suite!"
231                 print "There's no need to do this normally as removals from unstable will"
232                 print "propogate to testing automagically."
233                 game_over()
234
235     # Additional architecture checks
236     if Options["Architecture"] and check_source:
237         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
238
239     # Don't do dependency checks on multiple suites
240     if Options["Rdep-Check"] and len(suites) > 1:
241         utils.fubar("Reverse dependency check on multiple suites is not implemented.")
242
243     to_remove = []
244     maintainers = {}
245
246     # We have 3 modes of package selection: binary, source-only, binary-only
247     # and source+binary.
248
249     # XXX: TODO: This all needs converting to use placeholders or the object
250     #            API. It's an SQL injection dream at the moment
251
252     if Options["Binary"]:
253         # Removal by binary package name
254         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))
255         to_remove.extend(q)
256     else:
257         # Source-only
258         if not Options["Binary-Only"]:
259             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))
260             to_remove.extend(q)
261         if not Options["Source-Only"]:
262             # Source + Binary
263             q = session.execute("""
264                     SELECT b.package, b.version, a.arch_string, b.id, b.maintainer
265                     FROM binaries b
266                          JOIN bin_associations ba ON b.id = ba.bin
267                          JOIN architecture a ON b.architecture = a.id
268                          JOIN suite su ON ba.suite = su.id
269                          JOIN archive ON archive.id = su.archive_id
270                          JOIN files_archive_map af ON b.file = af.file_id AND af.archive_id = archive.id
271                          JOIN component c ON af.component_id = c.id
272                          JOIN source s ON b.source = s.id
273                          JOIN src_associations sa ON s.id = sa.source AND sa.suite = su.id
274                     WHERE TRUE %s %s %s %s""" % (con_packages, con_suites, con_components, con_architectures))
275             to_remove.extend(q)
276
277     if not to_remove:
278         print "Nothing to do."
279         sys.exit(0)
280
281     # If we don't have a reason; spawn an editor so the user can add one
282     # Write the rejection email out as the <foo>.reason file
283     if not Options["Reason"] and not Options["No-Action"]:
284         (fd, temp_filename) = utils.temp_filename()
285         editor = os.environ.get("EDITOR","vi")
286         result = os.system("%s %s" % (editor, temp_filename))
287         if result != 0:
288             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
289         temp_file = utils.open_file(temp_filename)
290         for line in temp_file.readlines():
291             Options["Reason"] += line
292         temp_file.close()
293         os.unlink(temp_filename)
294
295     # Generate the summary of what's to be removed
296     d = {}
297     for i in to_remove:
298         package = i[0]
299         version = i[1]
300         architecture = i[2]
301         maintainer = i[4]
302         maintainers[maintainer] = ""
303         if not d.has_key(package):
304             d[package] = {}
305         if not d[package].has_key(version):
306             d[package][version] = []
307         if architecture not in d[package][version]:
308             d[package][version].append(architecture)
309
310     maintainer_list = []
311     for maintainer_id in maintainers.keys():
312         maintainer_list.append(get_maintainer(maintainer_id).name)
313     summary = ""
314     removals = d.keys()
315     removals.sort()
316     for package in removals:
317         versions = d[package].keys()
318         versions.sort(apt_pkg.version_compare)
319         for version in versions:
320             d[package][version].sort(utils.arch_compare_sw)
321             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
322     print "Will remove the following packages from %s:" % (suites_list)
323     print
324     print summary
325     print "Maintainer: %s" % ", ".join(maintainer_list)
326     if Options["Done"]:
327         print "Will also close bugs: "+Options["Done"]
328     if carbon_copy:
329         print "Will also send CCs to: " + ", ".join(carbon_copy)
330     if Options["Do-Close"]:
331         print "Will also close associated bug reports."
332     print
333     print "------------------- Reason -------------------"
334     print Options["Reason"]
335     print "----------------------------------------------"
336     print
337
338     if Options["Rdep-Check"]:
339         arches = utils.split_args(Options["Architecture"])
340         reverse_depends_check(removals, suites[0], arches, session)
341
342     # If -n/--no-action, drop out here
343     if Options["No-Action"]:
344         sys.exit(0)
345
346     print "Going to remove the packages now."
347     game_over()
348
349     # Do the actual deletion
350     print "Deleting...",
351     sys.stdout.flush()
352
353     try:
354         bugs = utils.split_args(Options["Done"])
355         remove(session, Options["Reason"], suites, to_remove,
356                partial=Options["Partial"], components=utils.split_args(Options["Component"]),
357                done_bugs=bugs, carbon_copy=carbon_copy, close_related_bugs=Options["Do-Close"]
358                )
359     except ValueError as ex:
360         utils.fubar(ex.message)
361     else:
362         print "done."
363
364 #######################################################################################
365
366 if __name__ == '__main__':
367     main()