3 """ General purpose package removal tool for ftpmaster """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 James Troup <james@nocrew.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 ################################################################################
22 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
24 # o Ask again -> No respond. Darren coder supreme.
25 # o OpenBSD decide to make changes, but only in OpenBSD source
26 # tree. Darren hears, gets angry! Decides: "LICENSE NO ALLOW!"
28 # o OpenBSD team decide to switch to different packet filter under BSD
29 # license. Because Project Goal: Every user should be able to make
30 # changes to source tree. IPF license bad!!
31 # o Darren try get back: says, NetBSD, FreeBSD allowed! MUAHAHAHAH!!!
32 # o Theo say: no care, pf much better than ipf!
33 # o Darren changes mind: changes license. But OpenBSD will not change
34 # back to ipf. Darren even much more bitter.
35 # o Darren so bitterbitter. Decides: I'LL GET BACK BY FORKING OPENBSD AND
36 # RELEASING MY OWN VERSION. HEHEHEHEHE.
38 # http://slashdot.org/comments.pl?sid=26697&cid=2883271
40 ################################################################################
49 from daklib.config import Config
50 from daklib.dbconn import *
51 from daklib import utils
52 from daklib.dak_exceptions import *
53 from daklib.regexes import re_strip_source_version, re_build_dep_arch
54 import debianbts as bts
56 ################################################################################
60 ################################################################################
62 def usage (exit_code=0):
63 print """Usage: dak rm [OPTIONS] PACKAGE[...]
64 Remove PACKAGE(s) from suite(s).
66 -a, --architecture=ARCH only act on this architecture
67 -b, --binary remove binaries only
68 -c, --component=COMPONENT act on this component
69 -C, --carbon-copy=EMAIL send a CC of removal message to EMAIL
70 -d, --done=BUG# send removal message as closure to bug#
71 -D, --do-close also close all bugs associated to that package
72 -h, --help show this help and exit
73 -m, --reason=MSG reason for removal
74 -n, --no-action don't do anything
75 -p, --partial don't affect override files
76 -R, --rdep-check check reverse dependencies
77 -s, --suite=SUITE act on this suite
78 -S, --source-only remove source only
80 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
81 --architecture=amd64,i386"""
85 ################################################################################
87 # "Hudson: What that's great, that's just fucking great man, now what
88 # the fuck are we supposed to do? We're in some real pretty shit now
89 # man...That's it man, game over man, game over, man! Game over! What
90 # the fuck are we gonna do now? What are we gonna do?"
93 answer = utils.our_raw_input("Continue (y/N)? ").lower()
98 ################################################################################
100 def reverse_depends_check(removals, suites, arches=None):
103 print "Checking reverse dependencies..."
104 components = cnf.ValueList("Suite::%s::Components" % suites[0])
109 all_arches = set(arches)
111 all_arches = set([x.arch_string for x in get_suite_architectures(suites[0])])
112 all_arches -= set(["source", "all"])
113 for architecture in all_arches:
116 virtual_packages = {}
117 for component in components:
118 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (cnf["Dir::Root"], suites[0], component, architecture)
119 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
120 (fd, temp_filename) = utils.temp_filename()
121 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
123 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
124 # Also check for udebs
125 filename = "%s/dists/%s/%s/debian-installer/binary-%s/Packages.gz" % (cnf["Dir::Root"], suites[0], component, architecture)
126 if os.path.exists(filename):
127 (result, output) = commands.getstatusoutput("gunzip -c %s >> %s" % (filename, temp_filename))
129 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
130 packages = utils.open_file(temp_filename)
131 Packages = apt_pkg.ParseTagFile(packages)
132 while Packages.Step():
133 package = Packages.Section.Find("Package")
134 source = Packages.Section.Find("Source")
138 source = source.split(' ', 1)[0]
139 sources[package] = source
140 depends = Packages.Section.Find("Depends")
142 deps[package] = depends
143 provides = Packages.Section.Find("Provides")
144 # Maintain a counter for each virtual package. If a
145 # Provides: exists, set the counter to 0 and count all
146 # provides by a package not in the list for removal.
147 # If the counter stays 0 at the end, we know that only
148 # the to-be-removed packages provided this virtual
151 for virtual_pkg in provides.split(","):
152 virtual_pkg = virtual_pkg.strip()
153 if virtual_pkg == package: continue
154 if not virtual_packages.has_key(virtual_pkg):
155 virtual_packages[virtual_pkg] = 0
156 if package not in removals:
157 virtual_packages[virtual_pkg] += 1
158 p2c[package] = component
160 os.unlink(temp_filename)
162 # If a virtual package is only provided by the to-be-removed
163 # packages, treat the virtual package as to-be-removed too.
164 for virtual_pkg in virtual_packages.keys():
165 if virtual_packages[virtual_pkg] == 0:
166 removals.append(virtual_pkg)
168 # Check binary dependencies (Depends)
169 for package in deps.keys():
170 if package in removals: continue
173 parsed_dep += apt_pkg.ParseDepends(deps[package])
174 except ValueError, e:
175 print "Error for package %s: %s" % (package, e)
176 for dep in parsed_dep:
177 # Check for partial breakage. If a package has a ORed
178 # dependency, there is only a dependency problem if all
179 # packages in the ORed depends will be removed.
181 for dep_package, _, _ in dep:
182 if dep_package in removals:
184 if unsat == len(dep):
185 component = p2c[package]
186 source = sources[package]
187 if component != "main":
188 source = "%s/%s" % (source, component)
189 all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
193 print "# Broken Depends:"
194 for source, bindict in sorted(all_broken.items()):
196 for binary, arches in sorted(bindict.items()):
197 if arches == all_arches:
200 lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
201 print '%s: %s' % (source, lines[0])
202 for line in lines[1:]:
203 print ' ' * (len(source) + 2) + line
206 # Check source dependencies (Build-Depends and Build-Depends-Indep)
208 for component in components:
209 filename = "%s/dists/%s/%s/source/Sources.gz" % (cnf["Dir::Root"], suites[0], component)
210 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
211 (fd, temp_filename) = utils.temp_filename()
212 result, output = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
214 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
216 sources = utils.open_file(temp_filename, "r")
217 Sources = apt_pkg.ParseTagFile(sources)
218 while Sources.Step():
219 source = Sources.Section.Find("Package")
220 if source in removals: continue
222 for build_dep_type in ["Build-Depends", "Build-Depends-Indep"]:
223 build_dep = Sources.Section.get(build_dep_type)
225 # Remove [arch] information since we want to see breakage on all arches
226 build_dep = re_build_dep_arch.sub("", build_dep)
228 parsed_dep += apt_pkg.ParseDepends(build_dep)
229 except ValueError, e:
230 print "Error for source %s: %s" % (source, e)
231 for dep in parsed_dep:
233 for dep_package, _, _ in dep:
234 if dep_package in removals:
236 if unsat == len(dep):
237 if component != "main":
238 source = "%s/%s" % (source, component)
239 all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
242 os.unlink(temp_filename)
245 print "# Broken Build-Depends:"
246 for source, bdeps in sorted(all_broken.items()):
247 bdeps = sorted(bdeps)
248 print '%s: %s' % (source, bdeps[0])
249 for bdep in bdeps[1:]:
250 print ' ' * (len(source) + 2) + bdep
254 print "Dependency problem found."
255 if not Options["No-Action"]:
258 print "No dependency problem found."
261 ################################################################################
268 Arguments = [('h',"help","Rm::Options::Help"),
269 ('a',"architecture","Rm::Options::Architecture", "HasArg"),
270 ('b',"binary", "Rm::Options::Binary-Only"),
271 ('c',"component", "Rm::Options::Component", "HasArg"),
272 ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
273 ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
274 ('D',"do-close","Rm::Options::Do-Close"),
275 ('R',"rdep-check", "Rm::Options::Rdep-Check"),
276 ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
277 ('n',"no-action","Rm::Options::No-Action"),
278 ('p',"partial", "Rm::Options::Partial"),
279 ('s',"suite","Rm::Options::Suite", "HasArg"),
280 ('S',"source-only", "Rm::Options::Source-Only"),
283 for i in [ "architecture", "binary-only", "carbon-copy", "component",
284 "done", "help", "no-action", "partial", "rdep-check", "reason",
286 if not cnf.has_key("Rm::Options::%s" % (i)):
287 cnf["Rm::Options::%s" % (i)] = ""
288 if not cnf.has_key("Rm::Options::Suite"):
289 cnf["Rm::Options::Suite"] = "unstable"
291 arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
292 Options = cnf.SubTree("Rm::Options")
297 session = DBConn().session()
299 # Sanity check options
301 utils.fubar("need at least one package name as an argument.")
302 if Options["Architecture"] and Options["Source-Only"]:
303 utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
304 if Options["Binary-Only"] and Options["Source-Only"]:
305 utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
306 if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
307 utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
308 if Options["Architecture"] and not Options["Partial"]:
309 utils.warn("-a/--architecture implies -p/--partial.")
310 Options["Partial"] = "true"
311 if Options["Do-Close"] and not Options["Done"]:
313 if Options["Do-Close"] and Options["Binary-Only"]:
315 if Options["Do-Close"] and Options["Source-Only"]:
317 if Options["Do-Close"] and Options["Suite"] != 'unstable':
320 # Force the admin to tell someone if we're not doing a 'dak
321 # cruft-report' inspired removal (or closing a bug, which counts
322 # as telling someone).
323 if not Options["No-Action"] and not Options["Carbon-Copy"] \
324 and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
325 utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
327 # Process -C/--carbon-copy
329 # Accept 3 types of arguments (space separated):
330 # 1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
331 # 2) the keyword 'package' - cc's $package@packages.debian.org for every argument
332 # 3) contains a '@' - assumed to be an email address, used unmofidied
335 for copy_to in utils.split_args(Options.get("Carbon-Copy")):
336 if copy_to.isdigit():
337 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
338 elif copy_to == 'package':
339 for package in arguments:
340 carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
341 if cnf.has_key("Dinstall::TrackingServer"):
342 carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
344 carbon_copy.append(copy_to)
346 utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
348 if Options["Binary-Only"]:
352 con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
354 (con_suites, con_architectures, con_components, check_source) = \
355 utils.parse_args(Options)
357 # Additional suite checks
359 suites = utils.split_args(Options["Suite"])
360 suites_list = utils.join_with_commas_and(suites)
361 if not Options["No-Action"]:
363 s = get_suite(suite, session=session)
365 suite_ids_list.append(s.suite_id)
366 if suite == "stable":
367 print "**WARNING** About to remove from the stable suite!"
368 print "This should only be done just prior to a (point) release and not at"
369 print "any other time."
371 elif suite == "testing":
372 print "**WARNING About to remove from the testing suite!"
373 print "There's no need to do this normally as removals from unstable will"
374 print "propogate to testing automagically."
377 # Additional architecture checks
378 if Options["Architecture"] and check_source:
379 utils.warn("'source' in -a/--argument makes no sense and is ignored.")
381 # Additional component processing
382 over_con_components = con_components.replace("c.id", "component")
389 # We have 3 modes of package selection: binary-only, source-only
390 # and source+binary. The first two are trivial and obvious; the
391 # latter is a nasty mess, but very nice from a UI perspective so
392 # we try to support it.
394 # XXX: TODO: This all needs converting to use placeholders or the object
395 # API. It's an SQL injection dream at the moment
397 if Options["Binary-Only"]:
399 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, location l, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s %s" % (con_packages, con_suites, con_components, con_architectures))
400 for i in q.fetchall():
405 q = session.execute("SELECT l.path, f.filename, s.source, s.version, 'source', s.id, s.maintainer FROM source s, src_associations sa, suite su, files f, location l, component c WHERE sa.source = s.id AND sa.suite = su.id AND s.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s" % (con_packages, con_suites, con_components))
406 for i in q.fetchall():
407 source_packages[i[2]] = i[:2]
408 to_remove.append(i[2:])
409 if not Options["Source-Only"]:
412 # First get a list of binary package names we suspect are linked to the source
413 q = session.execute("SELECT DISTINCT b.package FROM binaries b, source s, src_associations sa, suite su, files f, location l, component c WHERE b.source = s.id AND sa.source = s.id AND sa.suite = su.id AND s.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s" % (con_packages, con_suites, con_components))
414 for i in q.fetchall():
415 binary_packages[i[0]] = ""
416 # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
417 for i in source_packages.keys():
418 filename = "/".join(source_packages[i])
420 dsc = utils.parse_changes(filename, dsc_file=1)
421 except CantOpenError:
422 utils.warn("couldn't open '%s'." % (filename))
424 for package in dsc.get("binary").split(','):
425 package = package.strip()
426 binary_packages[package] = ""
427 # Then for each binary package: find any version in
428 # unstable, check the Source: field in the deb matches our
429 # source package and if so add it to the list of packages
431 for package in binary_packages.keys():
432 q = session.execute("SELECT l.path, f.filename, b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, files f, location l, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s AND b.package = '%s'" % (con_suites, con_components, con_architectures, package))
433 for i in q.fetchall():
434 filename = "/".join(i[:2])
435 control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
436 source = control.Find("Source", control.Find("Package"))
437 source = re_strip_source_version.sub('', source)
438 if source_packages.has_key(source):
439 to_remove.append(i[2:])
443 print "Nothing to do."
446 # If we don't have a reason; spawn an editor so the user can add one
447 # Write the rejection email out as the <foo>.reason file
448 if not Options["Reason"] and not Options["No-Action"]:
449 (fd, temp_filename) = utils.temp_filename()
450 editor = os.environ.get("EDITOR","vi")
451 result = os.system("%s %s" % (editor, temp_filename))
453 utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
454 temp_file = utils.open_file(temp_filename)
455 for line in temp_file.readlines():
456 Options["Reason"] += line
458 os.unlink(temp_filename)
460 # Generate the summary of what's to be removed
467 maintainers[maintainer] = ""
468 if not d.has_key(package):
470 if not d[package].has_key(version):
471 d[package][version] = []
472 if architecture not in d[package][version]:
473 d[package][version].append(architecture)
476 for maintainer_id in maintainers.keys():
477 maintainer_list.append(get_maintainer(maintainer_id).name)
481 for package in removals:
482 versions = d[package].keys()
483 versions.sort(apt_pkg.VersionCompare)
484 for version in versions:
485 d[package][version].sort(utils.arch_compare_sw)
486 summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
487 print "Will remove the following packages from %s:" % (suites_list)
490 print "Maintainer: %s" % ", ".join(maintainer_list)
492 print "Will also close bugs: "+Options["Done"]
494 print "Will also send CCs to: " + ", ".join(carbon_copy)
496 print "------------------- Reason -------------------"
497 print Options["Reason"]
498 print "----------------------------------------------"
501 if Options["Rdep-Check"]:
502 arches = utils.split_args(Options["Architecture"])
503 reverse_depends_check(removals, suites, arches)
505 # If -n/--no-action, drop out here
506 if Options["No-Action"]:
509 print "Going to remove the packages now."
512 whoami = utils.whoami()
513 date = commands.getoutput('date -R')
515 # Log first; if it all falls apart I want a record that we at least tried.
516 logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
517 logfile.write("=========================================================================\n")
518 logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
519 logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
521 logfile.write("Closed bugs: %s\n" % (Options["Done"]))
522 logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
523 logfile.write("----------------------------------------------\n")
524 logfile.write("=========================================================================\n")
527 # Do the same in rfc822 format
528 logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
529 logfile822.write("Date: %s\n" % date)
530 logfile822.write("Ftpmaster: %s\n" % whoami)
531 logfile822.write("Suite: %s\n" % suites_list)
534 for package in summary.split("\n"):
535 for row in package.split("\n"):
536 element = row.split("|")
537 if len(element) == 3:
538 if element[2].find("source") > 0:
539 sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
540 element[2] = sub("source\s?,?", "", element[2]).strip(" ")
542 binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
544 logfile822.write("Sources:\n")
545 for source in sources:
546 logfile822.write(" %s\n" % source)
548 logfile822.write("Binaries:\n")
549 for binary in binaries:
550 logfile822.write(" %s\n" % binary)
551 logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
553 logfile822.write("Bug: %s\n" % Options["Done"])
554 logfile822.write("\n")
557 dsc_type_id = get_override_type('dsc', session).overridetype_id
558 deb_type_id = get_override_type('deb', session).overridetype_id
560 # Do the actual deletion
568 for suite_id in suite_ids_list:
569 if architecture == "source":
570 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
571 {'packageid': package_id, 'suiteid': suite_id})
572 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
574 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
575 {'packageid': package_id, 'suiteid': suite_id})
576 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
577 # Delete from the override file
578 if not Options["Partial"]:
579 if architecture == "source":
580 type_id = dsc_type_id
582 type_id = deb_type_id
583 # TODO: Again, fix this properly to remove the remaining non-bind argument
584 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})
589 Subst["__RM_ADDRESS__"] = cnf["Rm::MyEmailAddress"]
590 Subst["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
592 if cnf.Find("Dinstall::Bcc") != "":
593 bcc.append(cnf["Dinstall::Bcc"])
594 if cnf.Find("Rm::Bcc") != "":
595 bcc.append(cnf["Rm::Bcc"])
597 Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
599 Subst["__BCC__"] = "X-Filler: 42"
600 Subst["__CC__"] = "X-DAK: dak rm"
602 Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
603 Subst["__SUITE_LIST__"] = suites_list
604 Subst["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
605 Subst["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
606 Subst["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
607 Subst["__WHOAMI__"] = whoami
609 # Send the bug closing messages
611 summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
612 summarymail += "----------------------------------------------\n"
613 Subst["__SUMMARY__"] = summarymail
614 whereami = utils.where_am_i()
615 Archive = cnf.SubTree("Archive::%s" % (whereami))
616 Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"]
617 Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"]
618 for bug in utils.split_args(Options["Done"]):
619 Subst["__BUG_NUMBER__"] = bug
620 mail_message = utils.TemplateSubst(Subst,cnf["Dir::Templates"]+"/rm.bug-close")
621 utils.send_mail(mail_message)
623 # close associated bug reports
624 if Options["Do-Close"]:
625 whereami = utils.where_am_i()
626 Archive = cnf.SubTree("Archive::%s" % (whereami))
627 # at this point, I just assume, that the first closed bug gives
628 # some usefull information on why the package got removed
629 Subst["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
630 for bug in bts.get_bugs('src', package, 'status', 'open'):
631 Subst["__BUG_NUMBER_ALSO__"] += bug + "-done@" + cnf["Dinstall::BugServer"] + ","
632 mail_message = utils.TemplateSubst(Subst,cnf["Dir::Templates"]+"/rm.bug-close-related")
633 utils.send_mail(mail_message)
635 #######################################################################################
637 if __name__ == '__main__':