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>
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.
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.
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
21 ################################################################################
23 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
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!"
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.
39 # http://slashdot.org/comments.pl?sid=26697&cid=2883271
41 ################################################################################
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.regexes import re_strip_source_version, re_bin_only_nmu
55 import debianbts as bts
57 ################################################################################
61 ################################################################################
63 def usage (exit_code=0):
64 print """Usage: dak rm [OPTIONS] PACKAGE[...]
65 Remove PACKAGE(s) from suite(s).
67 -a, --architecture=ARCH only act on this architecture
68 -b, --binary remove binaries only
69 -c, --component=COMPONENT act on this component
70 -C, --carbon-copy=EMAIL send a CC of removal message to EMAIL
71 -d, --done=BUG# send removal message as closure to bug#
72 -D, --do-close also close all bugs associated to that package
73 -h, --help show this help and exit
74 -m, --reason=MSG reason for removal
75 -n, --no-action don't do anything
76 -p, --partial don't affect override files
77 -R, --rdep-check check reverse dependencies
78 -s, --suite=SUITE act on this suite
79 -S, --source-only remove source only
81 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
82 --architecture=amd64,i386"""
86 ################################################################################
88 # "Hudson: What that's great, that's just fucking great man, now what
89 # the fuck are we supposed to do? We're in some real pretty shit now
90 # man...That's it man, game over man, game over, man! Game over! What
91 # the fuck are we gonna do now? What are we gonna do?"
94 answer = utils.our_raw_input("Continue (y/N)? ").lower()
99 ################################################################################
101 def reverse_depends_check(removals, suite, arches=None, session=None):
102 print "Checking reverse dependencies..."
103 if utils.check_reverse_depends(removals, suite, arches, session):
104 print "Dependency problem found."
105 if not Options["No-Action"]:
108 print "No dependency problem found."
111 ################################################################################
118 Arguments = [('h',"help","Rm::Options::Help"),
119 ('a',"architecture","Rm::Options::Architecture", "HasArg"),
120 ('b',"binary", "Rm::Options::Binary-Only"),
121 ('c',"component", "Rm::Options::Component", "HasArg"),
122 ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
123 ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
124 ('D',"do-close","Rm::Options::Do-Close"),
125 ('R',"rdep-check", "Rm::Options::Rdep-Check"),
126 ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
127 ('n',"no-action","Rm::Options::No-Action"),
128 ('p',"partial", "Rm::Options::Partial"),
129 ('s',"suite","Rm::Options::Suite", "HasArg"),
130 ('S',"source-only", "Rm::Options::Source-Only"),
133 for i in [ "architecture", "binary-only", "carbon-copy", "component",
134 "done", "help", "no-action", "partial", "rdep-check", "reason",
135 "source-only", "Do-Close" ]:
136 if not cnf.has_key("Rm::Options::%s" % (i)):
137 cnf["Rm::Options::%s" % (i)] = ""
138 if not cnf.has_key("Rm::Options::Suite"):
139 cnf["Rm::Options::Suite"] = "unstable"
141 arguments = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
142 Options = cnf.subtree("Rm::Options")
147 session = DBConn().session()
149 # Sanity check options
151 utils.fubar("need at least one package name as an argument.")
152 if Options["Architecture"] and Options["Source-Only"]:
153 utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
154 if Options["Binary-Only"] and Options["Source-Only"]:
155 utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
156 if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
157 utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
158 if Options["Architecture"] and not Options["Partial"]:
159 utils.warn("-a/--architecture implies -p/--partial.")
160 Options["Partial"] = "true"
161 if Options["Do-Close"] and not Options["Done"]:
163 if Options["Do-Close"] and Options["Binary-Only"]:
165 if Options["Do-Close"] and Options["Source-Only"]:
167 if Options["Do-Close"] and Options["Suite"] != 'unstable':
170 # Force the admin to tell someone if we're not doing a 'dak
171 # cruft-report' inspired removal (or closing a bug, which counts
172 # as telling someone).
173 if not Options["No-Action"] and not Options["Carbon-Copy"] \
174 and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
175 utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
177 # Process -C/--carbon-copy
179 # Accept 3 types of arguments (space separated):
180 # 1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
181 # 2) the keyword 'package' - cc's $package@packages.debian.org for every argument
182 # 3) contains a '@' - assumed to be an email address, used unmofidied
185 for copy_to in utils.split_args(Options.get("Carbon-Copy")):
186 if copy_to.isdigit():
187 if cnf.has_key("Dinstall::BugServer"):
188 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
190 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
191 elif copy_to == 'package':
192 for package in arguments:
193 if cnf.has_key("Dinstall::PackagesServer"):
194 carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
195 if cnf.has_key("Dinstall::TrackingServer"):
196 carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
198 carbon_copy.append(copy_to)
200 utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
202 if Options["Binary-Only"]:
206 con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
208 (con_suites, con_architectures, con_components, check_source) = \
209 utils.parse_args(Options)
211 # Additional suite checks
214 suites = utils.split_args(Options["Suite"])
215 suites_list = utils.join_with_commas_and(suites)
216 if not Options["No-Action"]:
218 s = get_suite(suite, session=session)
220 suite_ids_list.append(s.suite_id)
221 whitelists.append(s.mail_whitelist)
222 if suite in ("oldstable", "stable"):
223 print "**WARNING** About to remove from the (old)stable suite!"
224 print "This should only be done just prior to a (point) release and not at"
225 print "any other time."
227 elif suite == "testing":
228 print "**WARNING About to remove from the testing suite!"
229 print "There's no need to do this normally as removals from unstable will"
230 print "propogate to testing automagically."
233 # Additional architecture checks
234 if Options["Architecture"] and check_source:
235 utils.warn("'source' in -a/--argument makes no sense and is ignored.")
237 # Additional component processing
238 over_con_components = con_components.replace("c.id", "component")
240 # Don't do dependency checks on multiple suites
241 if Options["Rdep-Check"] and len(suites) > 1:
242 utils.fubar("Reverse dependency check on multiple suites is not implemented.")
249 # We have 3 modes of package selection: binary-only, source-only
250 # and source+binary. The first two are trivial and obvious; the
251 # latter is a nasty mess, but very nice from a UI perspective so
252 # we try to support it.
254 # XXX: TODO: This all needs converting to use placeholders or the object
255 # API. It's an SQL injection dream at the moment
257 if Options["Binary-Only"]:
259 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))
260 for i in q.fetchall():
265 q = session.execute("SELECT archive.path || '/pool/' || c.name || '/', f.filename, 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))
266 for i in q.fetchall():
267 source_packages[i[2]] = i[:2]
268 to_remove.append(i[2:])
269 if not Options["Source-Only"]:
272 # First get a list of binary package names we suspect are linked to the source
273 q = session.execute("SELECT DISTINCT b.package FROM binaries b, source s, src_associations sa, suite su, archive, files f, files_archive_map af, component c WHERE b.source = s.id AND sa.source = s.id AND sa.suite = su.id AND su.archive_id = archive.id AND s.file = f.id AND f.id = af.file_id AND af.archive_id = su.archive_id AND af.component_id = c.id %s %s %s" % (con_packages, con_suites, con_components))
274 for i in q.fetchall():
275 binary_packages[i[0]] = ""
276 # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
277 for i in source_packages.keys():
278 filename = "/".join(source_packages[i])
280 dsc = utils.parse_changes(filename, dsc_file=1)
281 except CantOpenError:
282 utils.warn("couldn't open '%s'." % (filename))
284 for package in dsc.get("binary").split(','):
285 package = package.strip()
286 binary_packages[package] = ""
287 # Then for each binary package: find any version in
288 # unstable, check the Source: field in the deb matches our
289 # source package and if so add it to the list of packages
291 for package in binary_packages.keys():
292 q = session.execute("SELECT archive.path || '/pool/' || c.name || '/', f.filename, b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, archive, files f, files_archive_map af, component c WHERE ba.bin = b.id AND ba.suite = su.id AND archive.id = su.archive_id AND b.architecture = a.id AND b.file = f.id AND f.id = af.file_id AND af.archive_id = su.archive_id AND af.component_id = c.id %s %s %s AND b.package = '%s'" % (con_suites, con_components, con_architectures, package))
293 for i in q.fetchall():
294 filename = "/".join(i[:2])
295 control = apt_pkg.TagSection(utils.deb_extract_control(utils.open_file(filename)))
296 source = control.find("Source", control.find("Package"))
297 source = re_strip_source_version.sub('', source)
298 if source_packages.has_key(source):
299 to_remove.append(i[2:])
303 print "Nothing to do."
306 # If we don't have a reason; spawn an editor so the user can add one
307 # Write the rejection email out as the <foo>.reason file
308 if not Options["Reason"] and not Options["No-Action"]:
309 (fd, temp_filename) = utils.temp_filename()
310 editor = os.environ.get("EDITOR","vi")
311 result = os.system("%s %s" % (editor, temp_filename))
313 utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
314 temp_file = utils.open_file(temp_filename)
315 for line in temp_file.readlines():
316 Options["Reason"] += line
318 os.unlink(temp_filename)
320 # Generate the summary of what's to be removed
327 maintainers[maintainer] = ""
328 if not d.has_key(package):
330 if not d[package].has_key(version):
331 d[package][version] = []
332 if architecture not in d[package][version]:
333 d[package][version].append(architecture)
336 for maintainer_id in maintainers.keys():
337 maintainer_list.append(get_maintainer(maintainer_id).name)
342 for package in removals:
343 versions = d[package].keys()
344 versions.sort(apt_pkg.version_compare)
345 for version in versions:
346 d[package][version].sort(utils.arch_compare_sw)
347 summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
348 print "Will remove the following packages from %s:" % (suites_list)
351 print "Maintainer: %s" % ", ".join(maintainer_list)
353 print "Will also close bugs: "+Options["Done"]
355 print "Will also send CCs to: " + ", ".join(carbon_copy)
356 if Options["Do-Close"]:
357 print "Will also close associated bug reports."
359 print "------------------- Reason -------------------"
360 print Options["Reason"]
361 print "----------------------------------------------"
364 if Options["Rdep-Check"]:
365 arches = utils.split_args(Options["Architecture"])
366 reverse_depends_check(removals, suites[0], arches, session)
368 # If -n/--no-action, drop out here
369 if Options["No-Action"]:
372 print "Going to remove the packages now."
375 whoami = utils.whoami()
376 date = commands.getoutput('date -R')
378 # Log first; if it all falls apart I want a record that we at least tried.
379 logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
380 logfile.write("=========================================================================\n")
381 logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
382 logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
384 logfile.write("Closed bugs: %s\n" % (Options["Done"]))
385 logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
386 logfile.write("----------------------------------------------\n")
388 # Do the same in rfc822 format
389 logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
390 logfile822.write("Date: %s\n" % date)
391 logfile822.write("Ftpmaster: %s\n" % whoami)
392 logfile822.write("Suite: %s\n" % suites_list)
395 for package in summary.split("\n"):
396 for row in package.split("\n"):
397 element = row.split("|")
398 if len(element) == 3:
399 if element[2].find("source") > 0:
400 sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
401 element[2] = sub("source\s?,?", "", element[2]).strip(" ")
403 binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
405 logfile822.write("Sources:\n")
406 for source in sources:
407 logfile822.write(" %s\n" % source)
409 logfile822.write("Binaries:\n")
410 for binary in binaries:
411 logfile822.write(" %s\n" % binary)
412 logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
414 logfile822.write("Bug: %s\n" % Options["Done"])
416 dsc_type_id = get_override_type('dsc', session).overridetype_id
417 deb_type_id = get_override_type('deb', session).overridetype_id
419 # Do the actual deletion
427 for suite_id in suite_ids_list:
428 if architecture == "source":
429 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
430 {'packageid': package_id, 'suiteid': suite_id})
431 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
433 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
434 {'packageid': package_id, 'suiteid': suite_id})
435 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
436 # Delete from the override file
437 if not Options["Partial"]:
438 if architecture == "source":
439 type_id = dsc_type_id
441 type_id = deb_type_id
442 # TODO: Again, fix this properly to remove the remaining non-bind argument
443 session.execute("DELETE FROM override WHERE package = :package AND type = :typeid AND suite = :suiteid %s" % (over_con_components), {'package': package, 'typeid': type_id, 'suiteid': suite_id})
447 # If we don't have a Bug server configured, we're done
448 if not cnf.has_key("Dinstall::BugServer"):
449 if Options["Done"] or Options["Do-Close"]:
450 print "Cannot send mail to BugServer as Dinstall::BugServer is not configured"
452 logfile.write("=========================================================================\n")
455 logfile822.write("\n")
460 # read common subst variables for all bug closure mails
462 Subst_common["__RM_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
463 Subst_common["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
464 Subst_common["__CC__"] = "X-DAK: dak rm"
466 Subst_common["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
467 Subst_common["__SUITE_LIST__"] = suites_list
468 Subst_common["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
469 Subst_common["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
470 Subst_common["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
471 Subst_common["__WHOAMI__"] = whoami
473 # Send the bug closing messages
475 Subst_close_rm = Subst_common
477 if cnf.find("Dinstall::Bcc") != "":
478 bcc.append(cnf["Dinstall::Bcc"])
479 if cnf.find("Rm::Bcc") != "":
480 bcc.append(cnf["Rm::Bcc"])
482 Subst_close_rm["__BCC__"] = "Bcc: " + ", ".join(bcc)
484 Subst_close_rm["__BCC__"] = "X-Filler: 42"
485 summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
486 summarymail += "----------------------------------------------\n"
487 Subst_close_rm["__SUMMARY__"] = summarymail
489 whereami = utils.where_am_i()
490 Archive = get_archive(whereami, session)
492 utils.warn("Cannot find archive %s. Setting blank values for origin" % whereami)
493 Subst_close_rm["__PRIMARY_MIRROR__"] = ""
495 Subst_close_rm["__PRIMARY_MIRROR__"] = Archive.primary_mirror
497 for bug in utils.split_args(Options["Done"]):
498 Subst_close_rm["__BUG_NUMBER__"] = bug
499 if Options["Do-Close"]:
500 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close-with-related")
502 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close")
503 utils.send_mail(mail_message, whitelists=whitelists)
505 # close associated bug reports
506 if Options["Do-Close"]:
507 Subst_close_other = Subst_common
509 wnpp = utils.parse_wnpp_bug_file()
510 versions = list(set([re_bin_only_nmu.sub('', v) for v in versions]))
511 if len(versions) == 1:
512 Subst_close_other["__VERSION__"] = versions[0]
514 utils.fubar("Closing bugs with multiple package versions is not supported. Do it yourself.")
516 Subst_close_other["__BCC__"] = "Bcc: " + ", ".join(bcc)
518 Subst_close_other["__BCC__"] = "X-Filler: 42"
519 # at this point, I just assume, that the first closed bug gives
520 # some useful information on why the package got removed
521 Subst_close_other["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
522 if len(sources) == 1:
523 source_pkg = source.split("_", 1)[0]
525 utils.fubar("Closing bugs for multiple source packages is not supported. Do it yourself.")
526 Subst_close_other["__BUG_NUMBER_ALSO__"] = ""
527 Subst_close_other["__SOURCE__"] = source_pkg
528 other_bugs = bts.get_bugs('src', source_pkg, 'status', 'open', 'status', 'forwarded')
530 logfile.write("Also closing bug(s):")
531 logfile822.write("Also-Bugs:")
532 for bug in other_bugs:
533 Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
534 logfile.write(" " + str(bug))
535 logfile822.write(" " + str(bug))
537 logfile822.write("\n")
538 if source_pkg in wnpp.keys():
539 logfile.write("Also closing WNPP bug(s):")
540 logfile822.write("Also-WNPP:")
541 for bug in wnpp[source_pkg]:
542 # the wnpp-rm file we parse also contains our removal
543 # bugs, filtering that out
544 if bug != Subst_close_other["__BUG_NUMBER__"]:
545 Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
546 logfile.write(" " + str(bug))
547 logfile822.write(" " + str(bug))
549 logfile822.write("\n")
551 mail_message = utils.TemplateSubst(Subst_close_other,cnf["Dir::Templates"]+"/rm.bug-close-related")
552 if Subst_close_other["__BUG_NUMBER_ALSO__"]:
553 utils.send_mail(mail_message)
556 logfile.write("=========================================================================\n")
559 logfile822.write("\n")
562 #######################################################################################
564 if __name__ == '__main__':