]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
dak rm: improve checking of reverse Build-Depends
[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 # Copyright (C) 2010 Alexander Reichle-Schmehl <tolimar@debian.org>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
24 #    respond.
25 # o Ask again -> No respond. Darren coder supreme.
26 # o OpenBSD decide to make changes, but only in OpenBSD source
27 #    tree. Darren hears, gets angry! Decides: "LICENSE NO ALLOW!"
28 # o Insert Flame War.
29 # o OpenBSD team decide to switch to different packet filter under BSD
30 #    license. Because Project Goal: Every user should be able to make
31 #    changes to source tree. IPF license bad!!
32 # o Darren try get back: says, NetBSD, FreeBSD allowed! MUAHAHAHAH!!!
33 # o Theo say: no care, pf much better than ipf!
34 # o Darren changes mind: changes license. But OpenBSD will not change
35 #    back to ipf. Darren even much more bitter.
36 # o Darren so bitterbitter. Decides: I'LL GET BACK BY FORKING OPENBSD AND
37 #    RELEASING MY OWN VERSION. HEHEHEHEHE.
38
39 #                        http://slashdot.org/comments.pl?sid=26697&cid=2883271
40
41 ################################################################################
42
43 import commands
44 import os
45 import sys
46 import apt_pkg
47 import apt_inst
48 from re import sub
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 import debianbts as bts
56
57 ################################################################################
58
59 Options = None
60
61 ################################################################################
62
63 def usage (exit_code=0):
64     print """Usage: dak rm [OPTIONS] PACKAGE[...]
65 Remove PACKAGE(s) from suite(s).
66
67   -a, --architecture=ARCH    only act on this architecture
68   -b, --binary               remove binaries only
69   -c, --component=COMPONENT  act on this component
70   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
71   -d, --done=BUG#            send removal message as closure to bug#
72   -D, --do-close             also close all bugs associated to that package
73   -h, --help                 show this help and exit
74   -m, --reason=MSG           reason for removal
75   -n, --no-action            don't do anything
76   -p, --partial              don't affect override files
77   -R, --rdep-check           check reverse dependencies
78   -s, --suite=SUITE          act on this suite
79   -S, --source-only          remove source only
80
81 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
82     --architecture=amd64,i386"""
83
84     sys.exit(exit_code)
85
86 ################################################################################
87
88 # "Hudson: What that's great, that's just fucking great man, now what
89 #  the fuck are we supposed to do? We're in some real pretty shit now
90 #  man...That's it man, game over man, game over, man! Game over! What
91 #  the fuck are we gonna do now? What are we gonna do?"
92
93 def game_over():
94     answer = utils.our_raw_input("Continue (y/N)? ").lower()
95     if answer != "y":
96         print "Aborted."
97         sys.exit(1)
98
99 ################################################################################
100
101 def reverse_depends_check(removals, suite, arches=None, session=None):
102     cnf = Config()
103
104     print "Checking reverse dependencies..."
105     components = get_component_names()
106     dep_problem = 0
107     p2c = {}
108     all_broken = {}
109     if arches:
110         all_arches = set(arches)
111     else:
112         all_arches = set([x.arch_string for x in get_suite_architectures(suite)])
113     all_arches -= set(["source", "all"])
114     for architecture in all_arches:
115         deps = {}
116         sources = {}
117         virtual_packages = {}
118         for component in components:
119             filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (cnf["Dir::Root"], suite, component, architecture)
120             # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
121             (fd, temp_filename) = utils.temp_filename()
122             (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
123             if (result != 0):
124                 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
125             # Also check for udebs
126             filename = "%s/dists/%s/%s/debian-installer/binary-%s/Packages.gz" % (cnf["Dir::Root"], suite, component, architecture)
127             if os.path.exists(filename):
128                 (result, output) = commands.getstatusoutput("gunzip -c %s >> %s" % (filename, temp_filename))
129                 if (result != 0):
130                     utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
131             packages = utils.open_file(temp_filename)
132             Packages = apt_pkg.ParseTagFile(packages)
133             while Packages.Step():
134                 package = Packages.Section.Find("Package")
135                 source = Packages.Section.Find("Source")
136                 if not source:
137                     source = package
138                 elif ' ' in source:
139                     source = source.split(' ', 1)[0]
140                 sources[package] = source
141                 depends = Packages.Section.Find("Depends")
142                 if depends:
143                     deps[package] = depends
144                 provides = Packages.Section.Find("Provides")
145                 # Maintain a counter for each virtual package.  If a
146                 # Provides: exists, set the counter to 0 and count all
147                 # provides by a package not in the list for removal.
148                 # If the counter stays 0 at the end, we know that only
149                 # the to-be-removed packages provided this virtual
150                 # package.
151                 if provides:
152                     for virtual_pkg in provides.split(","):
153                         virtual_pkg = virtual_pkg.strip()
154                         if virtual_pkg == package: continue
155                         if not virtual_packages.has_key(virtual_pkg):
156                             virtual_packages[virtual_pkg] = 0
157                         if package not in removals:
158                             virtual_packages[virtual_pkg] += 1
159                 p2c[package] = component
160             packages.close()
161             os.unlink(temp_filename)
162
163         # If a virtual package is only provided by the to-be-removed
164         # packages, treat the virtual package as to-be-removed too.
165         for virtual_pkg in virtual_packages.keys():
166             if virtual_packages[virtual_pkg] == 0:
167                 removals.append(virtual_pkg)
168
169         # Check binary dependencies (Depends)
170         for package in deps.keys():
171             if package in removals: continue
172             parsed_dep = []
173             try:
174                 parsed_dep += apt_pkg.ParseDepends(deps[package])
175             except ValueError, e:
176                 print "Error for package %s: %s" % (package, e)
177             for dep in parsed_dep:
178                 # Check for partial breakage.  If a package has a ORed
179                 # dependency, there is only a dependency problem if all
180                 # packages in the ORed depends will be removed.
181                 unsat = 0
182                 for dep_package, _, _ in dep:
183                     if dep_package in removals:
184                         unsat += 1
185                 if unsat == len(dep):
186                     component = p2c[package]
187                     source = sources[package]
188                     if component != "main":
189                         source = "%s/%s" % (source, component)
190                     all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
191                     dep_problem = 1
192
193     if all_broken:
194         print "# Broken Depends:"
195         for source, bindict in sorted(all_broken.items()):
196             lines = []
197             for binary, arches in sorted(bindict.items()):
198                 if arches == all_arches:
199                     lines.append(binary)
200                 else:
201                     lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
202             print '%s: %s' % (source, lines[0])
203             for line in lines[1:]:
204                 print ' ' * (len(source) + 2) + line
205         print
206
207     # Check source dependencies (Build-Depends and Build-Depends-Indep)
208     all_broken.clear()
209     dbsuite = get_suite(suite, session)
210     metakey_bd = get_or_set_metadatakey("Build-Depends", session)
211     metakey_bdi = get_or_set_metadatakey("Build-Depends-Indep", session)
212     params = {
213         'suite_id':    dbsuite.suite_id,
214         'metakey_ids': (metakey_bd.key_id, metakey_bdi.key_id),
215     }
216     statement = '''
217         SELECT s.id, s.source, string_agg(sm.value, ', ') as build_dep
218            FROM source s
219            JOIN source_metadata sm ON s.id = sm.src_id
220            WHERE s.id in
221                (SELECT source FROM src_associations
222                    WHERE suite = :suite_id)
223                AND sm.key_id in :metakey_ids
224            GROUP BY s.id, s.source'''
225     query = session.query('id', 'source', 'build_dep').from_statement(statement). \
226         params(params)
227     for source_id, source, build_dep in query:
228         if source in removals: continue
229         parsed_dep = []
230         if build_dep is not None:
231             # Remove [arch] information since we want to see breakage on all arches
232             build_dep = re_build_dep_arch.sub("", build_dep)
233             try:
234                 parsed_dep += apt_pkg.ParseDepends(build_dep)
235             except ValueError, e:
236                 print "Error for source %s: %s" % (source, e)
237         for dep in parsed_dep:
238             unsat = 0
239             for dep_package, _, _ in dep:
240                 if dep_package in removals:
241                     unsat += 1
242             if unsat == len(dep):
243                 component = DBSource.get(source_id, session).get_component_name()
244                 if component != "main":
245                     source = "%s/%s" % (source, component)
246                 all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
247                 dep_problem = 1
248
249     if all_broken:
250         print "# Broken Build-Depends:"
251         for source, bdeps in sorted(all_broken.items()):
252             bdeps = sorted(bdeps)
253             print '%s: %s' % (source, bdeps[0])
254             for bdep in bdeps[1:]:
255                 print ' ' * (len(source) + 2) + bdep
256         print
257
258     if dep_problem:
259         print "Dependency problem found."
260         if not Options["No-Action"]:
261             game_over()
262     else:
263         print "No dependency problem found."
264     print
265
266 ################################################################################
267
268 def main ():
269     global Options
270
271     cnf = Config()
272
273     Arguments = [('h',"help","Rm::Options::Help"),
274                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
275                  ('b',"binary", "Rm::Options::Binary-Only"),
276                  ('c',"component", "Rm::Options::Component", "HasArg"),
277                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
278                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
279                  ('D',"do-close","Rm::Options::Do-Close"),
280                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
281                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
282                  ('n',"no-action","Rm::Options::No-Action"),
283                  ('p',"partial", "Rm::Options::Partial"),
284                  ('s',"suite","Rm::Options::Suite", "HasArg"),
285                  ('S',"source-only", "Rm::Options::Source-Only"),
286                  ]
287
288     for i in [ "architecture", "binary-only", "carbon-copy", "component",
289                "done", "help", "no-action", "partial", "rdep-check", "reason",
290                "source-only", "Do-Close" ]:
291         if not cnf.has_key("Rm::Options::%s" % (i)):
292             cnf["Rm::Options::%s" % (i)] = ""
293     if not cnf.has_key("Rm::Options::Suite"):
294         cnf["Rm::Options::Suite"] = "unstable"
295
296     arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
297     Options = cnf.SubTree("Rm::Options")
298
299     if Options["Help"]:
300         usage()
301
302     session = DBConn().session()
303
304     # Sanity check options
305     if not arguments:
306         utils.fubar("need at least one package name as an argument.")
307     if Options["Architecture"] and Options["Source-Only"]:
308         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
309     if Options["Binary-Only"] and Options["Source-Only"]:
310         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
311     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
312         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
313     if Options["Architecture"] and not Options["Partial"]:
314         utils.warn("-a/--architecture implies -p/--partial.")
315         Options["Partial"] = "true"
316     if Options["Do-Close"] and not Options["Done"]:
317         utils.fubar("No.")
318     if Options["Do-Close"] and Options["Binary-Only"]:
319         utils.fubar("No.")
320     if Options["Do-Close"] and Options["Source-Only"]:
321         utils.fubar("No.")
322     if Options["Do-Close"] and Options["Suite"] != 'unstable':
323         utils.fubar("No.")
324
325     # Force the admin to tell someone if we're not doing a 'dak
326     # cruft-report' inspired removal (or closing a bug, which counts
327     # as telling someone).
328     if not Options["No-Action"] and not Options["Carbon-Copy"] \
329            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
330         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
331
332     # Process -C/--carbon-copy
333     #
334     # Accept 3 types of arguments (space separated):
335     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
336     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
337     #  3) contains a '@' - assumed to be an email address, used unmofidied
338     #
339     carbon_copy = []
340     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
341         if copy_to.isdigit():
342             if cnf.has_key("Dinstall::BugServer"):
343                 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
344             else:
345                 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
346         elif copy_to == 'package':
347             for package in arguments:
348                 if cnf.has_key("Dinstall::PackagesServer"):
349                     carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
350                 if cnf.has_key("Dinstall::TrackingServer"):
351                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
352         elif '@' in copy_to:
353             carbon_copy.append(copy_to)
354         else:
355             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
356
357     if Options["Binary-Only"]:
358         field = "b.package"
359     else:
360         field = "s.source"
361     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
362
363     (con_suites, con_architectures, con_components, check_source) = \
364                  utils.parse_args(Options)
365
366     # Additional suite checks
367     suite_ids_list = []
368     suites = utils.split_args(Options["Suite"])
369     suites_list = utils.join_with_commas_and(suites)
370     if not Options["No-Action"]:
371         for suite in suites:
372             s = get_suite(suite, session=session)
373             if s is not None:
374                 suite_ids_list.append(s.suite_id)
375             if suite in ("oldstable", "stable"):
376                 print "**WARNING** About to remove from the (old)stable suite!"
377                 print "This should only be done just prior to a (point) release and not at"
378                 print "any other time."
379                 game_over()
380             elif suite == "testing":
381                 print "**WARNING About to remove from the testing suite!"
382                 print "There's no need to do this normally as removals from unstable will"
383                 print "propogate to testing automagically."
384                 game_over()
385
386     # Additional architecture checks
387     if Options["Architecture"] and check_source:
388         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
389
390     # Additional component processing
391     over_con_components = con_components.replace("c.id", "component")
392
393     # Don't do dependency checks on multiple suites
394     if Options["Rdep-Check"] and len(suites) > 1:
395         utils.fubar("Reverse dependency check on multiple suites is not implemented.")
396
397     print "Working...",
398     sys.stdout.flush()
399     to_remove = []
400     maintainers = {}
401
402     # We have 3 modes of package selection: binary-only, source-only
403     # and source+binary.  The first two are trivial and obvious; the
404     # latter is a nasty mess, but very nice from a UI perspective so
405     # we try to support it.
406
407     # XXX: TODO: This all needs converting to use placeholders or the object
408     #            API. It's an SQL injection dream at the moment
409
410     if Options["Binary-Only"]:
411         # Binary-only
412         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))
413         for i in q.fetchall():
414             to_remove.append(i)
415     else:
416         # Source-only
417         source_packages = {}
418         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))
419         for i in q.fetchall():
420             source_packages[i[2]] = i[:2]
421             to_remove.append(i[2:])
422         if not Options["Source-Only"]:
423             # Source + Binary
424             binary_packages = {}
425             # First get a list of binary package names we suspect are linked to the source
426             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))
427             for i in q.fetchall():
428                 binary_packages[i[0]] = ""
429             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
430             for i in source_packages.keys():
431                 filename = "/".join(source_packages[i])
432                 try:
433                     dsc = utils.parse_changes(filename, dsc_file=1)
434                 except CantOpenError:
435                     utils.warn("couldn't open '%s'." % (filename))
436                     continue
437                 for package in dsc.get("binary").split(','):
438                     package = package.strip()
439                     binary_packages[package] = ""
440             # Then for each binary package: find any version in
441             # unstable, check the Source: field in the deb matches our
442             # source package and if so add it to the list of packages
443             # to be removed.
444             for package in binary_packages.keys():
445                 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))
446                 for i in q.fetchall():
447                     filename = "/".join(i[:2])
448                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
449                     source = control.Find("Source", control.Find("Package"))
450                     source = re_strip_source_version.sub('', source)
451                     if source_packages.has_key(source):
452                         to_remove.append(i[2:])
453     print "done."
454
455     if not to_remove:
456         print "Nothing to do."
457         sys.exit(0)
458
459     # If we don't have a reason; spawn an editor so the user can add one
460     # Write the rejection email out as the <foo>.reason file
461     if not Options["Reason"] and not Options["No-Action"]:
462         (fd, temp_filename) = utils.temp_filename()
463         editor = os.environ.get("EDITOR","vi")
464         result = os.system("%s %s" % (editor, temp_filename))
465         if result != 0:
466             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
467         temp_file = utils.open_file(temp_filename)
468         for line in temp_file.readlines():
469             Options["Reason"] += line
470         temp_file.close()
471         os.unlink(temp_filename)
472
473     # Generate the summary of what's to be removed
474     d = {}
475     for i in to_remove:
476         package = i[0]
477         version = i[1]
478         architecture = i[2]
479         maintainer = i[4]
480         maintainers[maintainer] = ""
481         if not d.has_key(package):
482             d[package] = {}
483         if not d[package].has_key(version):
484             d[package][version] = []
485         if architecture not in d[package][version]:
486             d[package][version].append(architecture)
487
488     maintainer_list = []
489     for maintainer_id in maintainers.keys():
490         maintainer_list.append(get_maintainer(maintainer_id).name)
491     summary = ""
492     removals = d.keys()
493     removals.sort()
494     versions = []
495     for package in removals:
496         versions = d[package].keys()
497         versions.sort(apt_pkg.VersionCompare)
498         for version in versions:
499             d[package][version].sort(utils.arch_compare_sw)
500             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
501     print "Will remove the following packages from %s:" % (suites_list)
502     print
503     print summary
504     print "Maintainer: %s" % ", ".join(maintainer_list)
505     if Options["Done"]:
506         print "Will also close bugs: "+Options["Done"]
507     if carbon_copy:
508         print "Will also send CCs to: " + ", ".join(carbon_copy)
509     if Options["Do-Close"]:
510         print "Will also close associated bug reports."
511     print
512     print "------------------- Reason -------------------"
513     print Options["Reason"]
514     print "----------------------------------------------"
515     print
516
517     if Options["Rdep-Check"]:
518         arches = utils.split_args(Options["Architecture"])
519         reverse_depends_check(removals, suites[0], arches, session)
520
521     # If -n/--no-action, drop out here
522     if Options["No-Action"]:
523         sys.exit(0)
524
525     print "Going to remove the packages now."
526     game_over()
527
528     whoami = utils.whoami()
529     date = commands.getoutput('date -R')
530
531     # Log first; if it all falls apart I want a record that we at least tried.
532     logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
533     logfile.write("=========================================================================\n")
534     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
535     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
536     if Options["Done"]:
537         logfile.write("Closed bugs: %s\n" % (Options["Done"]))
538     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
539     logfile.write("----------------------------------------------\n")
540
541     # Do the same in rfc822 format
542     logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
543     logfile822.write("Date: %s\n" % date)
544     logfile822.write("Ftpmaster: %s\n" % whoami)
545     logfile822.write("Suite: %s\n" % suites_list)
546     sources = []
547     binaries = []
548     for package in summary.split("\n"):
549         for row in package.split("\n"):
550             element = row.split("|")
551             if len(element) == 3:
552                 if element[2].find("source") > 0:
553                     sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
554                     element[2] = sub("source\s?,?", "", element[2]).strip(" ")
555                 if element[2]:
556                     binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
557     if sources:
558         logfile822.write("Sources:\n")
559         for source in sources:
560             logfile822.write(" %s\n" % source)
561     if binaries:
562         logfile822.write("Binaries:\n")
563         for binary in binaries:
564             logfile822.write(" %s\n" % binary)
565     logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
566     if Options["Done"]:
567         logfile822.write("Bug: %s\n" % Options["Done"])
568
569     dsc_type_id = get_override_type('dsc', session).overridetype_id
570     deb_type_id = get_override_type('deb', session).overridetype_id
571
572     # Do the actual deletion
573     print "Deleting...",
574     sys.stdout.flush()
575
576     for i in to_remove:
577         package = i[0]
578         architecture = i[2]
579         package_id = i[3]
580         for suite_id in suite_ids_list:
581             if architecture == "source":
582                 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
583                                 {'packageid': package_id, 'suiteid': suite_id})
584                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
585             else:
586                 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
587                                 {'packageid': package_id, 'suiteid': suite_id})
588                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
589             # Delete from the override file
590             if not Options["Partial"]:
591                 if architecture == "source":
592                     type_id = dsc_type_id
593                 else:
594                     type_id = deb_type_id
595                 # TODO: Again, fix this properly to remove the remaining non-bind argument
596                 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})
597     session.commit()
598     print "done."
599
600     # If we don't have a Bug server configured, we're done
601     if not cnf.has_key("Dinstall::BugServer"):
602         if Options["Done"] or Options["Do-Close"]:
603             print "Cannot send mail to BugServer as Dinstall::BugServer is not configured"
604
605         logfile.write("=========================================================================\n")
606         logfile.close()
607
608         logfile822.write("\n")
609         logfile822.close()
610
611         return
612
613     # read common subst variables for all bug closure mails
614     Subst_common = {}
615     Subst_common["__RM_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
616     Subst_common["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
617     Subst_common["__CC__"] = "X-DAK: dak rm"
618     if carbon_copy:
619         Subst_common["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
620     Subst_common["__SUITE_LIST__"] = suites_list
621     Subst_common["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
622     Subst_common["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
623     Subst_common["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
624     Subst_common["__WHOAMI__"] = whoami
625
626     # Send the bug closing messages
627     if Options["Done"]:
628         Subst_close_rm = Subst_common
629         bcc = []
630         if cnf.Find("Dinstall::Bcc") != "":
631             bcc.append(cnf["Dinstall::Bcc"])
632         if cnf.Find("Rm::Bcc") != "":
633             bcc.append(cnf["Rm::Bcc"])
634         if bcc:
635             Subst_close_rm["__BCC__"] = "Bcc: " + ", ".join(bcc)
636         else:
637             Subst_close_rm["__BCC__"] = "X-Filler: 42"
638         summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
639         summarymail += "----------------------------------------------\n"
640         Subst_close_rm["__SUMMARY__"] = summarymail
641
642         whereami = utils.where_am_i()
643         Archive = get_archive(whereami, session)
644         if Archive is None:
645             utils.warn("Cannot find archive %s.  Setting blank values for origin" % whereami)
646             Subst_close_rm["__MASTER_ARCHIVE__"] = ""
647             Subst_close_rm["__PRIMARY_MIRROR__"] = ""
648         else:
649             Subst_close_rm["__MASTER_ARCHIVE__"] = Archive.origin_server
650             Subst_close_rm["__PRIMARY_MIRROR__"] = Archive.primary_mirror
651
652         for bug in utils.split_args(Options["Done"]):
653             Subst_close_rm["__BUG_NUMBER__"] = bug
654             if Options["Do-Close"]:
655                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close-with-related")
656             else:
657                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close")
658             utils.send_mail(mail_message)
659
660     # close associated bug reports
661     if Options["Do-Close"]:
662         Subst_close_other = Subst_common
663         bcc = []
664         wnpp = utils.parse_wnpp_bug_file()
665         if len(versions) == 1:
666             Subst_close_other["__VERSION__"] = versions[0]
667         else:
668             utils.fubar("Closing bugs with multiple package versions is not supported.  Do it yourself.")
669         if bcc:
670             Subst_close_other["__BCC__"] = "Bcc: " + ", ".join(bcc)
671         else:
672             Subst_close_other["__BCC__"] = "X-Filler: 42"
673         # at this point, I just assume, that the first closed bug gives
674         # some useful information on why the package got removed
675         Subst_close_other["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
676         if len(sources) == 1:
677             source_pkg = source.split("_", 1)[0]
678         else:
679             utils.fubar("Closing bugs for multiple source pakcages is not supported.  Do it yourself.")
680         Subst_close_other["__BUG_NUMBER_ALSO__"] = ""
681         Subst_close_other["__SOURCE__"] = source_pkg
682         other_bugs = bts.get_bugs('src', source_pkg, 'status', 'open')
683         if other_bugs:
684             logfile.write("Also closing bug(s):")
685             logfile822.write("Also-Bugs:")
686             for bug in other_bugs:
687                 Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
688                 logfile.write(" " + str(bug))
689                 logfile822.write(" " + str(bug))
690             logfile.write("\n")
691             logfile822.write("\n")
692         if source_pkg in wnpp.keys():
693             logfile.write("Also closing WNPP bug(s):")
694             logfile822.write("Also-WNPP:")
695             for bug in wnpp[source_pkg]:
696                 # the wnpp-rm file we parse also contains our removal
697                 # bugs, filtering that out
698                 if bug != Subst_close_other["__BUG_NUMBER__"]:
699                     Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
700                     logfile.write(" " + str(bug))
701                     logfile822.write(" " + str(bug))
702             logfile.write("\n")
703             logfile822.write("\n")
704
705         mail_message = utils.TemplateSubst(Subst_close_other,cnf["Dir::Templates"]+"/rm.bug-close-related")
706         if Subst_close_other["__BUG_NUMBER_ALSO__"]:
707             utils.send_mail(mail_message)
708
709
710     logfile.write("=========================================================================\n")
711     logfile.close()
712
713     logfile822.write("\n")
714     logfile822.close()
715
716 #######################################################################################
717
718 if __name__ == '__main__':
719     main()