]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
Merge from Mark: <mhy> err yes, I don't know what I was thinking
[dak.git] / dak / rm.py
1 #!/usr/bin/env python
2
3 # General purpose package removal tool for ftpmaster
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5
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.
10
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.
15
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
19
20 ################################################################################
21
22 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
23 #    respond.
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!"
27 # o Insert Flame War.
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.
37
38 #                        http://slashdot.org/comments.pl?sid=26697&cid=2883271
39
40 ################################################################################
41
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
48 ################################################################################
49
50 re_strip_source_version = re.compile (r'\s+.*$')
51 re_build_dep_arch = re.compile(r"\[[^]]+\]")
52
53 ################################################################################
54
55 Cnf = None
56 Options = None
57 projectB = None
58
59 ################################################################################
60
61 def usage (exit_code=0):
62     print """Usage: dak rm [OPTIONS] PACKAGE[...]
63 Remove PACKAGE(s) from suite(s).
64
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
77
78 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
79     --architecture=m68k,i386"""
80
81     sys.exit(exit_code)
82
83 ################################################################################
84
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?"
89
90 def game_over():
91     answer = utils.our_raw_input("Continue (y/N)? ").lower()
92     if answer != "y":
93         print "Aborted."
94         sys.exit(1)
95
96 ################################################################################
97
98 def reverse_depends_check(removals, suites):
99     print "Checking reverse dependencies..."
100     components = Cnf.ValueList("Suite::%s::Components" % suites[0])
101     dep_problem = 0
102     p2c = {}
103     for architecture in Cnf.ValueList("Suite::%s::Architectures" % suites[0]):
104         if architecture in ["source", "all"]:
105             continue
106         deps = {}
107         virtual_packages = {}
108         for component in components:
109             filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (Cnf["Dir::Root"], suites[0], component, architecture)
110             # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
111             temp_filename = utils.temp_filename()
112             (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
113             if (result != 0):
114                 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
115             packages = utils.open_file(temp_filename)
116             Packages = apt_pkg.ParseTagFile(packages)
117             while Packages.Step():
118                 package = Packages.Section.Find("Package")
119                 depends = Packages.Section.Find("Depends")
120                 if depends:
121                     deps[package] = depends
122                 provides = Packages.Section.Find("Provides")
123                 # Maintain a counter for each virtual package.  If a
124                 # Provides: exists, set the counter to 0 and count all
125                 # provides by a package not in the list for removal.
126                 # If the counter stays 0 at the end, we know that only
127                 # the to-be-removed packages provided this virtual
128                 # package.
129                 if provides:
130                     for virtual_pkg in provides.split(","):
131                         virtual_pkg = virtual_pkg.strip()
132                         if virtual_pkg == package: continue
133                         if not virtual_packages.has_key(virtual_pkg):
134                             virtual_packages[virtual_pkg] = 0
135                         if package not in removals:
136                             virtual_packages[virtual_pkg] += 1
137                 p2c[package] = component
138             packages.close()
139             os.unlink(temp_filename)
140
141         # If a virtual package is only provided by the to-be-removed
142         # packages, treat the virtual package as to-be-removed too.
143         for virtual_pkg in virtual_packages.keys():
144             if virtual_packages[virtual_pkg] == 0:
145                 removals.append(virtual_pkg)
146
147         # Check binary dependencies (Depends)
148         for package in deps.keys():
149             if package in removals: continue
150             parsed_dep = []
151             try:
152                 parsed_dep += apt_pkg.ParseDepends(deps[package])
153             except ValueError, e:
154                 print "Error for package %s: %s" % (package, e)
155             for dep in parsed_dep:
156                 # Check for partial breakage.  If a package has a ORed
157                 # dependency, there is only a dependency problem if all
158                 # packages in the ORed depends will be removed.
159                 unsat = 0
160                 for dep_package, _, _ in dep:
161                     if dep_package in removals:
162                         unsat += 1
163                 if unsat == len(dep):
164                     component = p2c[package]
165                     if component != "main":
166                         what = "%s/%s" % (package, component)
167                     else:
168                         what = "** %s" % (package)
169                     print "%s has an unsatisfied dependency on %s: %s" % (what, architecture, utils.pp_deps(dep))
170                     dep_problem = 1
171
172     # Check source dependencies (Build-Depends and Build-Depends-Indep)
173     for component in components:
174         filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suites[0], component)
175         # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
176         temp_filename = utils.temp_filename()
177         result, output = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
178         if result != 0:
179             sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
180             sys.exit(result)
181         sources = utils.open_file(temp_filename, "r")
182         Sources = apt_pkg.ParseTagFile(sources)
183         while Sources.Step():
184             source = Sources.Section.Find("Package")
185             if source in removals: continue
186             parsed_dep = []
187             for build_dep_type in ["Build-Depends", "Build-Depends-Indep"]:
188                 build_dep = Sources.Section.get(build_dep_type)
189                 if build_dep:
190                     # Remove [arch] information since we want to see breakage on all arches
191                     build_dep = re_build_dep_arch.sub("", build_dep)
192                     try:
193                         parsed_dep += apt_pkg.ParseDepends(build_dep)
194                     except ValueError, e:
195                         print "Error for source %s: %s" % (source, e)
196             for dep in parsed_dep:
197                 unsat = 0
198                 for dep_package, _, _ in dep:
199                     if dep_package in removals:
200                         unsat += 1
201                 if unsat == len(dep):
202                     if component != "main":
203                         source = "%s/%s" % (source, component)
204                     else:
205                         source = "** %s" % (source)
206                     print "%s has an unsatisfied build-dependency: %s" % (source, utils.pp_deps(dep))
207                     dep_problem = 1
208         sources.close()
209         os.unlink(temp_filename)
210
211     if dep_problem:
212         print "Dependency problem found."
213         if not Options["No-Action"]:
214             game_over()
215     else:
216         print "No dependency problem found."
217     print
218
219 ################################################################################
220
221 def main ():
222     global Cnf, Options, projectB
223
224     Cnf = utils.get_conf()
225
226     Arguments = [('h',"help","Rm::Options::Help"),
227                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
228                  ('b',"binary", "Rm::Options::Binary-Only"),
229                  ('c',"component", "Rm::Options::Component", "HasArg"),
230                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
231                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
232                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
233                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
234                  ('n',"no-action","Rm::Options::No-Action"),
235                  ('p',"partial", "Rm::Options::Partial"),
236                  ('s',"suite","Rm::Options::Suite", "HasArg"),
237                  ('S',"source-only", "Rm::Options::Source-Only"),
238                  ]
239
240     for i in [ "architecture", "binary-only", "carbon-copy", "component",
241                "done", "help", "no-action", "partial", "rdep-check", "reason",
242                "source-only" ]:
243         if not Cnf.has_key("Rm::Options::%s" % (i)):
244             Cnf["Rm::Options::%s" % (i)] = ""
245     if not Cnf.has_key("Rm::Options::Suite"):
246         Cnf["Rm::Options::Suite"] = "unstable"
247
248     arguments = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
249     Options = Cnf.SubTree("Rm::Options")
250
251     if Options["Help"]:
252         usage()
253
254     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
255     database.init(Cnf, projectB)
256
257     # Sanity check options
258     if not arguments:
259         utils.fubar("need at least one package name as an argument.")
260     if Options["Architecture"] and Options["Source-Only"]:
261         utils.fubar("can't use -a/--architecutre and -S/--source-only options simultaneously.")
262     if Options["Binary-Only"] and Options["Source-Only"]:
263         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
264     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
265         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
266     if Options["Architecture"] and not Options["Partial"]:
267         utils.warn("-a/--architecture implies -p/--partial.")
268         Options["Partial"] = "true"
269
270     # Force the admin to tell someone if we're not doing a 'dak
271     # cruft-report' inspired removal (or closing a bug, which counts
272     # as telling someone).
273     if not Options["No-Action"] and not Options["Carbon-Copy"] \
274            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
275         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
276
277     # Process -C/--carbon-copy
278     #
279     # Accept 3 types of arguments (space separated):
280     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
281     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
282     #  3) contains a '@' - assumed to be an email address, used unmofidied
283     #
284     carbon_copy = []
285     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
286         if copy_to.isdigit():
287             carbon_copy.append(copy_to + "@" + Cnf["Dinstall::BugServer"])
288         elif copy_to == 'package':
289             for package in arguments:
290                 carbon_copy.append(package + "@" + Cnf["Dinstall::PackagesServer"])
291                 if Cnf.has_key("Dinstall::TrackingServer"):
292                     carbon_copy.append(package + "@" + Cnf["Dinstall::TrackingServer"])
293         elif '@' in copy_to:
294             carbon_copy.append(copy_to)
295         else:
296             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
297
298     if Options["Binary-Only"]:
299         field = "b.package"
300     else:
301         field = "s.source"
302     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
303
304     (con_suites, con_architectures, con_components, check_source) = \
305                  utils.parse_args(Options)
306
307     # Additional suite checks
308     suite_ids_list = []
309     suites = utils.split_args(Options["Suite"])
310     suites_list = utils.join_with_commas_and(suites)
311     if not Options["No-Action"]:
312         for suite in suites:
313             suite_id = database.get_suite_id(suite)
314             if suite_id != -1:
315                 suite_ids_list.append(suite_id)
316             if suite == "stable":
317                 print "**WARNING** About to remove from the stable suite!"
318                 print "This should only be done just prior to a (point) release and not at"
319                 print "any other time."
320                 game_over()
321             elif suite == "testing":
322                 print "**WARNING About to remove from the testing suite!"
323                 print "There's no need to do this normally as removals from unstable will"
324                 print "propogate to testing automagically."
325                 game_over()
326
327     # Additional architecture checks
328     if Options["Architecture"] and check_source:
329         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
330
331     # Additional component processing
332     over_con_components = con_components.replace("c.id", "component")
333
334     print "Working...",
335     sys.stdout.flush()
336     to_remove = []
337     maintainers = {}
338
339     # We have 3 modes of package selection: binary-only, source-only
340     # and source+binary.  The first two are trivial and obvious; the
341     # latter is a nasty mess, but very nice from a UI perspective so
342     # we try to support it.
343
344     if Options["Binary-Only"]:
345         # Binary-only
346         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))
347         for i in q.getresult():
348             to_remove.append(i)
349     else:
350         # Source-only
351         source_packages = {}
352         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))
353         for i in q.getresult():
354             source_packages[i[2]] = i[:2]
355             to_remove.append(i[2:])
356         if not Options["Source-Only"]:
357             # Source + Binary
358             binary_packages = {}
359             # First get a list of binary package names we suspect are linked to the source
360             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))
361             for i in q.getresult():
362                 binary_packages[i[0]] = ""
363             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
364             for i in source_packages.keys():
365                 filename = "/".join(source_packages[i])
366                 try:
367                     dsc = utils.parse_changes(filename)
368                 except CantOpenError:
369                     utils.warn("couldn't open '%s'." % (filename))
370                     continue
371                 for package in dsc.get("binary").split(','):
372                     package = package.strip()
373                     binary_packages[package] = ""
374             # Then for each binary package: find any version in
375             # unstable, check the Source: field in the deb matches our
376             # source package and if so add it to the list of packages
377             # to be removed.
378             for package in binary_packages.keys():
379                 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))
380                 for i in q.getresult():
381                     filename = "/".join(i[:2])
382                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
383                     source = control.Find("Source", control.Find("Package"))
384                     source = re_strip_source_version.sub('', source)
385                     if source_packages.has_key(source):
386                         to_remove.append(i[2:])
387     print "done."
388
389     if not to_remove:
390         print "Nothing to do."
391         sys.exit(0)
392
393     # If we don't have a reason; spawn an editor so the user can add one
394     # Write the rejection email out as the <foo>.reason file
395     if not Options["Reason"] and not Options["No-Action"]:
396         temp_filename = utils.temp_filename()
397         editor = os.environ.get("EDITOR","vi")
398         result = os.system("%s %s" % (editor, temp_filename))
399         if result != 0:
400             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
401         temp_file = utils.open_file(temp_filename)
402         for line in temp_file.readlines():
403             Options["Reason"] += line
404         temp_file.close()
405         os.unlink(temp_filename)
406
407     # Generate the summary of what's to be removed
408     d = {}
409     for i in to_remove:
410         package = i[0]
411         version = i[1]
412         architecture = i[2]
413         maintainer = i[4]
414         maintainers[maintainer] = ""
415         if not d.has_key(package):
416             d[package] = {}
417         if not d[package].has_key(version):
418             d[package][version] = []
419         if architecture not in d[package][version]:
420             d[package][version].append(architecture)
421
422     maintainer_list = []
423     for maintainer_id in maintainers.keys():
424         maintainer_list.append(database.get_maintainer(maintainer_id))
425     summary = ""
426     removals = d.keys()
427     removals.sort()
428     for package in removals:
429         versions = d[package].keys()
430         versions.sort(apt_pkg.VersionCompare)
431         for version in versions:
432             d[package][version].sort(utils.arch_compare_sw)
433             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
434     print "Will remove the following packages from %s:" % (suites_list)
435     print
436     print summary
437     print "Maintainer: %s" % ", ".join(maintainer_list)
438     if Options["Done"]:
439         print "Will also close bugs: "+Options["Done"]
440     if carbon_copy:
441         print "Will also send CCs to: " + ", ".join(carbon_copy)
442     print
443     print "------------------- Reason -------------------"
444     print Options["Reason"]
445     print "----------------------------------------------"
446     print
447
448     if Options["Rdep-Check"]:
449         reverse_depends_check(removals, suites)
450
451     # If -n/--no-action, drop out here
452     if Options["No-Action"]:
453         sys.exit(0)
454
455     print "Going to remove the packages now."
456     game_over()
457
458     whoami = utils.whoami()
459     date = commands.getoutput('date -R')
460
461     # Log first; if it all falls apart I want a record that we at least tried.
462     logfile = utils.open_file(Cnf["Rm::LogFile"], 'a')
463     logfile.write("=========================================================================\n")
464     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
465     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
466     if Options["Done"]:
467         logfile.write("Closed bugs: %s\n" % (Options["Done"]))
468     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
469     logfile.write("----------------------------------------------\n")
470     logfile.flush()
471
472     dsc_type_id = database.get_override_type_id('dsc')
473     deb_type_id = database.get_override_type_id('deb')
474
475     # Do the actual deletion
476     print "Deleting...",
477     sys.stdout.flush()
478     projectB.query("BEGIN WORK")
479     for i in to_remove:
480         package = i[0]
481         architecture = i[2]
482         package_id = i[3]
483         for suite_id in suite_ids_list:
484             if architecture == "source":
485                 projectB.query("DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id))
486                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
487             else:
488                 projectB.query("DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id))
489                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
490             # Delete from the override file
491             if not Options["Partial"]:
492                 if architecture == "source":
493                     type_id = dsc_type_id
494                 else:
495                     type_id = deb_type_id
496                 projectB.query("DELETE FROM override WHERE package = '%s' AND type = %s AND suite = %s %s" % (package, type_id, suite_id, over_con_components))
497     projectB.query("COMMIT WORK")
498     print "done."
499
500     # Send the bug closing messages
501     if Options["Done"]:
502         Subst = {}
503         Subst["__RM_ADDRESS__"] = Cnf["Rm::MyEmailAddress"]
504         Subst["__BUG_SERVER__"] = Cnf["Dinstall::BugServer"]
505         bcc = []
506         if Cnf.Find("Dinstall::Bcc") != "":
507             bcc.append(Cnf["Dinstall::Bcc"])
508         if Cnf.Find("Rm::Bcc") != "":
509             bcc.append(Cnf["Rm::Bcc"])
510         if bcc:
511             Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
512         else:
513             Subst["__BCC__"] = "X-Filler: 42"
514         Subst["__CC__"] = "X-DAK: dak rm\nX-Katie: melanie $Revision: 1.44 $"
515         if carbon_copy:
516             Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
517         Subst["__SUITE_LIST__"] = suites_list
518         Subst["__SUMMARY__"] = summary
519         Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"]
520         Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"]
521         Subst["__WHOAMI__"] = whoami
522         whereami = utils.where_am_i()
523         Archive = Cnf.SubTree("Archive::%s" % (whereami))
524         Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"]
525         Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"]
526         for bug in utils.split_args(Options["Done"]):
527             Subst["__BUG_NUMBER__"] = bug
528             mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/rm.bug-close")
529             utils.send_mail(mail_message)
530
531     logfile.write("=========================================================================\n")
532     logfile.close()
533
534 #######################################################################################
535
536 if __name__ == '__main__':
537     main()