]> git.donarmstrong.com Git - dak.git/blob - dak/rm.py
Remove old (and slow) code
[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_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               PACKAGE are binary packages to remove
69   -B, --binary-only          remove binaries only
70   -c, --component=COMPONENT  act on this component
71   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
72   -d, --done=BUG#            send removal message as closure to bug#
73   -D, --do-close             also close all bugs associated to that package
74   -h, --help                 show this help and exit
75   -m, --reason=MSG           reason for removal
76   -n, --no-action            don't do anything
77   -p, --partial              don't affect override files
78   -R, --rdep-check           check reverse dependencies
79   -s, --suite=SUITE          act on this suite
80   -S, --source-only          remove source only
81
82 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
83     --architecture=amd64,i386"""
84
85     sys.exit(exit_code)
86
87 ################################################################################
88
89 # "Hudson: What that's great, that's just fucking great man, now what
90 #  the fuck are we supposed to do? We're in some real pretty shit now
91 #  man...That's it man, game over man, game over, man! Game over! What
92 #  the fuck are we gonna do now? What are we gonna do?"
93
94 def game_over():
95     answer = utils.our_raw_input("Continue (y/N)? ").lower()
96     if answer != "y":
97         print "Aborted."
98         sys.exit(1)
99
100 ################################################################################
101
102 def reverse_depends_check(removals, suite, arches=None, session=None):
103     print "Checking reverse dependencies..."
104     if utils.check_reverse_depends(removals, suite, arches, session):
105         print "Dependency problem found."
106         if not Options["No-Action"]:
107             game_over()
108     else:
109         print "No dependency problem found."
110     print
111
112 ################################################################################
113
114 def main ():
115     global Options
116
117     cnf = Config()
118
119     Arguments = [('h',"help","Rm::Options::Help"),
120                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
121                  ('b',"binary", "Rm::Options::Binary"),
122                  ('B',"binary-only", "Rm::Options::Binary-Only"),
123                  ('c',"component", "Rm::Options::Component", "HasArg"),
124                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
125                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
126                  ('D',"do-close","Rm::Options::Do-Close"),
127                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
128                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
129                  ('n',"no-action","Rm::Options::No-Action"),
130                  ('p',"partial", "Rm::Options::Partial"),
131                  ('s',"suite","Rm::Options::Suite", "HasArg"),
132                  ('S',"source-only", "Rm::Options::Source-Only"),
133                  ]
134
135     for i in [ "architecture", "binary", "binary-only", "carbon-copy", "component",
136                "done", "help", "no-action", "partial", "rdep-check", "reason",
137                "source-only", "Do-Close" ]:
138         if not cnf.has_key("Rm::Options::%s" % (i)):
139             cnf["Rm::Options::%s" % (i)] = ""
140     if not cnf.has_key("Rm::Options::Suite"):
141         cnf["Rm::Options::Suite"] = "unstable"
142
143     arguments = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
144     Options = cnf.subtree("Rm::Options")
145
146     if Options["Help"]:
147         usage()
148
149     session = DBConn().session()
150
151     # Sanity check options
152     if not arguments:
153         utils.fubar("need at least one package name as an argument.")
154     if Options["Architecture"] and Options["Source-Only"]:
155         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
156     if ((Options["Binary"] and Options["Source-Only"])
157             or (Options["Binary"] and Options["Binary-Only"])
158             or (Options["Binary-Only"] and Options["Source-Only"])):
159         utils.fubar("Only one of -b/--binary, -B/--binary-only and -S/--source-only can be used.")
160     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
161         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
162     if Options["Architecture"] and not Options["Partial"]:
163         utils.warn("-a/--architecture implies -p/--partial.")
164         Options["Partial"] = "true"
165     if Options["Do-Close"] and not Options["Done"]:
166         utils.fubar("No.")
167     if (Options["Do-Close"]
168            and (Options["Binary"] or Options["Binary-Only"] or Options["Source-Only"])):
169         utils.fubar("No.")
170
171     # Force the admin to tell someone if we're not doing a 'dak
172     # cruft-report' inspired removal (or closing a bug, which counts
173     # as telling someone).
174     if not Options["No-Action"] and not Options["Carbon-Copy"] \
175            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
176         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
177
178     # Process -C/--carbon-copy
179     #
180     # Accept 3 types of arguments (space separated):
181     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
182     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
183     #  3) contains a '@' - assumed to be an email address, used unmofidied
184     #
185     carbon_copy = []
186     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
187         if copy_to.isdigit():
188             if cnf.has_key("Dinstall::BugServer"):
189                 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
190             else:
191                 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
192         elif copy_to == 'package':
193             for package in arguments:
194                 if cnf.has_key("Dinstall::PackagesServer"):
195                     carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
196                 if cnf.has_key("Dinstall::TrackingServer"):
197                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
198         elif '@' in copy_to:
199             carbon_copy.append(copy_to)
200         else:
201             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
202
203     if Options["Binary"]:
204         field = "b.package"
205     else:
206         field = "s.source"
207     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
208
209     (con_suites, con_architectures, con_components, check_source) = \
210                  utils.parse_args(Options)
211
212     # Additional suite checks
213     suite_ids_list = []
214     whitelists = []
215     suites = utils.split_args(Options["Suite"])
216     suites_list = utils.join_with_commas_and(suites)
217     if not Options["No-Action"]:
218         for suite in suites:
219             s = get_suite(suite, session=session)
220             if s is not None:
221                 suite_ids_list.append(s.suite_id)
222                 whitelists.append(s.mail_whitelist)
223             if suite in ("oldstable", "stable"):
224                 print "**WARNING** About to remove from the (old)stable suite!"
225                 print "This should only be done just prior to a (point) release and not at"
226                 print "any other time."
227                 game_over()
228             elif suite == "testing":
229                 print "**WARNING About to remove from the testing suite!"
230                 print "There's no need to do this normally as removals from unstable will"
231                 print "propogate to testing automagically."
232                 game_over()
233
234     # Additional architecture checks
235     if Options["Architecture"] and check_source:
236         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
237
238     # Additional component processing
239     over_con_components = con_components.replace("c.id", "component")
240
241     # Don't do dependency checks on multiple suites
242     if Options["Rdep-Check"] and len(suites) > 1:
243         utils.fubar("Reverse dependency check on multiple suites is not implemented.")
244
245     to_remove = []
246     maintainers = {}
247
248     # We have 3 modes of package selection: binary, source-only, binary-only
249     # and source+binary.
250
251     # XXX: TODO: This all needs converting to use placeholders or the object
252     #            API. It's an SQL injection dream at the moment
253
254     if Options["Binary"]:
255         # Removal by binary package name
256         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, files_archive_map af, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND af.file_id = f.id AND af.archive_id = su.archive_id AND af.component_id = c.id %s %s %s %s" % (con_packages, con_suites, con_components, con_architectures))
257         to_remove.extend(q)
258     else:
259         # Source-only
260         if not Options["Binary-Only"]:
261             q = session.execute("SELECT s.source, s.version, 'source', s.id, s.maintainer FROM source s, src_associations sa, suite su, archive, files f, files_archive_map af, component c WHERE sa.source = s.id AND sa.suite = su.id AND archive.id = su.archive_id AND s.file = f.id AND af.file_id = f.id AND af.archive_id = su.archive_id AND af.component_id = c.id %s %s %s" % (con_packages, con_suites, con_components))
262             to_remove.extend(q)
263         if not Options["Source-Only"]:
264             # Source + Binary
265             q = session.execute("""
266                     SELECT b.package, b.version, a.arch_string, b.id, b.maintainer
267                     FROM binaries b
268                          JOIN bin_associations ba ON b.id = ba.bin
269                          JOIN architecture a ON b.architecture = a.id
270                          JOIN suite su ON ba.suite = su.id
271                          JOIN archive ON archive.id = su.archive_id
272                          JOIN files_archive_map af ON b.file = af.file_id AND af.archive_id = archive.id
273                          JOIN component c ON af.component_id = c.id
274                          JOIN source s ON b.source = s.id
275                          JOIN src_associations sa ON s.id = sa.source AND sa.suite = su.id
276                     WHERE TRUE %s %s %s %s""" % (con_packages, con_suites, con_components, con_architectures))
277             to_remove.extend(q)
278
279     if not to_remove:
280         print "Nothing to do."
281         sys.exit(0)
282
283     # If we don't have a reason; spawn an editor so the user can add one
284     # Write the rejection email out as the <foo>.reason file
285     if not Options["Reason"] and not Options["No-Action"]:
286         (fd, temp_filename) = utils.temp_filename()
287         editor = os.environ.get("EDITOR","vi")
288         result = os.system("%s %s" % (editor, temp_filename))
289         if result != 0:
290             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
291         temp_file = utils.open_file(temp_filename)
292         for line in temp_file.readlines():
293             Options["Reason"] += line
294         temp_file.close()
295         os.unlink(temp_filename)
296
297     # Generate the summary of what's to be removed
298     d = {}
299     for i in to_remove:
300         package = i[0]
301         version = i[1]
302         architecture = i[2]
303         maintainer = i[4]
304         maintainers[maintainer] = ""
305         if not d.has_key(package):
306             d[package] = {}
307         if not d[package].has_key(version):
308             d[package][version] = []
309         if architecture not in d[package][version]:
310             d[package][version].append(architecture)
311
312     maintainer_list = []
313     for maintainer_id in maintainers.keys():
314         maintainer_list.append(get_maintainer(maintainer_id).name)
315     summary = ""
316     removals = d.keys()
317     removals.sort()
318     versions = []
319     for package in removals:
320         versions = d[package].keys()
321         versions.sort(apt_pkg.version_compare)
322         for version in versions:
323             d[package][version].sort(utils.arch_compare_sw)
324             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
325     print "Will remove the following packages from %s:" % (suites_list)
326     print
327     print summary
328     print "Maintainer: %s" % ", ".join(maintainer_list)
329     if Options["Done"]:
330         print "Will also close bugs: "+Options["Done"]
331     if carbon_copy:
332         print "Will also send CCs to: " + ", ".join(carbon_copy)
333     if Options["Do-Close"]:
334         print "Will also close associated bug reports."
335     print
336     print "------------------- Reason -------------------"
337     print Options["Reason"]
338     print "----------------------------------------------"
339     print
340
341     if Options["Rdep-Check"]:
342         arches = utils.split_args(Options["Architecture"])
343         reverse_depends_check(removals, suites[0], arches, session)
344
345     # If -n/--no-action, drop out here
346     if Options["No-Action"]:
347         sys.exit(0)
348
349     print "Going to remove the packages now."
350     game_over()
351
352     whoami = utils.whoami()
353     date = commands.getoutput('date -R')
354
355     # Log first; if it all falls apart I want a record that we at least tried.
356     logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
357     logfile.write("=========================================================================\n")
358     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
359     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
360     if Options["Done"]:
361         logfile.write("Closed bugs: %s\n" % (Options["Done"]))
362     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
363     logfile.write("----------------------------------------------\n")
364
365     # Do the same in rfc822 format
366     logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
367     logfile822.write("Date: %s\n" % date)
368     logfile822.write("Ftpmaster: %s\n" % whoami)
369     logfile822.write("Suite: %s\n" % suites_list)
370     sources = []
371     binaries = []
372     for package in summary.split("\n"):
373         for row in package.split("\n"):
374             element = row.split("|")
375             if len(element) == 3:
376                 if element[2].find("source") > 0:
377                     sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
378                     element[2] = sub("source\s?,?", "", element[2]).strip(" ")
379                 if element[2]:
380                     binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
381     if sources:
382         logfile822.write("Sources:\n")
383         for source in sources:
384             logfile822.write(" %s\n" % source)
385     if binaries:
386         logfile822.write("Binaries:\n")
387         for binary in binaries:
388             logfile822.write(" %s\n" % binary)
389     logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
390     if Options["Done"]:
391         logfile822.write("Bug: %s\n" % Options["Done"])
392
393     dsc_type_id = get_override_type('dsc', session).overridetype_id
394     deb_type_id = get_override_type('deb', session).overridetype_id
395
396     # Do the actual deletion
397     print "Deleting...",
398     sys.stdout.flush()
399
400     for i in to_remove:
401         package = i[0]
402         architecture = i[2]
403         package_id = i[3]
404         for suite_id in suite_ids_list:
405             if architecture == "source":
406                 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
407                                 {'packageid': package_id, 'suiteid': suite_id})
408                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
409             else:
410                 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
411                                 {'packageid': package_id, 'suiteid': suite_id})
412                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
413             # Delete from the override file
414             if not Options["Partial"]:
415                 if architecture == "source":
416                     type_id = dsc_type_id
417                 else:
418                     type_id = deb_type_id
419                 # TODO: Again, fix this properly to remove the remaining non-bind argument
420                 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})
421     session.commit()
422     print "done."
423
424     # If we don't have a Bug server configured, we're done
425     if not cnf.has_key("Dinstall::BugServer"):
426         if Options["Done"] or Options["Do-Close"]:
427             print "Cannot send mail to BugServer as Dinstall::BugServer is not configured"
428
429         logfile.write("=========================================================================\n")
430         logfile.close()
431
432         logfile822.write("\n")
433         logfile822.close()
434
435         return
436
437     # read common subst variables for all bug closure mails
438     Subst_common = {}
439     Subst_common["__RM_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
440     Subst_common["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
441     Subst_common["__CC__"] = "X-DAK: dak rm"
442     if carbon_copy:
443         Subst_common["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
444     Subst_common["__SUITE_LIST__"] = suites_list
445     Subst_common["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
446     Subst_common["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
447     Subst_common["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
448     Subst_common["__WHOAMI__"] = whoami
449
450     # Send the bug closing messages
451     if Options["Done"]:
452         Subst_close_rm = Subst_common
453         bcc = []
454         if cnf.find("Dinstall::Bcc") != "":
455             bcc.append(cnf["Dinstall::Bcc"])
456         if cnf.find("Rm::Bcc") != "":
457             bcc.append(cnf["Rm::Bcc"])
458         if bcc:
459             Subst_close_rm["__BCC__"] = "Bcc: " + ", ".join(bcc)
460         else:
461             Subst_close_rm["__BCC__"] = "X-Filler: 42"
462         summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
463         summarymail += "----------------------------------------------\n"
464         Subst_close_rm["__SUMMARY__"] = summarymail
465
466         for bug in utils.split_args(Options["Done"]):
467             Subst_close_rm["__BUG_NUMBER__"] = bug
468             if Options["Do-Close"]:
469                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close-with-related")
470             else:
471                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close")
472             utils.send_mail(mail_message, whitelists=whitelists)
473
474     # close associated bug reports
475     if Options["Do-Close"]:
476         Subst_close_other = Subst_common
477         bcc = []
478         wnpp = utils.parse_wnpp_bug_file()
479         versions = list(set([re_bin_only_nmu.sub('', v) for v in versions]))
480         if len(versions) == 1:
481             Subst_close_other["__VERSION__"] = versions[0]
482         else:
483             utils.fubar("Closing bugs with multiple package versions is not supported.  Do it yourself.")
484         if bcc:
485             Subst_close_other["__BCC__"] = "Bcc: " + ", ".join(bcc)
486         else:
487             Subst_close_other["__BCC__"] = "X-Filler: 42"
488         # at this point, I just assume, that the first closed bug gives
489         # some useful information on why the package got removed
490         Subst_close_other["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
491         if len(sources) == 1:
492             source_pkg = source.split("_", 1)[0]
493         else:
494             utils.fubar("Closing bugs for multiple source packages is not supported.  Do it yourself.")
495         Subst_close_other["__BUG_NUMBER_ALSO__"] = ""
496         Subst_close_other["__SOURCE__"] = source_pkg
497         merged_bugs = set()
498         other_bugs = bts.get_bugs('src', source_pkg, 'status', 'open', 'status', 'forwarded')
499         if other_bugs:
500             for bugno in other_bugs:
501                 if bugno not in merged_bugs:
502                     for bug in bts.get_status(bugno):
503                         for merged in bug.mergedwith:
504                             other_bugs.remove(merged)
505                             merged_bugs.add(merged)
506             logfile.write("Also closing bug(s):")
507             logfile822.write("Also-Bugs:")
508             for bug in other_bugs:
509                 Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
510                 logfile.write(" " + str(bug))
511                 logfile822.write(" " + str(bug))
512             logfile.write("\n")
513             logfile822.write("\n")
514         if source_pkg in wnpp.keys():
515             logfile.write("Also closing WNPP bug(s):")
516             logfile822.write("Also-WNPP:")
517             for bug in wnpp[source_pkg]:
518                 # the wnpp-rm file we parse also contains our removal
519                 # bugs, filtering that out
520                 if bug != Subst_close_other["__BUG_NUMBER__"]:
521                     Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
522                     logfile.write(" " + str(bug))
523                     logfile822.write(" " + str(bug))
524             logfile.write("\n")
525             logfile822.write("\n")
526
527         mail_message = utils.TemplateSubst(Subst_close_other,cnf["Dir::Templates"]+"/rm.bug-close-related")
528         if Subst_close_other["__BUG_NUMBER_ALSO__"]:
529             utils.send_mail(mail_message)
530
531
532     logfile.write("=========================================================================\n")
533     logfile.close()
534
535     logfile822.write("\n")
536     logfile822.close()
537
538 #######################################################################################
539
540 if __name__ == '__main__':
541     main()