3 # Installs Debian packages
4 # Copyright (C) 2000, 2001 James Troup <james@nocrew.org>
5 # $Id: katie,v 1.69 2002-02-12 23:13:59 troup Exp $
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.
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.
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
21 # Originally based on dinstall by Guy Maor <maor@debian.org>
23 ###############################################################################
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."
29 # Kyle: "But Cartman, we're trying to..."
31 # Cartman: "uhh.. screw you guys... home."
33 ###############################################################################
35 import FCNTL, fcntl, os, string, sys, time;
37 import db_access, katie, logging, utils;
39 ###############################################################################
42 katie_version = "$Revision: 1.69 $";
47 Urgency_Logger = None;
62 ###############################################################################
64 # FIXME: this should go away to some Debian specific file
65 # FIXME: should die if file already exists
68 "Urgency Logger object"
69 def __init__ (self, Cnf):
70 "Initialize a new Urgency Logger object"
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);
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');
83 def log (self, source, version, urgency):
85 self.log_file.write(string.join([source, version, urgency])+'\n');
86 self.log_file.flush();
87 self.writes = self.writes + 1;
90 "Close a Logger object"
91 self.log_file.flush();
92 self.log_file.close();
94 new_filename = "%s/install-urgencies-%s" % (self.log_dir, self.timestamp);
95 utils.move(self.log_filename, new_filename);
97 os.unlink(self.log_filename);
99 ###############################################################################
101 def reject (str, prefix="Rejected: "):
102 global reject_message;
104 reject_message = reject_message + prefix + str + "\n";
106 # Recheck anything that relies on the database; since that's not
107 # frozen between accept and katie's run time.
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));
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));
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);
131 ###############################################################################
134 global Cnf, Options, Katie, projectB, changes, dsc, dsc_files, files, pkg, Subst;
136 Cnf = utils.get_conf()
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")];
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)] = "";
151 changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
152 Options = Cnf.SubTree("Dinstall::Options")
154 Katie = katie.Katie(Cnf);
155 projectB = Katie.projectB;
157 changes = Katie.pkg.changes;
159 dsc_files = Katie.pkg.dsc_files;
160 files = Katie.pkg.files;
164 return changes_files;
166 ###############################################################################
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"""
178 ###############################################################################
181 (summary, short_summary) = Katie.build_summaries();
183 (prompt, answer) = ("", "XXX")
184 if Options["No-Action"] or Options["Automatic"]:
187 if string.find(reject_message, "Rejected") != -1:
188 print "REJECT\n" + reject_message,;
189 prompt = "[R]eject, Skip, Quit ?";
190 if Options["Automatic"]:
193 print "INSTALL\n" + reject_message + summary,;
194 prompt = "[I]nstall, Skip, Quit ?";
195 if Options["Automatic"]:
198 while string.find(prompt, answer) == -1:
200 answer = utils.our_raw_input()
201 m = katie.re_default_answer.match(prompt)
204 answer = string.upper(answer[:1])
213 ###############################################################################
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
221 Subst["__REJECTOR_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"];
222 Subst["__MANUAL_REJECT_MESSAGE__"] = Cnf["Dinstall::MyEmailAddress"];
223 reject_mail_message = utils.TemplateSubst(Subst,utils.open_file(Cnf["Dir::TemplatesDir"]+"/katie.unaccept").read());
225 # Write the rejection email out as the <foo>.reason file
226 reason_filename = 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);
236 utils.send_mail (reject_mail_message, "");
237 Logger.log(["unaccepted", pkg.changes_file]);
239 ###############################################################################
242 global install_count, install_bytes;
246 Logger.log(["installing changes",pkg.changes_file]);
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");
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]["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));
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))
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);
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
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));
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]["files id"]:
303 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
304 source_id = db_access.get_source_id (source, source_version);
306 projectB.query("INSERT INTO binaries (package, version, maintainer, source, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, %d, '%s', %d)"
307 % (package, version, maintainer_id, source_id, architecture_id, files[file]["files id"], type, fingerprint_id));
309 projectB.query("INSERT INTO binaries (package, version, maintainer, architecture, file, type) VALUES ('%s', '%s', %d, %d, %d, '%s', %d)"
310 % (package, version, maintainer_id, architecture_id, files[file]["files id"], type, fingerprint_id));
311 for suite in changes["distribution"].keys():
312 suite_id = db_access.get_suite_id(suite);
313 projectB.query("INSERT INTO bin_associations (suite, bin) VALUES (%d, currval('binaries_id_seq'))" % (suite_id));
315 # If the .orig.tar.gz is in a legacy directory we need to poolify
316 # it, so that apt-get source (and anything else that goes by the
317 # "Directory:" field in the Sources.gz file) works.
318 orig_tar_id = Katie.pkg.orig_tar_id;
319 orig_tar_location = Katie.pkg.orig_tar_location;
320 legacy_source_untouchable = Katie.pkg.legacy_source_untouchable;
321 if orig_tar_id != None and orig_tar_location == "legacy":
322 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 # Is this an old upload superseded by a newer -sa upload? (See check_dsc() for details)
326 if legacy_source_untouchable.has_key(qid["files_id"]):
328 # First move the files to the new location
329 legacy_filename = qid["path"]+qid["filename"];
330 pool_location = utils.poolify (changes["source"], files[file]["component"]);
331 pool_filename = pool_location + os.path.basename(qid["filename"]);
332 destination = Cnf["Dir::PoolDir"] + pool_location
333 utils.move(legacy_filename, destination);
334 # Then Update the DB's files table
335 q = projectB.query("UPDATE files SET filename = '%s', location = '%s' WHERE id = '%s'" % (pool_filename, dsc_location_id, qid["files_id"]));
337 # If this is a sourceful diff only upload that is moving non-legacy
338 # cross-component we need to copy the .orig.tar.gz into the new
339 # component too for the same reasons as above.
341 if changes["architecture"].has_key("source") and orig_tar_id != None and \
342 orig_tar_location != "legacy" and orig_tar_location != dsc_location_id:
343 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));
344 ql = q.getresult()[0];
345 old_filename = ql[0] + ql[1];
348 new_filename = utils.poolify (changes["source"], dsc_component) + os.path.basename(old_filename);
349 new_files_id = db_access.get_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
350 if new_files_id == None:
351 utils.copy(old_filename, Cnf["Dir::PoolDir"] + new_filename);
352 new_files_id = db_access.set_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
353 projectB.query("UPDATE dsc_files SET file = %s WHERE source = %s AND file = %s" % (new_files_id, source_id, orig_tar_id));
355 # Install the files into the pool
356 for file in files.keys():
357 destination = Cnf["Dir::PoolDir"] + files[file]["pool name"] + file
358 utils.move (file, destination)
359 Logger.log(["installed", file, files[file]["type"], files[file]["size"], files[file]["architecture"]]);
360 install_bytes = install_bytes + float(files[file]["size"])
362 # Copy the .changes file across for suite which need it.
363 for suite in changes["distribution"].keys():
364 if Cnf.has_key("Suite::%s::CopyChanges" % (suite)):
365 utils.copy (pkg.changes_file, Cnf["Dir::RootDir"] + Cnf["Suite::%s::CopyChanges" % (suite)]);
367 projectB.query("COMMIT WORK");
369 # Move the .changes into the 'done' directory
371 utils.move (pkg.changes_file, os.path.join(Cnf["Dir::QueueDoneDir"], os.path.basename(pkg.changes_file)));
373 utils.warn("couldn't move changes file '%s' to DONE directory. [Got %s]" % (os.path.basename(pkg.changes_file), sys.exc_type));
375 os.unlink(Katie.pkg.changes_file[:-8]+".katie");
377 if changes["architecture"].has_key("source"):
378 Urgency_Logger.log(dsc["source"], dsc["version"], changes["urgency"]);
380 install_count = install_count + 1;
382 ################################################################################
384 def process_it (changes_file):
385 # Absolutize the filename to avoid the requirement of being in the
386 # same directory as the .changes file.
387 pkg.changes_file = os.path.abspath(changes_file);
389 # And since handling of installs to stable munges with the CWD;
390 # save and restore it.
391 pkg.directory = os.getcwd();
399 os.chdir(pkg.directory);
401 ###############################################################################
404 global projectB, Logger, Urgency_Logger;
406 changes_files = init();
411 if Options["Version"]:
412 print "katie %s" % (katie_version);
415 # -n/--dry-run invalidates some other options which would involve things happening
416 if Options["No-Action"]:
417 Options["Automatic"] = "";
419 # Check that we aren't going to clash with the daily cron job
421 if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::RootDir"])) and not Options["No-Lock"]:
422 utils.fubar("Archive maintenance in progress. Try again later.");
424 # Obtain lock if not in no-action mode and initialize the log
426 if not Options["No-Action"]:
427 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
428 fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
429 Logger = Katie.Logger = logging.Logger(Cnf, "katie");
430 Urgency_Logger = Urgency_Log(Cnf);
432 # Initialize the substitution template mapping global
433 bcc = "X-Katie: %s" % (katie_version);
434 if Cnf.has_key("Dinstall::Bcc"):
435 Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
437 Subst["__BCC__"] = bcc;
438 Subst["__STABLE_REJECTOR__"] = Cnf["Dinstall::StableRejector"];
440 # Sort the .changes files so that we process sourceful ones first
441 changes_files.sort(utils.changes_compare);
443 # Process the changes files
444 for changes_file in changes_files:
445 print "\n" + changes_file;
446 process_it (changes_file);
450 if install_count > 1:
452 sys.stderr.write("Installed %d package %s, %s.\n" % (install_count, sets, utils.size_type(int(install_bytes))));
453 Logger.log(["total",install_count,install_bytes]);
455 if not Options["No-Action"]:
457 Urgency_Logger.close();
459 if __name__ == '__main__':