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