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