]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
dak rm: read binary metadata from db
[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     dbsuite = get_suite(suite, session)
103     cnf = Config()
104
105     print "Checking reverse dependencies..."
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     metakey_d = get_or_set_metadatakey("Depends", session)
115     metakey_p = get_or_set_metadatakey("Provides", session)
116     params = {
117         'suite_id':     dbsuite.suite_id,
118         'metakey_d_id': metakey_d.key_id,
119         'metakey_p_id': metakey_p.key_id,
120         'arch_all_id' : get_architecture('all', session).arch_id,
121     }
122     for architecture in all_arches:
123         deps = {}
124         sources = {}
125         virtual_packages = {}
126         params['arch_id'] = get_architecture(architecture, session).arch_id
127
128         statement = '''
129             SELECT b.id, b.package, s.source, c.name as component,
130                 bmd.value as depends, bmp.value as provides
131                 FROM binaries b
132                 LEFT OUTER JOIN binaries_metadata bmd
133                     ON b.id = bmd.bin_id AND bmd.key_id = :metakey_d_id
134                 LEFT OUTER JOIN binaries_metadata bmp
135                     ON b.id = bmp.bin_id AND bmp.key_id = :metakey_p_id
136                 JOIN source s ON b.source = s.id
137                 JOIN files f ON b.file = f.id
138                 JOIN location l ON f.location = l.id
139                 JOIN component c ON l.component = c.id
140                 WHERE b.id in
141                     (SELECT bin FROM bin_associations WHERE suite = :suite_id)
142                     AND b.architecture in (:arch_id, :arch_all_id)'''
143         query = session.query('id', 'package', 'source', 'component', 'depends', 'provides'). \
144             from_statement(statement).params(params)
145         for binary_id, package, source, component, depends, provides in query:
146             sources[package] = source
147             p2c[package] = component
148             if depends is not None:
149                 deps[package] = depends
150             # Maintain a counter for each virtual package.  If a
151             # Provides: exists, set the counter to 0 and count all
152             # provides by a package not in the list for removal.
153             # If the counter stays 0 at the end, we know that only
154             # the to-be-removed packages provided this virtual
155             # package.
156             if provides is not None:
157                 for virtual_pkg in provides.split(","):
158                     virtual_pkg = virtual_pkg.strip()
159                     if virtual_pkg == package: continue
160                     if not virtual_packages.has_key(virtual_pkg):
161                         virtual_packages[virtual_pkg] = 0
162                     if package not in removals:
163                         virtual_packages[virtual_pkg] += 1
164
165         # If a virtual package is only provided by the to-be-removed
166         # packages, treat the virtual package as to-be-removed too.
167         for virtual_pkg in virtual_packages.keys():
168             if virtual_packages[virtual_pkg] == 0:
169                 removals.append(virtual_pkg)
170
171         # Check binary dependencies (Depends)
172         for package in deps.keys():
173             if package in removals: continue
174             parsed_dep = []
175             try:
176                 parsed_dep += apt_pkg.ParseDepends(deps[package])
177             except ValueError, e:
178                 print "Error for package %s: %s" % (package, e)
179             for dep in parsed_dep:
180                 # Check for partial breakage.  If a package has a ORed
181                 # dependency, there is only a dependency problem if all
182                 # packages in the ORed depends will be removed.
183                 unsat = 0
184                 for dep_package, _, _ in dep:
185                     if dep_package in removals:
186                         unsat += 1
187                 if unsat == len(dep):
188                     component = p2c[package]
189                     source = sources[package]
190                     if component != "main":
191                         source = "%s/%s" % (source, component)
192                     all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
193                     dep_problem = 1
194
195     if all_broken:
196         print "# Broken Depends:"
197         for source, bindict in sorted(all_broken.items()):
198             lines = []
199             for binary, arches in sorted(bindict.items()):
200                 if arches == all_arches:
201                     lines.append(binary)
202                 else:
203                     lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
204             print '%s: %s' % (source, lines[0])
205             for line in lines[1:]:
206                 print ' ' * (len(source) + 2) + line
207         print
208
209     # Check source dependencies (Build-Depends and Build-Depends-Indep)
210     all_broken.clear()
211     metakey_bd = get_or_set_metadatakey("Build-Depends", session)
212     metakey_bdi = get_or_set_metadatakey("Build-Depends-Indep", session)
213     params = {
214         'suite_id':    dbsuite.suite_id,
215         'metakey_ids': (metakey_bd.key_id, metakey_bdi.key_id),
216     }
217     statement = '''
218         SELECT s.id, s.source, string_agg(sm.value, ', ') as build_dep
219            FROM source s
220            JOIN source_metadata sm ON s.id = sm.src_id
221            WHERE s.id in
222                (SELECT source FROM src_associations
223                    WHERE suite = :suite_id)
224                AND sm.key_id in :metakey_ids
225            GROUP BY s.id, s.source'''
226     query = session.query('id', 'source', 'build_dep').from_statement(statement). \
227         params(params)
228     for source_id, source, build_dep in query:
229         if source in removals: continue
230         parsed_dep = []
231         if build_dep is not None:
232             # Remove [arch] information since we want to see breakage on all arches
233             build_dep = re_build_dep_arch.sub("", build_dep)
234             try:
235                 parsed_dep += apt_pkg.ParseDepends(build_dep)
236             except ValueError, e:
237                 print "Error for source %s: %s" % (source, e)
238         for dep in parsed_dep:
239             unsat = 0
240             for dep_package, _, _ in dep:
241                 if dep_package in removals:
242                     unsat += 1
243             if unsat == len(dep):
244                 component = DBSource.get(source_id, session).get_component_name()
245                 if component != "main":
246                     source = "%s/%s" % (source, component)
247                 all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
248                 dep_problem = 1
249
250     if all_broken:
251         print "# Broken Build-Depends:"
252         for source, bdeps in sorted(all_broken.items()):
253             bdeps = sorted(bdeps)
254             print '%s: %s' % (source, bdeps[0])
255             for bdep in bdeps[1:]:
256                 print ' ' * (len(source) + 2) + bdep
257         print
258
259     if dep_problem:
260         print "Dependency problem found."
261         if not Options["No-Action"]:
262             game_over()
263     else:
264         print "No dependency problem found."
265     print
266
267 ################################################################################
268
269 def main ():
270     global Options
271
272     cnf = Config()
273
274     Arguments = [('h',"help","Rm::Options::Help"),
275                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
276                  ('b',"binary", "Rm::Options::Binary-Only"),
277                  ('c',"component", "Rm::Options::Component", "HasArg"),
278                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
279                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
280                  ('D',"do-close","Rm::Options::Do-Close"),
281                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
282                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
283                  ('n',"no-action","Rm::Options::No-Action"),
284                  ('p',"partial", "Rm::Options::Partial"),
285                  ('s',"suite","Rm::Options::Suite", "HasArg"),
286                  ('S',"source-only", "Rm::Options::Source-Only"),
287                  ]
288
289     for i in [ "architecture", "binary-only", "carbon-copy", "component",
290                "done", "help", "no-action", "partial", "rdep-check", "reason",
291                "source-only", "Do-Close" ]:
292         if not cnf.has_key("Rm::Options::%s" % (i)):
293             cnf["Rm::Options::%s" % (i)] = ""
294     if not cnf.has_key("Rm::Options::Suite"):
295         cnf["Rm::Options::Suite"] = "unstable"
296
297     arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
298     Options = cnf.SubTree("Rm::Options")
299
300     if Options["Help"]:
301         usage()
302
303     session = DBConn().session()
304
305     # Sanity check options
306     if not arguments:
307         utils.fubar("need at least one package name as an argument.")
308     if Options["Architecture"] and Options["Source-Only"]:
309         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
310     if Options["Binary-Only"] and Options["Source-Only"]:
311         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
312     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
313         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
314     if Options["Architecture"] and not Options["Partial"]:
315         utils.warn("-a/--architecture implies -p/--partial.")
316         Options["Partial"] = "true"
317     if Options["Do-Close"] and not Options["Done"]:
318         utils.fubar("No.")
319     if Options["Do-Close"] and Options["Binary-Only"]:
320         utils.fubar("No.")
321     if Options["Do-Close"] and Options["Source-Only"]:
322         utils.fubar("No.")
323     if Options["Do-Close"] and Options["Suite"] != 'unstable':
324         utils.fubar("No.")
325
326     # Force the admin to tell someone if we're not doing a 'dak
327     # cruft-report' inspired removal (or closing a bug, which counts
328     # as telling someone).
329     if not Options["No-Action"] and not Options["Carbon-Copy"] \
330            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
331         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
332
333     # Process -C/--carbon-copy
334     #
335     # Accept 3 types of arguments (space separated):
336     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
337     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
338     #  3) contains a '@' - assumed to be an email address, used unmofidied
339     #
340     carbon_copy = []
341     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
342         if copy_to.isdigit():
343             if cnf.has_key("Dinstall::BugServer"):
344                 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
345             else:
346                 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
347         elif copy_to == 'package':
348             for package in arguments:
349                 if cnf.has_key("Dinstall::PackagesServer"):
350                     carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
351                 if cnf.has_key("Dinstall::TrackingServer"):
352                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
353         elif '@' in copy_to:
354             carbon_copy.append(copy_to)
355         else:
356             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
357
358     if Options["Binary-Only"]:
359         field = "b.package"
360     else:
361         field = "s.source"
362     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
363
364     (con_suites, con_architectures, con_components, check_source) = \
365                  utils.parse_args(Options)
366
367     # Additional suite checks
368     suite_ids_list = []
369     suites = utils.split_args(Options["Suite"])
370     suites_list = utils.join_with_commas_and(suites)
371     if not Options["No-Action"]:
372         for suite in suites:
373             s = get_suite(suite, session=session)
374             if s is not None:
375                 suite_ids_list.append(s.suite_id)
376             if suite in ("oldstable", "stable"):
377                 print "**WARNING** About to remove from the (old)stable suite!"
378                 print "This should only be done just prior to a (point) release and not at"
379                 print "any other time."
380                 game_over()
381             elif suite == "testing":
382                 print "**WARNING About to remove from the testing suite!"
383                 print "There's no need to do this normally as removals from unstable will"
384                 print "propogate to testing automagically."
385                 game_over()
386
387     # Additional architecture checks
388     if Options["Architecture"] and check_source:
389         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
390
391     # Additional component processing
392     over_con_components = con_components.replace("c.id", "component")
393
394     # Don't do dependency checks on multiple suites
395     if Options["Rdep-Check"] and len(suites) > 1:
396         utils.fubar("Reverse dependency check on multiple suites is not implemented.")
397
398     print "Working...",
399     sys.stdout.flush()
400     to_remove = []
401     maintainers = {}
402
403     # We have 3 modes of package selection: binary-only, source-only
404     # and source+binary.  The first two are trivial and obvious; the
405     # latter is a nasty mess, but very nice from a UI perspective so
406     # we try to support it.
407
408     # XXX: TODO: This all needs converting to use placeholders or the object
409     #            API. It's an SQL injection dream at the moment
410
411     if Options["Binary-Only"]:
412         # Binary-only
413         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))
414         for i in q.fetchall():
415             to_remove.append(i)
416     else:
417         # Source-only
418         source_packages = {}
419         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))
420         for i in q.fetchall():
421             source_packages[i[2]] = i[:2]
422             to_remove.append(i[2:])
423         if not Options["Source-Only"]:
424             # Source + Binary
425             binary_packages = {}
426             # First get a list of binary package names we suspect are linked to the source
427             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))
428             for i in q.fetchall():
429                 binary_packages[i[0]] = ""
430             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
431             for i in source_packages.keys():
432                 filename = "/".join(source_packages[i])
433                 try:
434                     dsc = utils.parse_changes(filename, dsc_file=1)
435                 except CantOpenError:
436                     utils.warn("couldn't open '%s'." % (filename))
437                     continue
438                 for package in dsc.get("binary").split(','):
439                     package = package.strip()
440                     binary_packages[package] = ""
441             # Then for each binary package: find any version in
442             # unstable, check the Source: field in the deb matches our
443             # source package and if so add it to the list of packages
444             # to be removed.
445             for package in binary_packages.keys():
446                 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))
447                 for i in q.fetchall():
448                     filename = "/".join(i[:2])
449                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
450                     source = control.Find("Source", control.Find("Package"))
451                     source = re_strip_source_version.sub('', source)
452                     if source_packages.has_key(source):
453                         to_remove.append(i[2:])
454     print "done."
455
456     if not to_remove:
457         print "Nothing to do."
458         sys.exit(0)
459
460     # If we don't have a reason; spawn an editor so the user can add one
461     # Write the rejection email out as the <foo>.reason file
462     if not Options["Reason"] and not Options["No-Action"]:
463         (fd, temp_filename) = utils.temp_filename()
464         editor = os.environ.get("EDITOR","vi")
465         result = os.system("%s %s" % (editor, temp_filename))
466         if result != 0:
467             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
468         temp_file = utils.open_file(temp_filename)
469         for line in temp_file.readlines():
470             Options["Reason"] += line
471         temp_file.close()
472         os.unlink(temp_filename)
473
474     # Generate the summary of what's to be removed
475     d = {}
476     for i in to_remove:
477         package = i[0]
478         version = i[1]
479         architecture = i[2]
480         maintainer = i[4]
481         maintainers[maintainer] = ""
482         if not d.has_key(package):
483             d[package] = {}
484         if not d[package].has_key(version):
485             d[package][version] = []
486         if architecture not in d[package][version]:
487             d[package][version].append(architecture)
488
489     maintainer_list = []
490     for maintainer_id in maintainers.keys():
491         maintainer_list.append(get_maintainer(maintainer_id).name)
492     summary = ""
493     removals = d.keys()
494     removals.sort()
495     versions = []
496     for package in removals:
497         versions = d[package].keys()
498         versions.sort(apt_pkg.VersionCompare)
499         for version in versions:
500             d[package][version].sort(utils.arch_compare_sw)
501             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
502     print "Will remove the following packages from %s:" % (suites_list)
503     print
504     print summary
505     print "Maintainer: %s" % ", ".join(maintainer_list)
506     if Options["Done"]:
507         print "Will also close bugs: "+Options["Done"]
508     if carbon_copy:
509         print "Will also send CCs to: " + ", ".join(carbon_copy)
510     if Options["Do-Close"]:
511         print "Will also close associated bug reports."
512     print
513     print "------------------- Reason -------------------"
514     print Options["Reason"]
515     print "----------------------------------------------"
516     print
517
518     if Options["Rdep-Check"]:
519         arches = utils.split_args(Options["Architecture"])
520         reverse_depends_check(removals, suites[0], arches, session)
521
522     # If -n/--no-action, drop out here
523     if Options["No-Action"]:
524         sys.exit(0)
525
526     print "Going to remove the packages now."
527     game_over()
528
529     whoami = utils.whoami()
530     date = commands.getoutput('date -R')
531
532     # Log first; if it all falls apart I want a record that we at least tried.
533     logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
534     logfile.write("=========================================================================\n")
535     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
536     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
537     if Options["Done"]:
538         logfile.write("Closed bugs: %s\n" % (Options["Done"]))
539     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
540     logfile.write("----------------------------------------------\n")
541
542     # Do the same in rfc822 format
543     logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
544     logfile822.write("Date: %s\n" % date)
545     logfile822.write("Ftpmaster: %s\n" % whoami)
546     logfile822.write("Suite: %s\n" % suites_list)
547     sources = []
548     binaries = []
549     for package in summary.split("\n"):
550         for row in package.split("\n"):
551             element = row.split("|")
552             if len(element) == 3:
553                 if element[2].find("source") > 0:
554                     sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
555                     element[2] = sub("source\s?,?", "", element[2]).strip(" ")
556                 if element[2]:
557                     binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
558     if sources:
559         logfile822.write("Sources:\n")
560         for source in sources:
561             logfile822.write(" %s\n" % source)
562     if binaries:
563         logfile822.write("Binaries:\n")
564         for binary in binaries:
565             logfile822.write(" %s\n" % binary)
566     logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
567     if Options["Done"]:
568         logfile822.write("Bug: %s\n" % Options["Done"])
569
570     dsc_type_id = get_override_type('dsc', session).overridetype_id
571     deb_type_id = get_override_type('deb', session).overridetype_id
572
573     # Do the actual deletion
574     print "Deleting...",
575     sys.stdout.flush()
576
577     for i in to_remove:
578         package = i[0]
579         architecture = i[2]
580         package_id = i[3]
581         for suite_id in suite_ids_list:
582             if architecture == "source":
583                 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
584                                 {'packageid': package_id, 'suiteid': suite_id})
585                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
586             else:
587                 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
588                                 {'packageid': package_id, 'suiteid': suite_id})
589                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
590             # Delete from the override file
591             if not Options["Partial"]:
592                 if architecture == "source":
593                     type_id = dsc_type_id
594                 else:
595                     type_id = deb_type_id
596                 # TODO: Again, fix this properly to remove the remaining non-bind argument
597                 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})
598     session.commit()
599     print "done."
600
601     # If we don't have a Bug server configured, we're done
602     if not cnf.has_key("Dinstall::BugServer"):
603         if Options["Done"] or Options["Do-Close"]:
604             print "Cannot send mail to BugServer as Dinstall::BugServer is not configured"
605
606         logfile.write("=========================================================================\n")
607         logfile.close()
608
609         logfile822.write("\n")
610         logfile822.close()
611
612         return
613
614     # read common subst variables for all bug closure mails
615     Subst_common = {}
616     Subst_common["__RM_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
617     Subst_common["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
618     Subst_common["__CC__"] = "X-DAK: dak rm"
619     if carbon_copy:
620         Subst_common["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
621     Subst_common["__SUITE_LIST__"] = suites_list
622     Subst_common["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
623     Subst_common["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
624     Subst_common["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
625     Subst_common["__WHOAMI__"] = whoami
626
627     # Send the bug closing messages
628     if Options["Done"]:
629         Subst_close_rm = Subst_common
630         bcc = []
631         if cnf.Find("Dinstall::Bcc") != "":
632             bcc.append(cnf["Dinstall::Bcc"])
633         if cnf.Find("Rm::Bcc") != "":
634             bcc.append(cnf["Rm::Bcc"])
635         if bcc:
636             Subst_close_rm["__BCC__"] = "Bcc: " + ", ".join(bcc)
637         else:
638             Subst_close_rm["__BCC__"] = "X-Filler: 42"
639         summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
640         summarymail += "----------------------------------------------\n"
641         Subst_close_rm["__SUMMARY__"] = summarymail
642
643         whereami = utils.where_am_i()
644         Archive = get_archive(whereami, session)
645         if Archive is None:
646             utils.warn("Cannot find archive %s.  Setting blank values for origin" % whereami)
647             Subst_close_rm["__MASTER_ARCHIVE__"] = ""
648             Subst_close_rm["__PRIMARY_MIRROR__"] = ""
649         else:
650             Subst_close_rm["__MASTER_ARCHIVE__"] = Archive.origin_server
651             Subst_close_rm["__PRIMARY_MIRROR__"] = Archive.primary_mirror
652
653         for bug in utils.split_args(Options["Done"]):
654             Subst_close_rm["__BUG_NUMBER__"] = bug
655             if Options["Do-Close"]:
656                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close-with-related")
657             else:
658                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close")
659             utils.send_mail(mail_message)
660
661     # close associated bug reports
662     if Options["Do-Close"]:
663         Subst_close_other = Subst_common
664         bcc = []
665         wnpp = utils.parse_wnpp_bug_file()
666         if len(versions) == 1:
667             Subst_close_other["__VERSION__"] = versions[0]
668         else:
669             utils.fubar("Closing bugs with multiple package versions is not supported.  Do it yourself.")
670         if bcc:
671             Subst_close_other["__BCC__"] = "Bcc: " + ", ".join(bcc)
672         else:
673             Subst_close_other["__BCC__"] = "X-Filler: 42"
674         # at this point, I just assume, that the first closed bug gives
675         # some useful information on why the package got removed
676         Subst_close_other["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
677         if len(sources) == 1:
678             source_pkg = source.split("_", 1)[0]
679         else:
680             utils.fubar("Closing bugs for multiple source pakcages is not supported.  Do it yourself.")
681         Subst_close_other["__BUG_NUMBER_ALSO__"] = ""
682         Subst_close_other["__SOURCE__"] = source_pkg
683         other_bugs = bts.get_bugs('src', source_pkg, 'status', 'open')
684         if other_bugs:
685             logfile.write("Also closing bug(s):")
686             logfile822.write("Also-Bugs:")
687             for bug in other_bugs:
688                 Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
689                 logfile.write(" " + str(bug))
690                 logfile822.write(" " + str(bug))
691             logfile.write("\n")
692             logfile822.write("\n")
693         if source_pkg in wnpp.keys():
694             logfile.write("Also closing WNPP bug(s):")
695             logfile822.write("Also-WNPP:")
696             for bug in wnpp[source_pkg]:
697                 # the wnpp-rm file we parse also contains our removal
698                 # bugs, filtering that out
699                 if bug != Subst_close_other["__BUG_NUMBER__"]:
700                     Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
701                     logfile.write(" " + str(bug))
702                     logfile822.write(" " + str(bug))
703             logfile.write("\n")
704             logfile822.write("\n")
705
706         mail_message = utils.TemplateSubst(Subst_close_other,cnf["Dir::Templates"]+"/rm.bug-close-related")
707         if Subst_close_other["__BUG_NUMBER_ALSO__"]:
708             utils.send_mail(mail_message)
709
710
711     logfile.write("=========================================================================\n")
712     logfile.close()
713
714     logfile822.write("\n")
715     logfile822.close()
716
717 #######################################################################################
718
719 if __name__ == '__main__':
720     main()