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