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