]> git.decadent.org.uk Git - dak.git/blob - katie
Add CopyKatie support a la CopyChanges
[dak.git] / katie
1 #!/usr/bin/env python
2
3 # Installs Debian packages
4 # Copyright (C) 2000, 2001  James Troup <james@nocrew.org>
5 # $Id: katie,v 1.76 2002-03-31 16:14:48 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 # Originally based on dinstall by Guy Maor <maor@debian.org>
22
23 ###############################################################################
24
25 #    Cartman: "I'm trying to make the best of a bad situation, I don't
26 #              need to hear crap from a bunch of hippy freaks living in
27 #              denial.  Screw you guys, I'm going home."
28 #
29 #    Kyle: "But Cartman, we're trying to..."
30 #
31 #    Cartman: "uhh.. screw you guys... home."
32
33 ###############################################################################
34
35 import FCNTL, fcntl, os, string, sys, time;
36 import apt_pkg;
37 import db_access, katie, logging, utils;
38
39 ###############################################################################
40
41 # Globals
42 katie_version = "$Revision: 1.76 $";
43
44 Cnf = None;
45 Options = None;
46 Logger = None;
47 Urgency_Logger = None;
48 projectB = None;
49 Katie = None;
50 pkg = None;
51
52 reject_message = "";
53 changes = None;
54 dsc = None;
55 dsc_files = None;
56 files = None;
57 Subst = None;
58
59 install_count = 0;
60 install_bytes = 0.0;
61
62 ###############################################################################
63
64 # FIXME: this should go away to some Debian specific file
65 # FIXME: should die if file already exists
66
67 class Urgency_Log:
68     "Urgency Logger object"
69     def __init__ (self, Cnf):
70         "Initialize a new Urgency Logger object"
71         self.Cnf = Cnf;
72         self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()));
73         # Create the log directory if it doesn't exist
74         self.log_dir = Cnf["Dir::UrgencyLogDir"];
75         if not os.path.exists(self.log_dir):
76             umask = os.umask(00000);
77             os.makedirs(self.log_dir, 02775);
78         # Open the logfile
79         self.log_filename = "%s/.install-urgencies-%s.new" % (self.log_dir, self.timestamp);
80         self.log_file = utils.open_file(self.log_filename, 'w');
81         self.writes = 0;
82
83     def log (self, source, version, urgency):
84         "Log an event"
85         self.log_file.write(string.join([source, version, urgency])+'\n');
86         self.log_file.flush();
87         self.writes = self.writes + 1;
88
89     def close (self):
90         "Close a Logger object"
91         self.log_file.flush();
92         self.log_file.close();
93         if self.writes:
94             new_filename = "%s/install-urgencies-%s" % (self.log_dir, self.timestamp);
95             utils.move(self.log_filename, new_filename);
96         else:
97             os.unlink(self.log_filename);
98
99 ###############################################################################
100
101 def reject (str, prefix="Rejected: "):
102     global reject_message;
103     if str:
104         reject_message = reject_message + prefix + str + "\n";
105
106 # Recheck anything that relies on the database; since that's not
107 # frozen between accept and katie's run time.
108
109 def check():
110     for file in files.keys():
111         # Check that the source still exists
112         if files[file]["type"] == "deb":
113             source_version = files[file]["source version"];
114             source_package = files[file]["source package"];
115             if not changes["architecture"].has_key("source") \
116                and not Katie.source_exists(source_package, source_version):
117                 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
118
119         for suite in changes["distribution"].keys():
120             # Check the package is still in the override tables
121             if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
122                 reject("%s is NEW for %s." % (file, suite));
123
124             if files[file]["type"] == "deb":
125                 reject(Katie.check_binaries_against_db(file, suite));
126             elif files[file]["type"] == "dsc":
127                 reject(Katie.check_source_against_db(file));
128                 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
129                 reject(reject_msg);
130
131 ###############################################################################
132
133 def init():
134     global Cnf, Options, Katie, projectB, changes, dsc, dsc_files, files, pkg, Subst;
135
136     Cnf = utils.get_conf()
137
138     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
139                  ('h',"help","Dinstall::Options::Help"),
140                  ('m',"manual-reject","Dinstall::Options::Manual-Reject", "HasArg"),
141                  ('n',"no-action","Dinstall::Options::No-Action"),
142                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
143                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
144                  ('V',"version","Dinstall::Options::Version")];
145
146     for i in ["automatic", "help", "manual-reject", "no-action",
147               "no-lock", "no-mail", "version"]:
148         if not Cnf.has_key("Dinstall::Options::%s" % (i)):
149             Cnf["Dinstall::Options::%s" % (i)] = "";
150
151     changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
152     Options = Cnf.SubTree("Dinstall::Options")
153
154     Katie = katie.Katie(Cnf);
155     projectB = Katie.projectB;
156
157     changes = Katie.pkg.changes;
158     dsc = Katie.pkg.dsc;
159     dsc_files = Katie.pkg.dsc_files;
160     files = Katie.pkg.files;
161     pkg = Katie.pkg;
162     Subst = Katie.Subst;
163
164     return changes_files;
165
166 ###############################################################################
167
168 def usage (exit_code=0):
169     print """Usage: dinstall [OPTION]... [CHANGES]...
170   -a, --automatic           automatic run
171   -h, --help                show this help and exit.
172   -n, --no-action           don't do anything
173   -p, --no-lock             don't check lockfile !! for cron.daily only !!
174   -s, --no-mail             don't send any mail
175   -V, --version             display the version number and exit"""
176     sys.exit(exit_code)
177
178 ###############################################################################
179
180 def action ():
181     (summary, short_summary) = Katie.build_summaries();
182
183     (prompt, answer) = ("", "XXX")
184     if Options["No-Action"] or Options["Automatic"]:
185         answer = 'S'
186
187     if string.find(reject_message, "Rejected") != -1:
188         print "REJECT\n" + reject_message,;
189         prompt = "[R]eject, Skip, Quit ?";
190         if Options["Automatic"]:
191             answer = 'R';
192     else:
193         print "INSTALL\n" + reject_message + summary,;
194         prompt = "[I]nstall, Skip, Quit ?";
195         if Options["Automatic"]:
196             answer = 'I';
197
198     while string.find(prompt, answer) == -1:
199         answer = utils.our_raw_input(prompt);
200         m = katie.re_default_answer.match(prompt);
201         if answer == "":
202             answer = m.group(1);
203         answer = string.upper(answer[:1]);
204
205     if answer == 'R':
206         do_reject ();
207     elif answer == 'I':
208         install ();
209     elif answer == 'Q':
210         sys.exit(0)
211
212 ###############################################################################
213
214 # Our reject is not really a reject, but an unaccept, but since a) the
215 # code for that is non-trivial (reopen bugs, unannounce etc.), b) this
216 # should be exteremly rare, for now we'll go with whining at our admin
217 # folks...
218
219 def do_reject ():
220     Subst["__REJECTOR_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"];
221     Subst["__REJECT_MESSAGE__"] = reject_message;
222     Subst["__CC__"] = "Cc: " + Cnf["Dinstall::MyEmailAddress"];
223     reject_mail_message = utils.TemplateSubst(Subst,utils.open_file(Cnf["Dir::TemplatesDir"]+"/katie.unaccept").read());
224
225     # Write the rejection email out as the <foo>.reason file
226     reason_filename = os.path.basename(pkg.changes_file[:-8]) + ".reason";
227     reject_filename = Cnf["Dir::QueueRejectDir"] + '/' + reason_filename;
228     # If we fail here someone is probably trying to exploit the race
229     # so let's just raise an exception ...
230     if os.path.exists(reject_filename):
231         os.unlink(reject_filename);
232     fd = os.open(reject_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0644);
233     os.write(fd, reject_mail_message);
234     os.close(fd);
235
236     utils.send_mail (reject_mail_message, "");
237     Logger.log(["unaccepted", pkg.changes_file]);
238
239 ###############################################################################
240
241 def install ():
242     global install_count, install_bytes;
243
244     print "Installing."
245
246     Logger.log(["installing changes",pkg.changes_file]);
247
248     # Begin a transaction; if we bomb out anywhere between here and the COMMIT WORK below, the DB will not be changed.
249     projectB.query("BEGIN WORK");
250
251     # Add the .dsc file to the DB
252     for file in files.keys():
253         if files[file]["type"] == "dsc":
254             package = dsc["source"]
255             version = dsc["version"]  # NB: not files[file]["version"], that has no epoch
256             maintainer = dsc["maintainer"]
257             maintainer = string.replace(maintainer, "'", "\\'")
258             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
259             fingerprint_id = db_access.get_or_set_fingerprint_id(dsc["fingerprint"]);
260             install_date = time.strftime("%Y-%m-%d", time.localtime(time.time()));
261             filename = files[file]["pool name"] + file;
262             dsc_location_id = files[file]["location id"];
263             if not files[file].has_key("files id") or not files[file]["files id"]:
264                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], dsc_location_id)
265             projectB.query("INSERT INTO source (source, version, maintainer, file, install_date, sig_fpr) VALUES ('%s', '%s', %d, %d, '%s', %s)"
266                            % (package, version, maintainer_id, files[file]["files id"], install_date, fingerprint_id));
267
268             for suite in changes["distribution"].keys():
269                 suite_id = db_access.get_suite_id(suite);
270                 projectB.query("INSERT INTO src_associations (suite, source) VALUES (%d, currval('source_id_seq'))" % (suite_id))
271
272             # Add the source files to the DB (files and dsc_files)
273             projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files[file]["files id"]));
274             for dsc_file in dsc_files.keys():
275                 filename = files[file]["pool name"] + dsc_file;
276                 # If the .orig.tar.gz is already in the pool, it's
277                 # files id is stored in dsc_files by check_dsc().
278                 files_id = dsc_files[dsc_file].get("files id", None);
279                 if files_id == None:
280                     files_id = db_access.get_files_id(filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
281                 # FIXME: needs to check for -1/-2 and or handle exception
282                 if files_id == None:
283                     files_id = db_access.set_files_id (filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
284                 projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files_id));
285
286     # Add the .deb files to the DB
287     for file in files.keys():
288         if files[file]["type"] == "deb":
289             package = files[file]["package"]
290             version = files[file]["version"]
291             maintainer = files[file]["maintainer"]
292             maintainer = string.replace(maintainer, "'", "\\'")
293             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
294             fingerprint_id = db_access.get_or_set_fingerprint_id(changes["fingerprint"]);
295             architecture = files[file]["architecture"]
296             architecture_id = db_access.get_architecture_id (architecture);
297             type = files[file]["dbtype"];
298             dsc_component = files[file]["component"]
299             source = files[file]["source package"]
300             source_version = files[file]["source version"];
301             filename = files[file]["pool name"] + file;
302             if not files[file].has_key("location id") or not files[file]["location id"]:
303                 files[file]["location id"] = db_access.get_location_id(Cnf["Dir::PoolDir"],files[file]["component"],utils.where_am_i());
304             if not files[file].has_key("files id") or not files[file]["files id"]:
305                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
306             source_id = db_access.get_source_id (source, source_version);
307             if source_id:
308                 projectB.query("INSERT INTO binaries (package, version, maintainer, source, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, %d, '%s', %d)"
309                                % (package, version, maintainer_id, source_id, architecture_id, files[file]["files id"], type, fingerprint_id));
310             else:
311                 projectB.query("INSERT INTO binaries (package, version, maintainer, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, '%s', %d)"
312                                % (package, version, maintainer_id, architecture_id, files[file]["files id"], type, fingerprint_id));
313             for suite in changes["distribution"].keys():
314                 suite_id = db_access.get_suite_id(suite);
315                 projectB.query("INSERT INTO bin_associations (suite, bin) VALUES (%d, currval('binaries_id_seq'))" % (suite_id));
316
317     # If the .orig.tar.gz is in a legacy directory we need to poolify
318     # it, so that apt-get source (and anything else that goes by the
319     # "Directory:" field in the Sources.gz file) works.
320     orig_tar_id = Katie.pkg.orig_tar_id;
321     orig_tar_location = Katie.pkg.orig_tar_location;
322     legacy_source_untouchable = Katie.pkg.legacy_source_untouchable;
323     if orig_tar_id != None and orig_tar_location == "legacy":
324         q = projectB.query("SELECT DISTINCT ON (f.id) l.path, f.filename, f.id as files_id, df.source, df.id as dsc_files_id, f.size, f.md5sum FROM files f, dsc_files df, location l WHERE df.source IN (SELECT source FROM dsc_files WHERE file = %s) AND f.id = df.file AND l.id = f.location AND (l.type = 'legacy' OR l.type = 'legacy-mixed')" % (orig_tar_id));
325         qd = q.dictresult();
326         for qid in qd:
327             # Is this an old upload superseded by a newer -sa upload?  (See check_dsc() for details)
328             if legacy_source_untouchable.has_key(qid["files_id"]):
329                 continue;
330             # First move the files to the new location
331             legacy_filename = qid["path"]+qid["filename"];
332             pool_location = utils.poolify (changes["source"], files[file]["component"]);
333             pool_filename = pool_location + os.path.basename(qid["filename"]);
334             destination = Cnf["Dir::PoolDir"] + pool_location
335             utils.move(legacy_filename, destination);
336             # Then Update the DB's files table
337             q = projectB.query("UPDATE files SET filename = '%s', location = '%s' WHERE id = '%s'" % (pool_filename, dsc_location_id, qid["files_id"]));
338
339     # If this is a sourceful diff only upload that is moving non-legacy
340     # cross-component we need to copy the .orig.tar.gz into the new
341     # component too for the same reasons as above.
342     #
343     if changes["architecture"].has_key("source") and orig_tar_id != None and \
344        orig_tar_location != "legacy" and orig_tar_location != dsc_location_id:
345         q = projectB.query("SELECT l.path, f.filename, f.size, f.md5sum FROM files f, location l WHERE f.id = %s AND f.location = l.id" % (orig_tar_id));
346         ql = q.getresult()[0];
347         old_filename = ql[0] + ql[1];
348         file_size = ql[2];
349         file_md5sum = ql[3];
350         new_filename = utils.poolify(changes["source"], dsc_component) + os.path.basename(old_filename);
351         new_files_id = db_access.get_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
352         if new_files_id == None:
353             utils.copy(old_filename, Cnf["Dir::PoolDir"] + new_filename);
354             new_files_id = db_access.set_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
355             projectB.query("UPDATE dsc_files SET file = %s WHERE source = %s AND file = %s" % (new_files_id, source_id, orig_tar_id));
356
357     # Install the files into the pool
358     for file in files.keys():
359         destination = Cnf["Dir::PoolDir"] + files[file]["pool name"] + file;
360         utils.move(file, destination);
361         Logger.log(["installed", file, files[file]["type"], files[file]["size"], files[file]["architecture"]]);
362         install_bytes = install_bytes + float(files[file]["size"]);
363
364     # Copy the .changes file across for suite which need it.
365     for suite in changes["distribution"].keys():
366         if Cnf.has_key("Suite::%s::CopyChanges" % (suite)):
367             utils.copy(pkg.changes_file, Cnf["Dir::RootDir"] + Cnf["Suite::%s::CopyChanges" % (suite)]);
368         # and the .katie file...
369         if Cnf.has_key("Suite::%s::CopyKatie" % (suite)):
370             utils.copy(Katie.pkg.changes_file[:-8]+".katie", Cnf["Suite::%s::CopyKatie" % (suite)]);
371
372     projectB.query("COMMIT WORK");
373
374     # Move the .changes into the 'done' directory
375     try:
376         utils.move (pkg.changes_file, os.path.join(Cnf["Dir::QueueDoneDir"], os.path.basename(pkg.changes_file)));
377     except:
378         utils.warn("couldn't move changes file '%s' to DONE directory. [Got %s]" % (os.path.basename(pkg.changes_file), sys.exc_type));
379
380     os.unlink(Katie.pkg.changes_file[:-8]+".katie");
381
382     if changes["architecture"].has_key("source"):
383         Urgency_Logger.log(dsc["source"], dsc["version"], changes["urgency"]);
384
385     install_count = install_count + 1;
386
387 ################################################################################
388
389 def process_it (changes_file):
390     global reject_message;
391
392     reject_message = "";
393
394     # Absolutize the filename to avoid the requirement of being in the
395     # same directory as the .changes file.
396     pkg.changes_file = os.path.abspath(changes_file);
397
398     # And since handling of installs to stable munges with the CWD;
399     # save and restore it.
400     pkg.directory = os.getcwd();
401
402     Katie.init_vars();
403     Katie.update_vars();
404     Katie.update_subst();
405     check();
406     action();
407
408     # Restore CWD
409     os.chdir(pkg.directory);
410
411 ###############################################################################
412
413 def main():
414     global projectB, Logger, Urgency_Logger;
415
416     changes_files = init();
417
418     if Options["Help"]:
419         usage();
420
421     if Options["Version"]:
422         print "katie %s" % (katie_version);
423         sys.exit(0);
424
425     # -n/--dry-run invalidates some other options which would involve things happening
426     if Options["No-Action"]:
427         Options["Automatic"] = "";
428
429     # Check that we aren't going to clash with the daily cron job
430
431     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::RootDir"])) and not Options["No-Lock"]:
432         utils.fubar("Archive maintenance in progress.  Try again later.");
433
434     # Obtain lock if not in no-action mode and initialize the log
435
436     if not Options["No-Action"]:
437         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
438         fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
439         Logger = Katie.Logger = logging.Logger(Cnf, "katie");
440         Urgency_Logger = Urgency_Log(Cnf);
441
442     # Initialize the substitution template mapping global
443     bcc = "X-Katie: %s" % (katie_version);
444     if Cnf.has_key("Dinstall::Bcc"):
445         Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
446     else:
447         Subst["__BCC__"] = bcc;
448     Subst["__STABLE_REJECTOR__"] = Cnf["Dinstall::StableRejector"];
449
450     # Sort the .changes files so that we process sourceful ones first
451     changes_files.sort(utils.changes_compare);
452
453     # Process the changes files
454     for changes_file in changes_files:
455         print "\n" + changes_file;
456         process_it (changes_file);
457
458     if install_count:
459         sets = "set"
460         if install_count > 1:
461             sets = "sets"
462         sys.stderr.write("Installed %d package %s, %s.\n" % (install_count, sets, utils.size_type(int(install_bytes))));
463         Logger.log(["total",install_count,install_bytes]);
464
465     if not Options["No-Action"]:
466         Logger.close();
467         Urgency_Logger.close();
468
469 if __name__ == '__main__':
470     main()
471