]> git.decadent.org.uk Git - dak.git/blob - melanie
2004-04-01 James Troup <james@nocrew.org> * utils.py (temp_filename): new helper...
[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.40 2004-04-01 17:13:11 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
51 ################################################################################
52
53 Cnf = None;
54 projectB = None;
55
56 ################################################################################
57
58 def usage (exit_code=0):
59     print """Usage: melanie [OPTIONS] PACKAGE[...]
60 Remove PACKAGE(s) from suite(s).
61
62   -a, --architecture=ARCH    only act on this architecture
63   -b, --binary               remove binaries only
64   -c, --component=COMPONENT  act on this component
65   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
66   -d, --done=BUG#            send removal message as closure to bug#
67   -h, --help                 show this help and exit
68   -m, --reason=MSG           reason for removal
69   -n, --no-action            don't do anything
70   -p, --partial              don't affect override files
71   -s, --suite=SUITE          act on this suite
72   -S, --source-only          remove source only
73
74 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
75     --architecture=m68k,i386"""
76
77     sys.exit(exit_code)
78
79 ################################################################################
80
81 # "Hudson: What that's great, that's just fucking great man, now what
82 #  the fuck are we supposed to do? We're in some real pretty shit now
83 #  man...That's it man, game over man, game over, man! Game over! What
84 #  the fuck are we gonna do now? What are we gonna do?"
85
86 def game_over():
87     answer = utils.our_raw_input("Continue (y/N)? ").lower();
88     if answer != "y":
89         print "Aborted."
90         sys.exit(1);
91
92 ################################################################################
93
94 def main ():
95     global Cnf, projectB;
96
97     Cnf = utils.get_conf()
98
99     Arguments = [('h',"help","Melanie::Options::Help"),
100                  ('a',"architecture","Melanie::Options::Architecture", "HasArg"),
101                  ('b',"binary", "Melanie::Options::Binary-Only"),
102                  ('c',"component", "Melanie::Options::Component", "HasArg"),
103                  ('C',"carbon-copy", "Melanie::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
104                  ('d',"done","Melanie::Options::Done", "HasArg"), # Bugs fixed
105                  ('m',"reason", "Melanie::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
106                  ('n',"no-action","Melanie::Options::No-Action"),
107                  ('p',"partial", "Melanie::Options::Partial"),
108                  ('s',"suite","Melanie::Options::Suite", "HasArg"),
109                  ('S',"source-only", "Melanie::Options::Source-Only"),
110                  ];
111
112     for i in ["help", "architecture", "binary-only", "component", "carbon-copy", "done", "reason", "no-action", "partial", "source-only" ]:
113         if not Cnf.has_key("Melanie::Options::%s" % (i)):
114             Cnf["Melanie::Options::%s" % (i)] = "";
115     if not Cnf.has_key("Melanie::Options::Suite"):
116         Cnf["Melanie::Options::Suite"] = "unstable";
117
118     arguments = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
119     Options = Cnf.SubTree("Melanie::Options")
120
121     if Options["Help"]:
122         usage();
123
124     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
125     db_access.init(Cnf, projectB);
126
127     # Sanity check options
128     if not arguments:
129         utils.fubar("need at least one package name as an argument.");
130     if Options["Architecture"] and Options["Source-Only"]:
131         utils.fubar("can't use -a/--architecutre and -S/--source-only options simultaneously.");
132     if Options["Binary-Only"] and Options["Source-Only"]:
133         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.");
134     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
135         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.");
136     if Options["Architecture"] and not Options["Partial"]:
137         utils.warn("-a/--architecture implies -p/--partial.");
138         Options["Partial"] = "true";
139
140     # Force the admin to tell someone if we're not doing a rene-led removal
141     # (or closing a bug, which counts as telling someone).
142     if not Options["Carbon-Copy"] and not Options["Done"] \
143        and Options["Reason"].find("[rene]") == -1:
144         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a rene-led removal.");
145
146     # Process -C/--carbon-copy
147     #
148     # Accept 3 types of arguments (space separated):
149     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
150     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
151     #  3) contains a '@' - assumed to be an email address, used unmofidied
152     #
153     carbon_copy = [];
154     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
155         if utils.str_isnum(copy_to):
156             carbon_copy.append(copy_to + "@" + Cnf["Dinstall::BugServer"]);
157         elif copy_to == 'package':
158             for package in arguments:
159                 carbon_copy.append(package + "@" + Cnf["Dinstall::PackagesServer"]);
160                 if Cnf.has_key("Dinstall::TrackingServer"):
161                     carbon_copy.append(package + "@" + Cnf["Dinstall::TrackingServer"]);
162         elif '@' in copy_to:
163             carbon_copy.append(copy_to);
164         else:
165             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to));
166
167     if Options["Binary-Only"]:
168         field = "b.package";
169     else:
170         field = "s.source";
171     con_packages = "AND %s IN (%s)" % (field, ", ".join(map(repr, arguments)));
172
173     (con_suites, con_architectures, con_components, check_source) = \
174                  utils.parse_args(Options);
175
176     # Additional suite checks
177     suite_ids_list = [];
178     suites = utils.split_args(Options["Suite"]);
179     suites_list = utils.join_with_commas_and(suites);
180     if not Options["No-Action"]:
181         for suite in suites:
182             suite_id = db_access.get_suite_id(suite);
183             if suite_id != -1:
184                 suite_ids_list.append(suite_id);
185             if suite == "stable":
186                 print "**WARNING** About to remove from the stable suite!"
187                 print "This should only be done just prior to a (point) release and not at"
188                 print "any other time."
189                 game_over();
190             elif suite == "testing":
191                 print "**WARNING About to remove from the testing suite!"
192                 print "There's no need to do this normally as removals from unstable will"
193                 print "propogate to testing automagically."
194                 game_over();
195
196     # Additional architecture checks
197     if Options["Architecture"] and check_source:
198         utils.warn("'source' in -a/--argument makes no sense and is ignored.");
199
200     # Additional component processing
201     over_con_components = con_components.replace("c.id", "component");
202
203     print "Working...",
204     sys.stdout.flush();
205     to_remove = [];
206     maintainers = {};
207
208     # We have 3 modes of package selection: binary-only, source-only
209     # and source+binary.  The first two are trivial and obvious; the
210     # latter is a nasty mess, but very nice from a UI perspective so
211     # we try to support it.
212
213     if Options["Binary-Only"]:
214         # Binary-only
215         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));
216         for i in q.getresult():
217             to_remove.append(i);
218     else:
219         # Source-only
220         source_packages = {};
221         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));
222         for i in q.getresult():
223             source_packages[i[2]] = i[:2];
224             to_remove.append(i[2:]);
225         if not Options["Source-Only"]:
226             # Source + Binary
227             binary_packages = {};
228             # First get a list of binary package names we suspect are linked to the source
229             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));
230             for i in q.getresult():
231                 binary_packages[i[0]] = "";
232             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
233             for i in source_packages.keys():
234                 filename = "/".join(source_packages[i]);
235                 try:
236                     dsc = utils.parse_changes(filename);
237                 except utils.cant_open_exc:
238                     utils.warn("couldn't open '%s'." % (filename));
239                     continue;
240                 for package in dsc.get("binary").split(','):
241                     package = package.strip();
242                     binary_packages[package] = "";
243             # Then for each binary package: find any version in
244             # unstable, check the Source: field in the deb matches our
245             # source package and if so add it to the list of packages
246             # to be removed.
247             for package in binary_packages.keys():
248                 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));
249                 for i in q.getresult():
250                     filename = "/".join(i[:2]);
251                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
252                     source = control.Find("Source", control.Find("Package"));
253                     source = re_strip_source_version.sub('', source);
254                     if source_packages.has_key(source):
255                         to_remove.append(i[2:]);
256     print "done."
257
258     if not to_remove:
259         print "Nothing to do."
260         sys.exit(0);
261
262     # If we don't have a reason; spawn an editor so the user can add one
263     # Write the rejection email out as the <foo>.reason file
264     if not Options["Reason"] and not Options["No-Action"]:
265         temp_filename = utils.temp_filename();
266         editor = os.environ.get("EDITOR","vi")
267         result = os.system("%s %s" % (editor, temp_filename))
268         if result != 0:
269             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
270         file = utils.open_file(temp_filename);
271         for line in file.readlines():
272             Options["Reason"] += line;
273         os.unlink(temp_filename);
274
275     # Generate the summary of what's to be removed
276     d = {};
277     for i in to_remove:
278         package = i[0];
279         version = i[1];
280         architecture = i[2];
281         maintainer = i[4];
282         maintainers[maintainer] = "";
283         if not d.has_key(package):
284             d[package] = {};
285         if not d[package].has_key(version):
286             d[package][version] = [];
287         if architecture not in d[package][version]:
288             d[package][version].append(architecture);
289
290     maintainer_list = [];
291     for maintainer_id in maintainers.keys():
292         maintainer_list.append(db_access.get_maintainer(maintainer_id));
293     summary = "";
294     packages = d.keys();
295     packages.sort();
296     for package in packages:
297         versions = d[package].keys();
298         versions.sort(apt_pkg.VersionCompare);
299         for version in versions:
300             d[package][version].sort(utils.arch_compare_sw);
301             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]));
302     print "Will remove the following packages from %s:" % (suites_list);
303     print
304     print summary
305     print "Maintainer: %s" % ", ".join(maintainer_list)
306     if Options["Done"]:
307         print "Will also close bugs: "+Options["Done"];
308     if carbon_copy:
309         print "Will also send CCs to: " + ", ".join(carbon_copy)
310     print
311     print "------------------- Reason -------------------"
312     print Options["Reason"];
313     print "----------------------------------------------"
314     print
315
316     # If -n/--no-action, drop out here
317     if Options["No-Action"]:
318         sys.exit(0);
319
320     game_over();
321
322     whoami = utils.whoami();
323     date = commands.getoutput('date -R');
324
325     # Log first; if it all falls apart I want a record that we at least tried.
326     logfile = utils.open_file(Cnf["Melanie::LogFile"], 'a');
327     logfile.write("=========================================================================\n");
328     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami));
329     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary));
330     if Options["Done"]:
331         logfile.write("Closed bugs: %s\n" % (Options["Done"]));
332     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]));
333     logfile.write("----------------------------------------------\n");
334     logfile.flush();
335
336     dsc_type_id = db_access.get_override_type_id('dsc');
337     deb_type_id = db_access.get_override_type_id('deb');
338
339     # Do the actual deletion
340     print "Deleting...",
341     sys.stdout.flush();
342     projectB.query("BEGIN WORK");
343     for i in to_remove:
344         package = i[0];
345         architecture = i[2];
346         package_id = i[3];
347         for suite_id in suite_ids_list:
348             if architecture == "source":
349                 projectB.query("DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id));
350                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id);
351             else:
352                 projectB.query("DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id));
353                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id);
354             # Delete from the override file
355             if not Options["Partial"]:
356                 if architecture == "source":
357                     type_id = dsc_type_id;
358                 else:
359                     type_id = deb_type_id;
360                 projectB.query("DELETE FROM override WHERE package = '%s' AND type = %s AND suite = %s %s" % (package, type_id, suite_id, over_con_components));
361     projectB.query("COMMIT WORK");
362     print "done."
363
364     # Send the bug closing messages
365     if Options["Done"]:
366         Subst = {};
367         Subst["__MELANIE_ADDRESS__"] = Cnf["Melanie::MyEmailAddress"];
368         Subst["__BUG_SERVER__"] = Cnf["Dinstall::BugServer"];
369         bcc = [];
370         if Cnf.Find("Dinstall::Bcc") != "":
371             bcc.append(Cnf["Dinstall::Bcc"]);
372         if Cnf.Find("Melanie::Bcc") != "":
373             bcc.append(Cnf["Melanie::Bcc"]);
374         if bcc:
375             Subst["__BCC__"] = "Bcc: " + ", ".join(bcc);
376         else:
377             Subst["__BCC__"] = "X-Filler: 42";
378         Subst["__CC__"] = "X-Katie: melanie $Revision: 1.40 $";
379         if carbon_copy:
380             Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy);
381         Subst["__SUITE_LIST__"] = suites_list;
382         Subst["__SUMMARY__"] = summary;
383         Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"];
384         Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"];
385         Subst["__WHOAMI__"] = whoami;
386         whereami = utils.where_am_i();
387         Archive = Cnf.SubTree("Archive::%s" % (whereami));
388         Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"];
389         Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"];
390         for bug in utils.split_args(Options["Done"]):
391             Subst["__BUG_NUMBER__"] = bug;
392             mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/melanie.bug-close");
393             utils.send_mail(mail_message);
394
395     logfile.write("=========================================================================\n");
396     logfile.close();
397
398 #######################################################################################
399
400 if __name__ == '__main__':
401     main()
402