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