]> git.decadent.org.uk Git - dak.git/blob - katie
sync
[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.70 2002-02-13 02:38:53 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.70 $";
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         print prompt,;
200         answer = utils.our_raw_input()
201         m = katie.re_default_answer.match(prompt)
202         if answer == "":
203             answer = m.group(1)
204         answer = string.upper(answer[:1])
205
206     if answer == 'R':
207         do_reject ();
208     elif answer == 'I':
209         install ();
210     elif answer == 'Q':
211         sys.exit(0)
212
213 ###############################################################################
214
215 # Our reject is not really a reject, but an unaccept, but since a) the
216 # code for that is non-trivial (reopen bugs, unannounce etc.), b) this
217 # should be exteremly rare, for now we'll go with whining at our admin
218 # folks...
219
220 def do_reject ():
221     Subst["__REJECTOR_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"];
222     Subst["__REJECT_MESSAGE__"] = reject_message;
223     Subst["__CC__"] = "Cc: " + Cnf["Dinstall::MyEmailAddress"];
224     reject_mail_message = utils.TemplateSubst(Subst,utils.open_file(Cnf["Dir::TemplatesDir"]+"/katie.unaccept").read());
225
226     # Write the rejection email out as the <foo>.reason file
227     reason_filename = os.path.basename(pkg.changes_file[:-8]) + ".reason";
228     reject_filename = Cnf["Dir::QueueRejectDir"] + '/' + reason_filename;
229     # If we fail here someone is probably trying to exploit the race
230     # so let's just raise an exception ...
231     if os.path.exists(reject_filename):
232         os.unlink(reject_filename);
233     fd = os.open(reject_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0644);
234     os.write(fd, reject_mail_message);
235     os.close(fd);
236
237     utils.send_mail (reject_mail_message, "");
238     Logger.log(["unaccepted", pkg.changes_file]);
239
240 ###############################################################################
241
242 def install ():
243     global install_count, install_bytes;
244
245     print "Installing."
246
247     Logger.log(["installing changes",pkg.changes_file]);
248
249     # Begin a transaction; if we bomb out anywhere between here and the COMMIT WORK below, the DB will not be changed.
250     projectB.query("BEGIN WORK");
251
252     # Add the .dsc file to the DB
253     for file in files.keys():
254         if files[file]["type"] == "dsc":
255             package = dsc["source"]
256             version = dsc["version"]  # NB: not files[file]["version"], that has no epoch
257             maintainer = dsc["maintainer"]
258             maintainer = string.replace(maintainer, "'", "\\'")
259             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
260             fingerprint_id = db_access.get_or_set_fingerprint_id(dsc["fingerprint"]);
261             install_date = time.strftime("%Y-%m-%d", time.localtime(time.time()));
262             filename = files[file]["pool name"] + file;
263             dsc_location_id = files[file]["location id"];
264             if not files[file]["files id"]:
265                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], dsc_location_id)
266             projectB.query("INSERT INTO source (source, version, maintainer, file, install_date, sig_fpr) VALUES ('%s', '%s', %d, %d, '%s', %s)"
267                            % (package, version, maintainer_id, files[file]["files id"], install_date, fingerprint_id));
268
269             for suite in changes["distribution"].keys():
270                 suite_id = db_access.get_suite_id(suite);
271                 projectB.query("INSERT INTO src_associations (suite, source) VALUES (%d, currval('source_id_seq'))" % (suite_id))
272
273             # Add the source files to the DB (files and dsc_files)
274             projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files[file]["files id"]));
275             for dsc_file in dsc_files.keys():
276                 filename = files[file]["pool name"] + dsc_file;
277                 # If the .orig.tar.gz is already in the pool, it's
278                 # files id is stored in dsc_files by check_dsc().
279                 files_id = dsc_files[dsc_file].get("files id", None);
280                 if files_id == None:
281                     files_id = db_access.get_files_id(filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
282                 # FIXME: needs to check for -1/-2 and or handle exception
283                 if files_id == None:
284                     files_id = db_access.set_files_id (filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
285                 projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files_id));
286
287     # Add the .deb files to the DB
288     for file in files.keys():
289         if files[file]["type"] == "deb":
290             package = files[file]["package"]
291             version = files[file]["version"]
292             maintainer = files[file]["maintainer"]
293             maintainer = string.replace(maintainer, "'", "\\'")
294             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
295             fingerprint_id = db_access.get_or_set_fingerprint_id(changes["fingerprint"]);
296             architecture = files[file]["architecture"]
297             architecture_id = db_access.get_architecture_id (architecture);
298             type = files[file]["dbtype"];
299             dsc_component = files[file]["component"]
300             source = files[file]["source package"]
301             source_version = files[file]["source version"];
302             filename = files[file]["pool name"] + file;
303             if not files[file]["files id"]:
304                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
305             source_id = db_access.get_source_id (source, source_version);
306             if source_id:
307                 projectB.query("INSERT INTO binaries (package, version, maintainer, source, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, %d, '%s', %d)"
308                                % (package, version, maintainer_id, source_id, architecture_id, files[file]["files id"], type, fingerprint_id));
309             else:
310                 projectB.query("INSERT INTO binaries (package, version, maintainer, architecture, file, type) VALUES ('%s', '%s', %d, %d, %d, '%s', %d)"
311                                % (package, version, maintainer_id, architecture_id, files[file]["files id"], type, fingerprint_id));
312             for suite in changes["distribution"].keys():
313                 suite_id = db_access.get_suite_id(suite);
314                 projectB.query("INSERT INTO bin_associations (suite, bin) VALUES (%d, currval('binaries_id_seq'))" % (suite_id));
315
316     # If the .orig.tar.gz is in a legacy directory we need to poolify
317     # it, so that apt-get source (and anything else that goes by the
318     # "Directory:" field in the Sources.gz file) works.
319     orig_tar_id = Katie.pkg.orig_tar_id;
320     orig_tar_location = Katie.pkg.orig_tar_location;
321     legacy_source_untouchable = Katie.pkg.legacy_source_untouchable;
322     if orig_tar_id != None and orig_tar_location == "legacy":
323         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));
324         qd = q.dictresult();
325         for qid in qd:
326             # Is this an old upload superseded by a newer -sa upload?  (See check_dsc() for details)
327             if legacy_source_untouchable.has_key(qid["files_id"]):
328                 continue;
329             # First move the files to the new location
330             legacy_filename = qid["path"]+qid["filename"];
331             pool_location = utils.poolify (changes["source"], files[file]["component"]);
332             pool_filename = pool_location + os.path.basename(qid["filename"]);
333             destination = Cnf["Dir::PoolDir"] + pool_location
334             utils.move(legacy_filename, destination);
335             # Then Update the DB's files table
336             q = projectB.query("UPDATE files SET filename = '%s', location = '%s' WHERE id = '%s'" % (pool_filename, dsc_location_id, qid["files_id"]));
337
338     # If this is a sourceful diff only upload that is moving non-legacy
339     # cross-component we need to copy the .orig.tar.gz into the new
340     # component too for the same reasons as above.
341     #
342     if changes["architecture"].has_key("source") and orig_tar_id != None and \
343        orig_tar_location != "legacy" and orig_tar_location != dsc_location_id:
344         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));
345         ql = q.getresult()[0];
346         old_filename = ql[0] + ql[1];
347         file_size = ql[2];
348         file_md5sum = ql[3];
349         new_filename = utils.poolify (changes["source"], dsc_component) + os.path.basename(old_filename);
350         new_files_id = db_access.get_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
351         if new_files_id == None:
352             utils.copy(old_filename, Cnf["Dir::PoolDir"] + new_filename);
353             new_files_id = db_access.set_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
354             projectB.query("UPDATE dsc_files SET file = %s WHERE source = %s AND file = %s" % (new_files_id, source_id, orig_tar_id));
355
356     # Install the files into the pool
357     for file in files.keys():
358         destination = Cnf["Dir::PoolDir"] + files[file]["pool name"] + file
359         utils.move (file, destination)
360         Logger.log(["installed", file, files[file]["type"], files[file]["size"], files[file]["architecture"]]);
361         install_bytes = install_bytes + float(files[file]["size"])
362
363     # Copy the .changes file across for suite which need it.
364     for suite in changes["distribution"].keys():
365         if Cnf.has_key("Suite::%s::CopyChanges" % (suite)):
366             utils.copy (pkg.changes_file, Cnf["Dir::RootDir"] + Cnf["Suite::%s::CopyChanges" % (suite)]);
367
368     projectB.query("COMMIT WORK");
369
370     # Move the .changes into the 'done' directory
371     try:
372         utils.move (pkg.changes_file, os.path.join(Cnf["Dir::QueueDoneDir"], os.path.basename(pkg.changes_file)));
373     except:
374         utils.warn("couldn't move changes file '%s' to DONE directory. [Got %s]" % (os.path.basename(pkg.changes_file), sys.exc_type));
375
376     os.unlink(Katie.pkg.changes_file[:-8]+".katie");
377
378     if changes["architecture"].has_key("source"):
379         Urgency_Logger.log(dsc["source"], dsc["version"], changes["urgency"]);
380
381     install_count = install_count + 1;
382
383 ################################################################################
384
385 def process_it (changes_file):
386     # Absolutize the filename to avoid the requirement of being in the
387     # same directory as the .changes file.
388     pkg.changes_file = os.path.abspath(changes_file);
389
390     # And since handling of installs to stable munges with the CWD;
391     # save and restore it.
392     pkg.directory = os.getcwd();
393
394     Katie.init_vars();
395     Katie.update_vars();
396     Katie.update_subst();
397     check();
398     action();
399
400     # Restore CWD
401     os.chdir(pkg.directory);
402
403 ###############################################################################
404
405 def main():
406     global projectB, Logger, Urgency_Logger;
407
408     changes_files = init();
409
410     if Options["Help"]:
411         usage();
412
413     if Options["Version"]:
414         print "katie %s" % (katie_version);
415         sys.exit(0);
416
417     # -n/--dry-run invalidates some other options which would involve things happening
418     if Options["No-Action"]:
419         Options["Automatic"] = "";
420
421     # Check that we aren't going to clash with the daily cron job
422
423     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::RootDir"])) and not Options["No-Lock"]:
424         utils.fubar("Archive maintenance in progress.  Try again later.");
425
426     # Obtain lock if not in no-action mode and initialize the log
427
428     if not Options["No-Action"]:
429         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
430         fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
431         Logger = Katie.Logger = logging.Logger(Cnf, "katie");
432         Urgency_Logger = Urgency_Log(Cnf);
433
434     # Initialize the substitution template mapping global
435     bcc = "X-Katie: %s" % (katie_version);
436     if Cnf.has_key("Dinstall::Bcc"):
437         Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
438     else:
439         Subst["__BCC__"] = bcc;
440     Subst["__STABLE_REJECTOR__"] = Cnf["Dinstall::StableRejector"];
441
442     # Sort the .changes files so that we process sourceful ones first
443     changes_files.sort(utils.changes_compare);
444
445     # Process the changes files
446     for changes_file in changes_files:
447         print "\n" + changes_file;
448         process_it (changes_file);
449
450     if install_count:
451         sets = "set"
452         if install_count > 1:
453             sets = "sets"
454         sys.stderr.write("Installed %d package %s, %s.\n" % (install_count, sets, utils.size_type(int(install_bytes))));
455         Logger.log(["total",install_count,install_bytes]);
456
457     if not Options["No-Action"]:
458         Logger.close();
459         Urgency_Logger.close();
460
461 if __name__ == '__main__':
462     main()
463