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