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 ################################################################################
42 import commands, os, pg, re, sys
43 import apt_pkg, apt_inst
44 from daklib import database
45 from daklib import utils
46 from daklib.dak_exceptions import *
47 from daklib.regexes import re_strip_source_version, re_build_dep_arch
49 ################################################################################
55 ################################################################################
57 def usage (exit_code=0):
58 print """Usage: dak rm [OPTIONS] PACKAGE[...]
59 Remove PACKAGE(s) from suite(s).
61 -a, --architecture=ARCH only act on this architecture
62 -b, --binary remove binaries only
63 -c, --component=COMPONENT act on this component
64 -C, --carbon-copy=EMAIL send a CC of removal message to EMAIL
65 -d, --done=BUG# send removal message as closure to bug#
66 -h, --help show this help and exit
67 -m, --reason=MSG reason for removal
68 -n, --no-action don't do anything
69 -p, --partial don't affect override files
70 -R, --rdep-check check reverse dependencies
71 -s, --suite=SUITE act on this suite
72 -S, --source-only remove source only
74 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
75 --architecture=m68k,i386"""
79 ################################################################################
81 # "Hudson: What that's great, that's just fucking great man, now what
82 # the fuck are we supposed to do? We're in some real pretty shit now
83 # man...That's it man, game over man, game over, man! Game over! What
84 # the fuck are we gonna do now? What are we gonna do?"
87 answer = utils.our_raw_input("Continue (y/N)? ").lower()
92 ################################################################################
94 def reverse_depends_check(removals, suites, arches=None):
95 print "Checking reverse dependencies..."
96 components = Cnf.ValueList("Suite::%s::Components" % suites[0])
101 all_arches = set(arches)
103 all_arches = set(database.get_suite_architectures(suites[0]))
104 all_arches -= set(["source", "all"])
105 for architecture in all_arches:
108 virtual_packages = {}
109 for component in components:
110 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (Cnf["Dir::Root"], suites[0], component, architecture)
111 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
112 (fd, temp_filename) = utils.temp_filename()
113 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
115 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
116 packages = utils.open_file(temp_filename)
117 Packages = apt_pkg.ParseTagFile(packages)
118 while Packages.Step():
119 package = Packages.Section.Find("Package")
120 source = Packages.Section.Find("Source")
124 source = source.split(' ', 1)[0]
125 sources[package] = source
126 depends = Packages.Section.Find("Depends")
128 deps[package] = depends
129 provides = Packages.Section.Find("Provides")
130 # Maintain a counter for each virtual package. If a
131 # Provides: exists, set the counter to 0 and count all
132 # provides by a package not in the list for removal.
133 # If the counter stays 0 at the end, we know that only
134 # the to-be-removed packages provided this virtual
137 for virtual_pkg in provides.split(","):
138 virtual_pkg = virtual_pkg.strip()
139 if virtual_pkg == package: continue
140 if not virtual_packages.has_key(virtual_pkg):
141 virtual_packages[virtual_pkg] = 0
142 if package not in removals:
143 virtual_packages[virtual_pkg] += 1
144 p2c[package] = component
146 os.unlink(temp_filename)
148 # If a virtual package is only provided by the to-be-removed
149 # packages, treat the virtual package as to-be-removed too.
150 for virtual_pkg in virtual_packages.keys():
151 if virtual_packages[virtual_pkg] == 0:
152 removals.append(virtual_pkg)
154 # Check binary dependencies (Depends)
155 for package in deps.keys():
156 if package in removals: continue
159 parsed_dep += apt_pkg.ParseDepends(deps[package])
160 except ValueError, e:
161 print "Error for package %s: %s" % (package, e)
162 for dep in parsed_dep:
163 # Check for partial breakage. If a package has a ORed
164 # dependency, there is only a dependency problem if all
165 # packages in the ORed depends will be removed.
167 for dep_package, _, _ in dep:
168 if dep_package in removals:
170 if unsat == len(dep):
171 component = p2c[package]
172 source = sources[package]
173 if component != "main":
174 source = "%s/%s" % (source, component)
175 all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
179 print "# Broken Depends:"
180 for source, bindict in sorted(all_broken.items()):
182 for binary, arches in sorted(bindict.items()):
183 if arches == all_arches:
186 lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
187 print '%s: %s' % (source, lines[0])
188 for line in lines[1:]:
189 print ' ' * (len(source) + 2) + line
192 # Check source dependencies (Build-Depends and Build-Depends-Indep)
194 for component in components:
195 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suites[0], component)
196 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
197 (fd, temp_filename) = utils.temp_filename()
198 result, output = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
200 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
202 sources = utils.open_file(temp_filename, "r")
203 Sources = apt_pkg.ParseTagFile(sources)
204 while Sources.Step():
205 source = Sources.Section.Find("Package")
206 if source in removals: continue
208 for build_dep_type in ["Build-Depends", "Build-Depends-Indep"]:
209 build_dep = Sources.Section.get(build_dep_type)
211 # Remove [arch] information since we want to see breakage on all arches
212 build_dep = re_build_dep_arch.sub("", build_dep)
214 parsed_dep += apt_pkg.ParseDepends(build_dep)
215 except ValueError, e:
216 print "Error for source %s: %s" % (source, e)
217 for dep in parsed_dep:
219 for dep_package, _, _ in dep:
220 if dep_package in removals:
222 if unsat == len(dep):
223 if component != "main":
224 source = "%s/%s" % (source, component)
225 all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
228 os.unlink(temp_filename)
231 print "# Broken Build-Depends:"
232 for source, bdeps in sorted(all_broken.items()):
233 bdeps = sorted(bdeps)
234 print '%s: %s' % (source, bdeps[0])
235 for bdep in bdeps[1:]:
236 print ' ' * (len(source) + 2) + bdep
240 print "Dependency problem found."
241 if not Options["No-Action"]:
244 print "No dependency problem found."
247 ################################################################################
250 global Cnf, Options, projectB
252 Cnf = utils.get_conf()
254 Arguments = [('h',"help","Rm::Options::Help"),
255 ('a',"architecture","Rm::Options::Architecture", "HasArg"),
256 ('b',"binary", "Rm::Options::Binary-Only"),
257 ('c',"component", "Rm::Options::Component", "HasArg"),
258 ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
259 ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
260 ('R',"rdep-check", "Rm::Options::Rdep-Check"),
261 ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
262 ('n',"no-action","Rm::Options::No-Action"),
263 ('p',"partial", "Rm::Options::Partial"),
264 ('s',"suite","Rm::Options::Suite", "HasArg"),
265 ('S',"source-only", "Rm::Options::Source-Only"),
268 for i in [ "architecture", "binary-only", "carbon-copy", "component",
269 "done", "help", "no-action", "partial", "rdep-check", "reason",
271 if not Cnf.has_key("Rm::Options::%s" % (i)):
272 Cnf["Rm::Options::%s" % (i)] = ""
273 if not Cnf.has_key("Rm::Options::Suite"):
274 Cnf["Rm::Options::Suite"] = "unstable"
276 arguments = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
277 Options = Cnf.SubTree("Rm::Options")
282 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
283 database.init(Cnf, projectB)
285 # Sanity check options
287 utils.fubar("need at least one package name as an argument.")
288 if Options["Architecture"] and Options["Source-Only"]:
289 utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
290 if Options["Binary-Only"] and Options["Source-Only"]:
291 utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
292 if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
293 utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
294 if Options["Architecture"] and not Options["Partial"]:
295 utils.warn("-a/--architecture implies -p/--partial.")
296 Options["Partial"] = "true"
298 # Force the admin to tell someone if we're not doing a 'dak
299 # cruft-report' inspired removal (or closing a bug, which counts
300 # as telling someone).
301 if not Options["No-Action"] and not Options["Carbon-Copy"] \
302 and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
303 utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
305 # Process -C/--carbon-copy
307 # Accept 3 types of arguments (space separated):
308 # 1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
309 # 2) the keyword 'package' - cc's $package@packages.debian.org for every argument
310 # 3) contains a '@' - assumed to be an email address, used unmofidied
313 for copy_to in utils.split_args(Options.get("Carbon-Copy")):
314 if copy_to.isdigit():
315 carbon_copy.append(copy_to + "@" + Cnf["Dinstall::BugServer"])
316 elif copy_to == 'package':
317 for package in arguments:
318 carbon_copy.append(package + "@" + Cnf["Dinstall::PackagesServer"])
319 if Cnf.has_key("Dinstall::TrackingServer"):
320 carbon_copy.append(package + "@" + Cnf["Dinstall::TrackingServer"])
322 carbon_copy.append(copy_to)
324 utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
326 if Options["Binary-Only"]:
330 con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
332 (con_suites, con_architectures, con_components, check_source) = \
333 utils.parse_args(Options)
335 # Additional suite checks
337 suites = utils.split_args(Options["Suite"])
338 suites_list = utils.join_with_commas_and(suites)
339 if not Options["No-Action"]:
341 suite_id = database.get_suite_id(suite)
343 suite_ids_list.append(suite_id)
344 if suite == "stable":
345 print "**WARNING** About to remove from the stable suite!"
346 print "This should only be done just prior to a (point) release and not at"
347 print "any other time."
349 elif suite == "testing":
350 print "**WARNING About to remove from the testing suite!"
351 print "There's no need to do this normally as removals from unstable will"
352 print "propogate to testing automagically."
355 # Additional architecture checks
356 if Options["Architecture"] and check_source:
357 utils.warn("'source' in -a/--argument makes no sense and is ignored.")
359 # Additional component processing
360 over_con_components = con_components.replace("c.id", "component")
367 # We have 3 modes of package selection: binary-only, source-only
368 # and source+binary. The first two are trivial and obvious; the
369 # latter is a nasty mess, but very nice from a UI perspective so
370 # we try to support it.
372 if Options["Binary-Only"]:
374 q = projectB.query("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))
375 for i in q.getresult():
380 q = projectB.query("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))
381 for i in q.getresult():
382 source_packages[i[2]] = i[:2]
383 to_remove.append(i[2:])
384 if not Options["Source-Only"]:
387 # First get a list of binary package names we suspect are linked to the source
388 q = projectB.query("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))
389 for i in q.getresult():
390 binary_packages[i[0]] = ""
391 # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
392 for i in source_packages.keys():
393 filename = "/".join(source_packages[i])
395 dsc = utils.parse_changes(filename)
396 except CantOpenError:
397 utils.warn("couldn't open '%s'." % (filename))
399 for package in dsc.get("binary").split(','):
400 package = package.strip()
401 binary_packages[package] = ""
402 # Then for each binary package: find any version in
403 # unstable, check the Source: field in the deb matches our
404 # source package and if so add it to the list of packages
406 for package in binary_packages.keys():
407 q = projectB.query("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))
408 for i in q.getresult():
409 filename = "/".join(i[:2])
410 control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
411 source = control.Find("Source", control.Find("Package"))
412 source = re_strip_source_version.sub('', source)
413 if source_packages.has_key(source):
414 to_remove.append(i[2:])
418 print "Nothing to do."
421 # If we don't have a reason; spawn an editor so the user can add one
422 # Write the rejection email out as the <foo>.reason file
423 if not Options["Reason"] and not Options["No-Action"]:
424 (fd, temp_filename) = utils.temp_filename()
425 editor = os.environ.get("EDITOR","vi")
426 result = os.system("%s %s" % (editor, temp_filename))
428 utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
429 temp_file = utils.open_file(temp_filename)
430 for line in temp_file.readlines():
431 Options["Reason"] += line
433 os.unlink(temp_filename)
435 # Generate the summary of what's to be removed
442 maintainers[maintainer] = ""
443 if not d.has_key(package):
445 if not d[package].has_key(version):
446 d[package][version] = []
447 if architecture not in d[package][version]:
448 d[package][version].append(architecture)
451 for maintainer_id in maintainers.keys():
452 maintainer_list.append(database.get_maintainer(maintainer_id))
456 for package in removals:
457 versions = d[package].keys()
458 versions.sort(apt_pkg.VersionCompare)
459 for version in versions:
460 d[package][version].sort(utils.arch_compare_sw)
461 summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
462 print "Will remove the following packages from %s:" % (suites_list)
465 print "Maintainer: %s" % ", ".join(maintainer_list)
467 print "Will also close bugs: "+Options["Done"]
469 print "Will also send CCs to: " + ", ".join(carbon_copy)
471 print "------------------- Reason -------------------"
472 print Options["Reason"]
473 print "----------------------------------------------"
476 if Options["Rdep-Check"]:
477 arches = utils.split_args(Options["Architecture"])
478 reverse_depends_check(removals, suites, arches)
480 # If -n/--no-action, drop out here
481 if Options["No-Action"]:
484 print "Going to remove the packages now."
487 whoami = utils.whoami()
488 date = commands.getoutput('date -R')
490 # Log first; if it all falls apart I want a record that we at least tried.
491 logfile = utils.open_file(Cnf["Rm::LogFile"], 'a')
492 logfile.write("=========================================================================\n")
493 logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
494 logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
496 logfile.write("Closed bugs: %s\n" % (Options["Done"]))
497 logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
498 logfile.write("----------------------------------------------\n")
501 dsc_type_id = database.get_override_type_id('dsc')
502 deb_type_id = database.get_override_type_id('deb')
504 # Do the actual deletion
507 projectB.query("BEGIN WORK")
512 for suite_id in suite_ids_list:
513 if architecture == "source":
514 projectB.query("DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id))
515 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
517 projectB.query("DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id))
518 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
519 # Delete from the override file
520 if not Options["Partial"]:
521 if architecture == "source":
522 type_id = dsc_type_id
524 type_id = deb_type_id
525 projectB.query("DELETE FROM override WHERE package = '%s' AND type = %s AND suite = %s %s" % (package, type_id, suite_id, over_con_components))
526 projectB.query("COMMIT WORK")
529 # Send the bug closing messages
532 Subst["__RM_ADDRESS__"] = Cnf["Rm::MyEmailAddress"]
533 Subst["__BUG_SERVER__"] = Cnf["Dinstall::BugServer"]
535 if Cnf.Find("Dinstall::Bcc") != "":
536 bcc.append(Cnf["Dinstall::Bcc"])
537 if Cnf.Find("Rm::Bcc") != "":
538 bcc.append(Cnf["Rm::Bcc"])
540 Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
542 Subst["__BCC__"] = "X-Filler: 42"
543 Subst["__CC__"] = "X-DAK: dak rm\nX-Katie: melanie"
545 Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
546 Subst["__SUITE_LIST__"] = suites_list
547 Subst["__SUMMARY__"] = summary
548 Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"]
549 Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"]
550 Subst["__WHOAMI__"] = whoami
551 whereami = utils.where_am_i()
552 Archive = Cnf.SubTree("Archive::%s" % (whereami))
553 Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"]
554 Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"]
555 for bug in utils.split_args(Options["Done"]):
556 Subst["__BUG_NUMBER__"] = bug
557 mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/rm.bug-close")
558 utils.send_mail(mail_message)
560 logfile.write("=========================================================================\n")
563 #######################################################################################
565 if __name__ == '__main__':