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