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