]> git.decadent.org.uk Git - dak.git/blob - melanie
use whoami in utils
[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.13 2001-04-13 20:13:30 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         utils.fubar("need at least one package name as an argument.");
83     if Options["Architecture"] and Options["Source-Only"]:
84         utils.fubar("can't use -a/--architecutre and -S/--source-only options simultaneously.");
85     if Options["Binary-Only"] and Options["Source-Only"]:
86         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.");
87     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
88         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.");
89     if Options["Architecture"] and not Options["Partial"]:
90         utils.warn("-a/--architecture implies -p/--partial.");
91         Options["Partial"] = "true";
92
93     # Process -C/--carbon-copy
94     #
95     # Accept 3 types of arguments (space separated):
96     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
97     #  2) the keyword 'package' - cc's $arch@packages.debian.org for every argument
98     #  3) contains a '@' - assumed to be an email address, used unmofidied
99     #
100     carbon_copy = ""
101     for copy_to in string.split(Options.get("Carbon-Copy")):
102         if utils.str_isnum(copy_to):
103             carbon_copy = carbon_copy + copy_to + "@" + Cnf["Dinstall::BugServer"] + ", "
104         elif copy_to == 'package':
105             for package in arguments:
106                 carbon_copy = carbon_copy + package + "@" + Cnf["Dinstall::PackagesServer"] + ", "
107         elif '@' in copy_to:
108             carbon_copy = carbon_copy + copy_to + ", "
109         else:
110             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to));
111     # Make it a real email header
112     if carbon_copy != "":
113         carbon_copy = "Cc: " + carbon_copy[:-2] + '\n'
114
115     packages = {};
116     if Options["Binary-Only"]:
117         field = "b.package";
118     else:
119         field = "s.source";
120     con_packages = "AND (";
121     for package in arguments:
122         con_packages = con_packages + "%s = '%s' OR " % (field, package)
123         packages[package] = "";
124     con_packages = con_packages[:-3] + ")"
125
126     suites_list = "";
127     suite_ids_list = [];
128     con_suites = "AND (";
129     for suite in string.split(Options["Suite"]):
130         
131         if not Options["No-Action"] and suite == "stable":
132             print "**WARNING** About to remove from the stable suite!"
133             print "This should only be done just prior to a (point) release and not at"
134             print "any other time."
135             game_over();
136         elif not Options["No-Action"] and suite == "testing":
137             print "**WARNING About to remove from the testing suite!"
138             print "There's no need to do this normally as removals from unstable will"
139             print "propogate to testing automagically."
140             game_over();
141             
142         suite_id = db_access.get_suite_id(suite);
143         if suite_id == -1:
144             utils.warn("suite '%s' not recognised." % (suite));
145         else:
146             con_suites = con_suites + "su.id = %s OR " % (suite_id)
147
148         suites_list = suites_list + suite + ", "
149         suite_ids_list.append(suite_id);
150     con_suites = con_suites[:-3] + ")"
151     suites_list = suites_list[:-2];
152
153     if Options["Component"]:
154         con_components = "AND (";
155         over_con_components = "AND (";
156         for component in string.split(Options["Component"]):
157             component_id = db_access.get_component_id(component);
158             if component_id == -1:
159                 utils.warn("component '%s' not recognised." % (component));
160             else:
161                 con_components = con_components + "c.id = %s OR " % (component_id);
162                 over_con_components = over_con_components + "component = %s OR " % (component_id);
163         con_components = con_components[:-3] + ")"
164         over_con_components = over_con_components[:-3] + ")";
165     else:
166         con_components = "";    
167         over_con_components = "";
168
169     if Options["Architecture"]:
170         con_architectures = "AND (";
171         for architecture in string.split(Options["Architecture"]):
172             architecture_id = db_access.get_architecture_id(architecture);
173             if architecture_id == -1:
174                 utils.warn("architecture '%s' not recognised." % (architecture));
175             else:
176                 con_architectures = con_architectures + "a.id = %s OR " % (architecture_id)
177         con_architectures = con_architectures[:-3] + ")"
178     else:
179         con_architectures = "";
180
181
182     print "Working...",
183     sys.stdout.flush();
184     to_remove = [];
185     maintainers = {};
186
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, 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));
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, 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));
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                     utils.warn("couldn't open '%s'." % (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, 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));
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             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
249         file = utils.open_file(temp_filename, 'r');
250         for line in file.readlines():
251             Options["Reason"] = Options["Reason"] + line;
252         os.unlink(temp_filename);
253
254     # Generate the summary of what's to be removed
255     d = {};
256     for i in to_remove:
257         package = i[0];
258         version = i[1];
259         architecture = i[2];
260         maintainer = i[4];
261         maintainers[maintainer] = "";
262         if not d.has_key(package):
263             d[package] = {};
264         if not d[package].has_key(version):
265             d[package][version] = [];
266         d[package][version].append(architecture);
267
268     maintainer_list = "Maintainer: "
269     for maintainer_id in maintainers.keys():
270         maintainer_list = maintainer_list + db_access.get_maintainer(maintainer_id) + ", ";
271     maintainer_list = maintainer_list[:-2];
272
273     summary = "";
274     packages = d.keys();
275     packages.sort();
276     for package in packages:
277         versions = d[package].keys();
278         versions.sort();
279         for version in versions:
280             summary = summary + "%10s | %10s | " % (package, version);
281             for architecture in d[package][version]:
282                 summary = "%s%s, " % (summary, architecture);
283             summary = summary[:-2] + '\n';
284
285     print "Will remove the following packages from %s:" % (suites_list);
286     print
287     print summary
288     print maintainer_list
289     if Options["Done"]:
290         print "Will also close bugs: "+Options["Done"];
291     if carbon_copy:
292         print "Will also "+carbon_copy[:-1]
293     print
294     print "------------------- Reason -------------------"
295     print Options["Reason"];
296     print "----------------------------------------------"
297     print
298
299     # If -n/--no-action, drop out here
300     if Options["No-Action"]:
301         sys.exit(0);
302         
303     game_over();
304
305     whoami = utils.whoami();
306     date = commands.getoutput('date -R');
307
308     # Log first; if it all falls apart I want a record that we at least tried.
309     logfile = utils.open_file(Cnf["Melanie::LogFile"], 'a');
310     logfile.write("=========================================================================\n");
311     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami));
312     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary));
313     if Options["Done"]:
314         logfile.write("Closed bugs: %s\n" % (Options["Done"]));
315     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]));
316     logfile.write("----------------------------------------------\n");
317     logfile.flush();
318         
319     dsc_type_id = db_access.get_override_type_id('dsc');
320     deb_type_id = db_access.get_override_type_id('deb');
321     
322     # Do the actual deletion
323     print "Deleting...",
324     sys.stdout.flush();
325     projectB.query("BEGIN WORK");
326     for i in to_remove:
327         package = i[0];
328         architecture = i[2];
329         package_id = i[3];
330         for suite_id in suite_ids_list:
331             if architecture == "source":
332                 projectB.query("DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id));
333                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id);
334             else:
335                 projectB.query("DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id));
336                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id);
337             # Delete from the override file
338             if not Options["Partial"]:
339                 if architecture == "source":
340                     type_id = dsc_type_id;
341                 else:
342                     type_id = deb_type_id;
343                 projectB.query("DELETE FROM override WHERE package = '%s' AND type = %s AND suite = %s %s" % (package, type_id, suite_id, over_con_components));
344     projectB.query("COMMIT WORK");
345     print "done."
346
347     # Send the bug closing messages
348     if Options["Done"]:
349         Subst = {};
350         Subst["__MELANIE_ADDRESS__"] = Cnf["Melanie::MyEmailAddress"];
351         Subst["__BUG_SERVER__"] = Cnf["Dinstall::BugServer"];
352         bcc = "";
353         if Cnf.Find("Dinstall::Bcc") != "":
354             bcc = bcc + Cnf["Dinstall::Bcc"] + ", ";
355         if Cnf.Find("Melanie::Bcc") != "":
356             bcc = bcc + Cnf["Melanie::Bcc"] + ", ";
357         if bcc == "":
358             bcc = "X-Filler: 42" + ", ";
359         else:
360             bcc = "Bcc: " + bcc;
361         Subst["__BCC__"] = bcc[:-2];
362         Subst["__CC__"] = "X-Melanie: $Revision: 1.13 $\n" + carbon_copy[:-1];
363         Subst["__SUITE_LIST__"] = suites_list;
364         Subst["__SUMMARY__"] = summary;
365         Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"];
366         Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"];
367         Subst["__WHOAMI__"] = whoami;
368         whereami = utils.where_am_i();
369         Archive = Cnf.SubTree("Archive::%s" % (whereami));
370         Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"];
371         Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"];
372         for bug in string.split(Options["Done"]):
373             Subst["__BUG_NUMBER__"] = bug;
374             mail_message = utils.TemplateSubst(Subst,open(Cnf["Dir::TemplatesDir"]+"/melanie.bug-close","r").read());
375             utils.send_mail (mail_message, "")
376             
377     logfile.write("=========================================================================\n");
378     logfile.close();
379
380 #######################################################################################
381
382 if __name__ == '__main__':
383     main()
384