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
55 ################################################################################
59 ################################################################################
61 def usage (exit_code=0):
62 print """Usage: dak rm [OPTIONS] PACKAGE[...]
63 Remove PACKAGE(s) from suite(s).
65 -a, --architecture=ARCH only act on this architecture
66 -b, --binary remove binaries only
67 -c, --component=COMPONENT act on this component
68 -C, --carbon-copy=EMAIL send a CC of removal message to EMAIL
69 -d, --done=BUG# send removal message as closure to bug#
70 -h, --help show this help and exit
71 -m, --reason=MSG reason for removal
72 -n, --no-action don't do anything
73 -p, --partial don't affect override files
74 -R, --rdep-check check reverse dependencies
75 -s, --suite=SUITE act on this suite
76 -S, --source-only remove source only
78 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
79 --architecture=amd64,i386"""
83 ################################################################################
85 # "Hudson: What that's great, that's just fucking great man, now what
86 # the fuck are we supposed to do? We're in some real pretty shit now
87 # man...That's it man, game over man, game over, man! Game over! What
88 # the fuck are we gonna do now? What are we gonna do?"
91 answer = utils.our_raw_input("Continue (y/N)? ").lower()
96 ################################################################################
98 def reverse_depends_check(removals, suites, arches=None):
101 print "Checking reverse dependencies..."
102 components = cnf.ValueList("Suite::%s::Components" % suites[0])
107 all_arches = set(arches)
109 all_arches = set([x.arch_string for x in get_suite_architectures(suites[0])])
110 all_arches -= set(["source", "all"])
111 for architecture in all_arches:
114 virtual_packages = {}
115 for component in components:
116 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (cnf["Dir::Root"], suites[0], component, architecture)
117 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
118 (fd, temp_filename) = utils.temp_filename()
119 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
121 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
122 # Also check for udebs
123 filename = "%s/dists/%s/%s/debian-installer/binary-%s/Packages.gz" % (cnf["Dir::Root"], suites[0], component, architecture)
124 if os.path.exists(filename):
125 (result, output) = commands.getstatusoutput("gunzip -c %s >> %s" % (filename, temp_filename))
127 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
128 packages = utils.open_file(temp_filename)
129 Packages = apt_pkg.ParseTagFile(packages)
130 while Packages.Step():
131 package = Packages.Section.Find("Package")
132 source = Packages.Section.Find("Source")
136 source = source.split(' ', 1)[0]
137 sources[package] = source
138 depends = Packages.Section.Find("Depends")
140 deps[package] = depends
141 provides = Packages.Section.Find("Provides")
142 # Maintain a counter for each virtual package. If a
143 # Provides: exists, set the counter to 0 and count all
144 # provides by a package not in the list for removal.
145 # If the counter stays 0 at the end, we know that only
146 # the to-be-removed packages provided this virtual
149 for virtual_pkg in provides.split(","):
150 virtual_pkg = virtual_pkg.strip()
151 if virtual_pkg == package: continue
152 if not virtual_packages.has_key(virtual_pkg):
153 virtual_packages[virtual_pkg] = 0
154 if package not in removals:
155 virtual_packages[virtual_pkg] += 1
156 p2c[package] = component
158 os.unlink(temp_filename)
160 # If a virtual package is only provided by the to-be-removed
161 # packages, treat the virtual package as to-be-removed too.
162 for virtual_pkg in virtual_packages.keys():
163 if virtual_packages[virtual_pkg] == 0:
164 removals.append(virtual_pkg)
166 # Check binary dependencies (Depends)
167 for package in deps.keys():
168 if package in removals: continue
171 parsed_dep += apt_pkg.ParseDepends(deps[package])
172 except ValueError, e:
173 print "Error for package %s: %s" % (package, e)
174 for dep in parsed_dep:
175 # Check for partial breakage. If a package has a ORed
176 # dependency, there is only a dependency problem if all
177 # packages in the ORed depends will be removed.
179 for dep_package, _, _ in dep:
180 if dep_package in removals:
182 if unsat == len(dep):
183 component = p2c[package]
184 source = sources[package]
185 if component != "main":
186 source = "%s/%s" % (source, component)
187 all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
191 print "# Broken Depends:"
192 for source, bindict in sorted(all_broken.items()):
194 for binary, arches in sorted(bindict.items()):
195 if arches == all_arches:
198 lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
199 print '%s: %s' % (source, lines[0])
200 for line in lines[1:]:
201 print ' ' * (len(source) + 2) + line
204 # Check source dependencies (Build-Depends and Build-Depends-Indep)
206 for component in components:
207 filename = "%s/dists/%s/%s/source/Sources.gz" % (cnf["Dir::Root"], suites[0], component)
208 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
209 (fd, temp_filename) = utils.temp_filename()
210 result, output = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
212 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
214 sources = utils.open_file(temp_filename, "r")
215 Sources = apt_pkg.ParseTagFile(sources)
216 while Sources.Step():
217 source = Sources.Section.Find("Package")
218 if source in removals: continue
220 for build_dep_type in ["Build-Depends", "Build-Depends-Indep"]:
221 build_dep = Sources.Section.get(build_dep_type)
223 # Remove [arch] information since we want to see breakage on all arches
224 build_dep = re_build_dep_arch.sub("", build_dep)
226 parsed_dep += apt_pkg.ParseDepends(build_dep)
227 except ValueError, e:
228 print "Error for source %s: %s" % (source, e)
229 for dep in parsed_dep:
231 for dep_package, _, _ in dep:
232 if dep_package in removals:
234 if unsat == len(dep):
235 if component != "main":
236 source = "%s/%s" % (source, component)
237 all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
240 os.unlink(temp_filename)
243 print "# Broken Build-Depends:"
244 for source, bdeps in sorted(all_broken.items()):
245 bdeps = sorted(bdeps)
246 print '%s: %s' % (source, bdeps[0])
247 for bdep in bdeps[1:]:
248 print ' ' * (len(source) + 2) + bdep
252 print "Dependency problem found."
253 if not Options["No-Action"]:
256 print "No dependency problem found."
259 ################################################################################
266 Arguments = [('h',"help","Rm::Options::Help"),
267 ('a',"architecture","Rm::Options::Architecture", "HasArg"),
268 ('b',"binary", "Rm::Options::Binary-Only"),
269 ('c',"component", "Rm::Options::Component", "HasArg"),
270 ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
271 ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
272 ('R',"rdep-check", "Rm::Options::Rdep-Check"),
273 ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
274 ('n',"no-action","Rm::Options::No-Action"),
275 ('p',"partial", "Rm::Options::Partial"),
276 ('s',"suite","Rm::Options::Suite", "HasArg"),
277 ('S',"source-only", "Rm::Options::Source-Only"),
280 for i in [ "architecture", "binary-only", "carbon-copy", "component",
281 "done", "help", "no-action", "partial", "rdep-check", "reason",
283 if not cnf.has_key("Rm::Options::%s" % (i)):
284 cnf["Rm::Options::%s" % (i)] = ""
285 if not cnf.has_key("Rm::Options::Suite"):
286 cnf["Rm::Options::Suite"] = "unstable"
288 arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
289 Options = cnf.SubTree("Rm::Options")
294 session = DBConn().session()
296 # Sanity check options
298 utils.fubar("need at least one package name as an argument.")
299 if Options["Architecture"] and Options["Source-Only"]:
300 utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
301 if Options["Binary-Only"] and Options["Source-Only"]:
302 utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
303 if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
304 utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
305 if Options["Architecture"] and not Options["Partial"]:
306 utils.warn("-a/--architecture implies -p/--partial.")
307 Options["Partial"] = "true"
309 # Force the admin to tell someone if we're not doing a 'dak
310 # cruft-report' inspired removal (or closing a bug, which counts
311 # as telling someone).
312 if not Options["No-Action"] and not Options["Carbon-Copy"] \
313 and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
314 utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
316 # Process -C/--carbon-copy
318 # Accept 3 types of arguments (space separated):
319 # 1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
320 # 2) the keyword 'package' - cc's $package@packages.debian.org for every argument
321 # 3) contains a '@' - assumed to be an email address, used unmofidied
324 for copy_to in utils.split_args(Options.get("Carbon-Copy")):
325 if copy_to.isdigit():
326 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
327 elif copy_to == 'package':
328 for package in arguments:
329 carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
330 if cnf.has_key("Dinstall::TrackingServer"):
331 carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
333 carbon_copy.append(copy_to)
335 utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
337 if Options["Binary-Only"]:
341 con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
343 (con_suites, con_architectures, con_components, check_source) = \
344 utils.parse_args(Options)
346 # Additional suite checks
348 suites = utils.split_args(Options["Suite"])
349 suites_list = utils.join_with_commas_and(suites)
350 if not Options["No-Action"]:
352 s = get_suite(suite, session=session)
354 suite_ids_list.append(s.suite_id)
355 if suite == "stable":
356 print "**WARNING** About to remove from the stable suite!"
357 print "This should only be done just prior to a (point) release and not at"
358 print "any other time."
360 elif suite == "testing":
361 print "**WARNING About to remove from the testing suite!"
362 print "There's no need to do this normally as removals from unstable will"
363 print "propogate to testing automagically."
366 # Additional architecture checks
367 if Options["Architecture"] and check_source:
368 utils.warn("'source' in -a/--argument makes no sense and is ignored.")
370 # Additional component processing
371 over_con_components = con_components.replace("c.id", "component")
378 # We have 3 modes of package selection: binary-only, source-only
379 # and source+binary. The first two are trivial and obvious; the
380 # latter is a nasty mess, but very nice from a UI perspective so
381 # we try to support it.
383 # XXX: TODO: This all needs converting to use placeholders or the object
384 # API. It's an SQL injection dream at the moment
386 if Options["Binary-Only"]:
388 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))
389 for i in q.fetchall():
394 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))
395 for i in q.fetchall():
396 source_packages[i[2]] = i[:2]
397 to_remove.append(i[2:])
398 if not Options["Source-Only"]:
401 # First get a list of binary package names we suspect are linked to the source
402 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))
403 for i in q.fetchall():
404 binary_packages[i[0]] = ""
405 # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
406 for i in source_packages.keys():
407 filename = "/".join(source_packages[i])
409 dsc = utils.parse_changes(filename, dsc_file=1)
410 except CantOpenError:
411 utils.warn("couldn't open '%s'." % (filename))
413 for package in dsc.get("binary").split(','):
414 package = package.strip()
415 binary_packages[package] = ""
416 # Then for each binary package: find any version in
417 # unstable, check the Source: field in the deb matches our
418 # source package and if so add it to the list of packages
420 for package in binary_packages.keys():
421 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))
422 for i in q.fetchall():
423 filename = "/".join(i[:2])
424 control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
425 source = control.Find("Source", control.Find("Package"))
426 source = re_strip_source_version.sub('', source)
427 if source_packages.has_key(source):
428 to_remove.append(i[2:])
432 print "Nothing to do."
435 # If we don't have a reason; spawn an editor so the user can add one
436 # Write the rejection email out as the <foo>.reason file
437 if not Options["Reason"] and not Options["No-Action"]:
438 (fd, temp_filename) = utils.temp_filename()
439 editor = os.environ.get("EDITOR","vi")
440 result = os.system("%s %s" % (editor, temp_filename))
442 utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
443 temp_file = utils.open_file(temp_filename)
444 for line in temp_file.readlines():
445 Options["Reason"] += line
447 os.unlink(temp_filename)
449 # Generate the summary of what's to be removed
456 maintainers[maintainer] = ""
457 if not d.has_key(package):
459 if not d[package].has_key(version):
460 d[package][version] = []
461 if architecture not in d[package][version]:
462 d[package][version].append(architecture)
465 for maintainer_id in maintainers.keys():
466 maintainer_list.append(get_maintainer(maintainer_id).name)
470 for package in removals:
471 versions = d[package].keys()
472 versions.sort(apt_pkg.VersionCompare)
473 for version in versions:
474 d[package][version].sort(utils.arch_compare_sw)
475 summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
476 print "Will remove the following packages from %s:" % (suites_list)
479 print "Maintainer: %s" % ", ".join(maintainer_list)
481 print "Will also close bugs: "+Options["Done"]
483 print "Will also send CCs to: " + ", ".join(carbon_copy)
485 print "------------------- Reason -------------------"
486 print Options["Reason"]
487 print "----------------------------------------------"
490 if Options["Rdep-Check"]:
491 arches = utils.split_args(Options["Architecture"])
492 reverse_depends_check(removals, suites, arches)
494 # If -n/--no-action, drop out here
495 if Options["No-Action"]:
498 print "Going to remove the packages now."
501 whoami = utils.whoami()
502 date = commands.getoutput('date -R')
504 # Log first; if it all falls apart I want a record that we at least tried.
505 logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
506 logfile.write("=========================================================================\n")
507 logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
508 logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
510 logfile.write("Closed bugs: %s\n" % (Options["Done"]))
511 logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
512 logfile.write("----------------------------------------------\n")
515 # Do the same in rfc822 format
516 logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
517 logfile822.write("Date: %s\n" % date)
518 logfile822.write("Ftpmaster: %s\n" % whoami)
519 logfile822.write("Suite: %s\n" % suites_list)
522 for package in summary.split("\n"):
523 for row in package.split("\n"):
524 element = row.split("|")
525 if len(element) == 3:
526 if element[2].find("source") > 0:
527 sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
528 element[2] = sub("source\s?,?", "", element[2]).strip(" ")
530 binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
532 logfile822.write("Sources:\n")
533 for source in sources:
534 logfile822.write(" %s\n" % source)
536 logfile822.write("Binaries:\n")
537 for binary in binaries:
538 logfile822.write(" %s\n" % binary)
539 logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
541 logfile822.write("Bug: %s\n" % Options["Done"])
542 logfile822.write("\n")
546 dsc_type_id = get_override_type('dsc', session).overridetype_id
547 deb_type_id = get_override_type('deb', session).overridetype_id
549 # Do the actual deletion
557 for suite_id in suite_ids_list:
558 if architecture == "source":
559 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
560 {'packageid': package_id, 'suiteid': suite_id})
561 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
563 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
564 {'packageid': package_id, 'suiteid': suite_id})
565 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
566 # Delete from the override file
567 if not Options["Partial"]:
568 if architecture == "source":
569 type_id = dsc_type_id
571 type_id = deb_type_id
572 # TODO: Again, fix this properly to remove the remaining non-bind argument
573 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})
577 # Send the bug closing messages
580 Subst["__RM_ADDRESS__"] = cnf["Rm::MyEmailAddress"]
581 Subst["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
583 if cnf.Find("Dinstall::Bcc") != "":
584 bcc.append(cnf["Dinstall::Bcc"])
585 if cnf.Find("Rm::Bcc") != "":
586 bcc.append(cnf["Rm::Bcc"])
588 Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
590 Subst["__BCC__"] = "X-Filler: 42"
591 Subst["__CC__"] = "X-DAK: dak rm"
593 Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
594 Subst["__SUITE_LIST__"] = suites_list
595 summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
596 summarymail += "----------------------------------------------\n"
597 Subst["__SUMMARY__"] = summarymail
598 Subst["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
599 Subst["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
600 Subst["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
601 Subst["__WHOAMI__"] = whoami
602 whereami = utils.where_am_i()
603 Archive = cnf.SubTree("Archive::%s" % (whereami))
604 Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"]
605 Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"]
606 for bug in utils.split_args(Options["Done"]):
607 Subst["__BUG_NUMBER__"] = bug
608 mail_message = utils.TemplateSubst(Subst,cnf["Dir::Templates"]+"/rm.bug-close")
609 utils.send_mail(mail_message)
611 logfile.write("=========================================================================\n")
614 #######################################################################################
616 if __name__ == '__main__':