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