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