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 dak.lib.utils, dak.lib.database
44 import apt_pkg, apt_inst
46 ################################################################################
48 re_strip_source_version = re.compile (r'\s+.*$')
49 re_build_dep_arch = re.compile(r"\[[^]]+\]")
51 ################################################################################
57 ################################################################################
59 def usage (exit_code=0):
60 print """Usage: dak rm [OPTIONS] PACKAGE[...]
61 Remove PACKAGE(s) from suite(s).
63 -a, --architecture=ARCH only act on this architecture
64 -b, --binary remove binaries only
65 -c, --component=COMPONENT act on this component
66 -C, --carbon-copy=EMAIL send a CC of removal message to EMAIL
67 -d, --done=BUG# send removal message as closure to bug#
68 -h, --help show this help and exit
69 -m, --reason=MSG reason for removal
70 -n, --no-action don't do anything
71 -p, --partial don't affect override files
72 -R, --rdep-check check reverse dependencies
73 -s, --suite=SUITE act on this suite
74 -S, --source-only remove source only
76 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
77 --architecture=m68k,i386"""
81 ################################################################################
83 # "Hudson: What that's great, that's just fucking great man, now what
84 # the fuck are we supposed to do? We're in some real pretty shit now
85 # man...That's it man, game over man, game over, man! Game over! What
86 # the fuck are we gonna do now? What are we gonna do?"
89 answer = dak.lib.utils.our_raw_input("Continue (y/N)? ").lower()
94 ################################################################################
96 def reverse_depends_check(removals, suites):
97 print "Checking reverse dependencies..."
98 components = Cnf.ValueList("Suite::%s::Components" % suites[0])
101 for architecture in Cnf.ValueList("Suite::%s::Architectures" % suites[0]):
102 if architecture in ["source", "all"]:
105 virtual_packages = {}
106 for component in components:
107 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (Cnf["Dir::Root"], suites[0], component, architecture)
108 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
109 temp_filename = dak.lib.utils.temp_filename()
110 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
112 dak.lib.utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
113 packages = dak.lib.utils.open_file(temp_filename)
114 Packages = apt_pkg.ParseTagFile(packages)
115 while Packages.Step():
116 package = Packages.Section.Find("Package")
117 depends = Packages.Section.Find("Depends")
119 deps[package] = depends
120 provides = Packages.Section.Find("Provides")
121 # Maintain a counter for each virtual package. If a
122 # Provides: exists, set the counter to 0 and count all
123 # provides by a package not in the list for removal.
124 # If the counter stays 0 at the end, we know that only
125 # the to-be-removed packages provided this virtual
128 for virtual_pkg in provides.split(","):
129 virtual_pkg = virtual_pkg.strip()
130 if virtual_pkg == package: continue
131 if not virtual_packages.has_key(virtual_pkg):
132 virtual_packages[virtual_pkg] = 0
133 if package not in removals:
134 virtual_packages[virtual_pkg] += 1
135 p2c[package] = component
137 os.unlink(temp_filename)
139 # If a virtual package is only provided by the to-be-removed
140 # packages, treat the virtual package as to-be-removed too.
141 for virtual_pkg in virtual_packages.keys():
142 if virtual_packages[virtual_pkg] == 0:
143 removals.append(virtual_pkg)
145 # Check binary dependencies (Depends)
146 for package in deps.keys():
147 if package in removals: continue
150 parsed_dep += apt_pkg.ParseDepends(deps[package])
151 except ValueError, e:
152 print "Error for package %s: %s" % (package, e)
153 for dep in parsed_dep:
154 # Check for partial breakage. If a package has a ORed
155 # dependency, there is only a dependency problem if all
156 # packages in the ORed depends will be removed.
158 for dep_package, _, _ in dep:
159 if dep_package in removals:
161 if unsat == len(dep):
162 component = p2c[package]
163 if component != "main":
164 what = "%s/%s" % (package, component)
166 what = "** %s" % (package)
167 print "%s has an unsatisfied dependency on %s: %s" % (what, architecture, dak.lib.utils.pp_deps(dep))
170 # Check source dependencies (Build-Depends and Build-Depends-Indep)
171 for component in components:
172 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suites[0], component)
173 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
174 temp_filename = dak.lib.utils.temp_filename()
175 result, output = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
177 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
179 sources = dak.lib.utils.open_file(temp_filename, "r")
180 Sources = apt_pkg.ParseTagFile(sources)
181 while Sources.Step():
182 source = Sources.Section.Find("Package")
183 if source in removals: continue
185 for build_dep_type in ["Build-Depends", "Build-Depends-Indep"]:
186 build_dep = Sources.Section.get(build_dep_type)
188 # Remove [arch] information since we want to see breakage on all arches
189 build_dep = re_build_dep_arch.sub("", build_dep)
191 parsed_dep += apt_pkg.ParseDepends(build_dep)
192 except ValueError, e:
193 print "Error for source %s: %s" % (source, e)
194 for dep in parsed_dep:
196 for dep_package, _, _ in dep:
197 if dep_package in removals:
199 if unsat == len(dep):
200 if component != "main":
201 source = "%s/%s" % (source, component)
203 source = "** %s" % (source)
204 print "%s has an unsatisfied build-dependency: %s" % (source, dak.lib.utils.pp_deps(dep))
207 os.unlink(temp_filename)
210 print "Dependency problem found."
211 if not Options["No-Action"]:
214 print "No dependency problem found."
217 ################################################################################
220 global Cnf, Options, projectB
222 Cnf = dak.lib.utils.get_conf()
224 Arguments = [('h',"help","Rm::Options::Help"),
225 ('a',"architecture","Rm::Options::Architecture", "HasArg"),
226 ('b',"binary", "Rm::Options::Binary-Only"),
227 ('c',"component", "Rm::Options::Component", "HasArg"),
228 ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
229 ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
230 ('R',"rdep-check", "Rm::Options::Rdep-Check"),
231 ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
232 ('n',"no-action","Rm::Options::No-Action"),
233 ('p',"partial", "Rm::Options::Partial"),
234 ('s',"suite","Rm::Options::Suite", "HasArg"),
235 ('S',"source-only", "Rm::Options::Source-Only"),
238 for i in [ "architecture", "binary-only", "carbon-copy", "component",
239 "done", "help", "no-action", "partial", "rdep-check", "reason",
241 if not Cnf.has_key("Rm::Options::%s" % (i)):
242 Cnf["Rm::Options::%s" % (i)] = ""
243 if not Cnf.has_key("Rm::Options::Suite"):
244 Cnf["Rm::Options::Suite"] = "unstable"
246 arguments = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
247 Options = Cnf.SubTree("Rm::Options")
252 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
253 dak.lib.database.init(Cnf, projectB)
255 # Sanity check options
257 dak.lib.utils.fubar("need at least one package name as an argument.")
258 if Options["Architecture"] and Options["Source-Only"]:
259 dak.lib.utils.fubar("can't use -a/--architecutre and -S/--source-only options simultaneously.")
260 if Options["Binary-Only"] and Options["Source-Only"]:
261 dak.lib.utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
262 if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
263 dak.lib.utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
264 if Options["Architecture"] and not Options["Partial"]:
265 dak.lib.utils.warn("-a/--architecture implies -p/--partial.")
266 Options["Partial"] = "true"
268 # Force the admin to tell someone if we're not doing a 'dak
269 # cruft-report' inspired removal (or closing a bug, which counts
270 # as telling someone).
271 if not Options["No-Action"] and not Options["Carbon-Copy"] \
272 and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
273 dak.lib.utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
275 # Process -C/--carbon-copy
277 # Accept 3 types of arguments (space separated):
278 # 1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
279 # 2) the keyword 'package' - cc's $package@packages.debian.org for every argument
280 # 3) contains a '@' - assumed to be an email address, used unmofidied
283 for copy_to in dak.lib.utils.split_args(Options.get("Carbon-Copy")):
284 if dak.lib.utils.str_isnum(copy_to):
285 carbon_copy.append(copy_to + "@" + Cnf["Dinstall::BugServer"])
286 elif copy_to == 'package':
287 for package in arguments:
288 carbon_copy.append(package + "@" + Cnf["Dinstall::PackagesServer"])
289 if Cnf.has_key("Dinstall::TrackingServer"):
290 carbon_copy.append(package + "@" + Cnf["Dinstall::TrackingServer"])
292 carbon_copy.append(copy_to)
294 dak.lib.utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
296 if Options["Binary-Only"]:
300 con_packages = "AND %s IN (%s)" % (field, ", ".join(map(repr, arguments)))
302 (con_suites, con_architectures, con_components, check_source) = \
303 dak.lib.utils.parse_args(Options)
305 # Additional suite checks
307 suites = dak.lib.utils.split_args(Options["Suite"])
308 suites_list = dak.lib.utils.join_with_commas_and(suites)
309 if not Options["No-Action"]:
311 suite_id = dak.lib.database.get_suite_id(suite)
313 suite_ids_list.append(suite_id)
314 if suite == "stable":
315 print "**WARNING** About to remove from the stable suite!"
316 print "This should only be done just prior to a (point) release and not at"
317 print "any other time."
319 elif suite == "testing":
320 print "**WARNING About to remove from the testing suite!"
321 print "There's no need to do this normally as removals from unstable will"
322 print "propogate to testing automagically."
325 # Additional architecture checks
326 if Options["Architecture"] and check_source:
327 dak.lib.utils.warn("'source' in -a/--argument makes no sense and is ignored.")
329 # Additional component processing
330 over_con_components = con_components.replace("c.id", "component")
337 # We have 3 modes of package selection: binary-only, source-only
338 # and source+binary. The first two are trivial and obvious; the
339 # latter is a nasty mess, but very nice from a UI perspective so
340 # we try to support it.
342 if Options["Binary-Only"]:
344 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))
345 for i in q.getresult():
350 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))
351 for i in q.getresult():
352 source_packages[i[2]] = i[:2]
353 to_remove.append(i[2:])
354 if not Options["Source-Only"]:
357 # First get a list of binary package names we suspect are linked to the source
358 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))
359 for i in q.getresult():
360 binary_packages[i[0]] = ""
361 # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
362 for i in source_packages.keys():
363 filename = "/".join(source_packages[i])
365 dsc = dak.lib.utils.parse_changes(filename)
366 except dak.lib.utils.cant_open_exc:
367 dak.lib.utils.warn("couldn't open '%s'." % (filename))
369 for package in dsc.get("binary").split(','):
370 package = package.strip()
371 binary_packages[package] = ""
372 # Then for each binary package: find any version in
373 # unstable, check the Source: field in the deb matches our
374 # source package and if so add it to the list of packages
376 for package in binary_packages.keys():
377 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))
378 for i in q.getresult():
379 filename = "/".join(i[:2])
380 control = apt_pkg.ParseSection(apt_inst.debExtractControl(dak.lib.utils.open_file(filename)))
381 source = control.Find("Source", control.Find("Package"))
382 source = re_strip_source_version.sub('', source)
383 if source_packages.has_key(source):
384 to_remove.append(i[2:])
388 print "Nothing to do."
391 # If we don't have a reason; spawn an editor so the user can add one
392 # Write the rejection email out as the <foo>.reason file
393 if not Options["Reason"] and not Options["No-Action"]:
394 temp_filename = dak.lib.utils.temp_filename()
395 editor = os.environ.get("EDITOR","vi")
396 result = os.system("%s %s" % (editor, temp_filename))
398 dak.lib.utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
399 temp_file = dak.lib.utils.open_file(temp_filename)
400 for line in temp_file.readlines():
401 Options["Reason"] += line
403 os.unlink(temp_filename)
405 # Generate the summary of what's to be removed
412 maintainers[maintainer] = ""
413 if not d.has_key(package):
415 if not d[package].has_key(version):
416 d[package][version] = []
417 if architecture not in d[package][version]:
418 d[package][version].append(architecture)
421 for maintainer_id in maintainers.keys():
422 maintainer_list.append(dak.lib.database.get_maintainer(maintainer_id))
426 for package in removals:
427 versions = d[package].keys()
428 versions.sort(apt_pkg.VersionCompare)
429 for version in versions:
430 d[package][version].sort(dak.lib.utils.arch_compare_sw)
431 summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
432 print "Will remove the following packages from %s:" % (suites_list)
435 print "Maintainer: %s" % ", ".join(maintainer_list)
437 print "Will also close bugs: "+Options["Done"]
439 print "Will also send CCs to: " + ", ".join(carbon_copy)
441 print "------------------- Reason -------------------"
442 print Options["Reason"]
443 print "----------------------------------------------"
446 if Options["Rdep-Check"]:
447 reverse_depends_check(removals, suites)
449 # If -n/--no-action, drop out here
450 if Options["No-Action"]:
453 print "Going to remove the packages now."
456 whoami = dak.lib.utils.whoami()
457 date = commands.getoutput('date -R')
459 # Log first; if it all falls apart I want a record that we at least tried.
460 logfile = dak.lib.utils.open_file(Cnf["Rm::LogFile"], 'a')
461 logfile.write("=========================================================================\n")
462 logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
463 logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
465 logfile.write("Closed bugs: %s\n" % (Options["Done"]))
466 logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
467 logfile.write("----------------------------------------------\n")
470 dsc_type_id = dak.lib.database.get_override_type_id('dsc')
471 deb_type_id = dak.lib.database.get_override_type_id('deb')
473 # Do the actual deletion
476 projectB.query("BEGIN WORK")
481 for suite_id in suite_ids_list:
482 if architecture == "source":
483 projectB.query("DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id))
484 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
486 projectB.query("DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id))
487 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
488 # Delete from the override file
489 if not Options["Partial"]:
490 if architecture == "source":
491 type_id = dsc_type_id
493 type_id = deb_type_id
494 projectB.query("DELETE FROM override WHERE package = '%s' AND type = %s AND suite = %s %s" % (package, type_id, suite_id, over_con_components))
495 projectB.query("COMMIT WORK")
498 # Send the bug closing messages
501 Subst["__RM_ADDRESS__"] = Cnf["Rm::MyEmailAddress"]
502 Subst["__BUG_SERVER__"] = Cnf["Dinstall::BugServer"]
504 if Cnf.Find("Dinstall::Bcc") != "":
505 bcc.append(Cnf["Dinstall::Bcc"])
506 if Cnf.Find("Rm::Bcc") != "":
507 bcc.append(Cnf["Rm::Bcc"])
509 Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
511 Subst["__BCC__"] = "X-Filler: 42"
512 Subst["__CC__"] = "X-DAK: dak rm\nX-Katie: this header is obsolete"
514 Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
515 Subst["__SUITE_LIST__"] = suites_list
516 Subst["__SUMMARY__"] = summary
517 Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"]
518 Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"]
519 Subst["__WHOAMI__"] = whoami
520 whereami = dak.lib.utils.where_am_i()
521 Archive = Cnf.SubTree("Archive::%s" % (whereami))
522 Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"]
523 Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"]
524 for bug in dak.lib.utils.split_args(Options["Done"]):
525 Subst["__BUG_NUMBER__"] = bug
526 mail_message = dak.lib.utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/rm.bug-close")
527 dak.lib.utils.send_mail(mail_message)
529 logfile.write("=========================================================================\n")
532 #######################################################################################
534 if __name__ == '__main__':