]> git.decadent.org.uk Git - dak.git/blob - kelly
2005-01-14 Anthony Towns <ajt@debian.org> * kelly: when UNACCEPTing, don't double...
[dak.git] / kelly
1 #!/usr/bin/env python
2
3 # Installs Debian packages from queue/accepted into the pool
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004  James Troup <james@nocrew.org>
5 # $Id: kelly,v 1.15 2005-01-14 14:07:17 ajt 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 ###############################################################################
22
23 #    Cartman: "I'm trying to make the best of a bad situation, I don't
24 #              need to hear crap from a bunch of hippy freaks living in
25 #              denial.  Screw you guys, I'm going home."
26 #
27 #    Kyle: "But Cartman, we're trying to..."
28 #
29 #    Cartman: "uhh.. screw you guys... home."
30
31 ###############################################################################
32
33 import errno, fcntl, os, sys, time;
34 import apt_pkg;
35 import db_access, katie, logging, utils;
36
37 ###############################################################################
38
39 # Globals
40 kelly_version = "$Revision: 1.15 $";
41
42 Cnf = None;
43 Options = None;
44 Logger = None;
45 Urgency_Logger = None;
46 projectB = None;
47 Katie = None;
48 pkg = None;
49
50 reject_message = "";
51 changes = None;
52 dsc = None;
53 dsc_files = None;
54 files = None;
55 Subst = None;
56
57 install_count = 0;
58 install_bytes = 0.0;
59
60 installing_to_stable = 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");
73         # Create the log directory if it doesn't exist
74         self.log_dir = Cnf["Dir::UrgencyLog"];
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(" ".join([source, version, urgency])+'\n');
86         self.log_file.flush();
87         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 += prefix + str + "\n";
105
106 # Recheck anything that relies on the database; since that's not
107 # frozen between accept and our run time.
108
109 def check():
110     for file in files.keys():
111         # The .orig.tar.gz can disappear out from under us is it's a
112         # duplicate of one in the archive.
113         if not files.has_key(file):
114             continue;
115         # Check that the source still exists
116         if files[file]["type"] == "deb":
117             source_version = files[file]["source version"];
118             source_package = files[file]["source package"];
119             if not changes["architecture"].has_key("source") \
120                and not Katie.source_exists(source_package, source_version,  changes["distribution"].keys()):
121                 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
122
123         # Version and file overwrite checks
124         if not installing_to_stable:
125             if files[file]["type"] == "deb":
126                 reject(Katie.check_binary_against_db(file), "");
127             elif files[file]["type"] == "dsc":
128                 reject(Katie.check_source_against_db(file), "");
129                 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
130                 reject(reject_msg, "");
131
132         # Check the package is still in the override tables
133         for suite in changes["distribution"].keys():
134             if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
135                 reject("%s is NEW for %s." % (file, suite));
136
137 ###############################################################################
138
139 def init():
140     global Cnf, Options, Katie, projectB, changes, dsc, dsc_files, files, pkg, Subst;
141
142     Cnf = utils.get_conf()
143
144     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
145                  ('h',"help","Dinstall::Options::Help"),
146                  ('n',"no-action","Dinstall::Options::No-Action"),
147                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
148                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
149                  ('V',"version","Dinstall::Options::Version")];
150
151     for i in ["automatic", "help", "no-action", "no-lock", "no-mail", "version"]:
152         if not Cnf.has_key("Dinstall::Options::%s" % (i)):
153             Cnf["Dinstall::Options::%s" % (i)] = "";
154
155     changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
156     Options = Cnf.SubTree("Dinstall::Options")
157
158     if Options["Help"]:
159         usage();
160
161     if Options["Version"]:
162         print "kelly %s" % (kelly_version);
163         sys.exit(0);
164
165     Katie = katie.Katie(Cnf);
166     projectB = Katie.projectB;
167
168     changes = Katie.pkg.changes;
169     dsc = Katie.pkg.dsc;
170     dsc_files = Katie.pkg.dsc_files;
171     files = Katie.pkg.files;
172     pkg = Katie.pkg;
173     Subst = Katie.Subst;
174
175     return changes_files;
176
177 ###############################################################################
178
179 def usage (exit_code=0):
180     print """Usage: kelly [OPTION]... [CHANGES]...
181   -a, --automatic           automatic run
182   -h, --help                show this help and exit.
183   -n, --no-action           don't do anything
184   -p, --no-lock             don't check lockfile !! for cron.daily only !!
185   -s, --no-mail             don't send any mail
186   -V, --version             display the version number and exit"""
187     sys.exit(exit_code)
188
189 ###############################################################################
190
191 def action ():
192     (summary, short_summary) = Katie.build_summaries();
193
194     (prompt, answer) = ("", "XXX")
195     if Options["No-Action"] or Options["Automatic"]:
196         answer = 'S'
197
198     if reject_message.find("Rejected") != -1:
199         print "REJECT\n" + reject_message,;
200         prompt = "[R]eject, Skip, Quit ?";
201         if Options["Automatic"]:
202             answer = 'R';
203     else:
204         print "INSTALL\n" + reject_message + summary,;
205         prompt = "[I]nstall, Skip, Quit ?";
206         if Options["Automatic"]:
207             answer = 'I';
208
209     while prompt.find(answer) == -1:
210         answer = utils.our_raw_input(prompt);
211         m = katie.re_default_answer.match(prompt);
212         if answer == "":
213             answer = m.group(1);
214         answer = answer[:1].upper();
215
216     if answer == 'R':
217         do_reject ();
218     elif answer == 'I':
219         if not installing_to_stable:
220             install();
221         else:
222             stable_install(summary, short_summary);
223     elif answer == 'Q':
224         sys.exit(0)
225
226 ###############################################################################
227
228 # Our reject is not really a reject, but an unaccept, but since a) the
229 # code for that is non-trivial (reopen bugs, unannounce etc.), b) this
230 # should be exteremly rare, for now we'll go with whining at our admin
231 # folks...
232
233 def do_reject ():
234     Subst["__REJECTOR_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"];
235     Subst["__REJECT_MESSAGE__"] = reject_message;
236     Subst["__CC__"] = "Cc: " + Cnf["Dinstall::MyEmailAddress"];
237     reject_mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/kelly.unaccept");
238
239     # Write the rejection email out as the <foo>.reason file
240     reason_filename = os.path.basename(pkg.changes_file[:-8]) + ".reason";
241     reject_filename = Cnf["Dir::Queue::Reject"] + '/' + reason_filename;
242     # If we fail here someone is probably trying to exploit the race
243     # so let's just raise an exception ...
244     if os.path.exists(reject_filename):
245         os.unlink(reject_filename);
246     fd = os.open(reject_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0644);
247     os.write(fd, reject_mail_message);
248     os.close(fd);
249
250     utils.send_mail(reject_mail_message);
251     Logger.log(["unaccepted", pkg.changes_file]);
252
253 ###############################################################################
254
255 def install ():
256     global install_count, install_bytes;
257
258     print "Installing."
259
260     Logger.log(["installing changes",pkg.changes_file]);
261
262     # Begin a transaction; if we bomb out anywhere between here and the COMMIT WORK below, the DB will not be changed.
263     projectB.query("BEGIN WORK");
264
265     # Add the .dsc file to the DB
266     for file in files.keys():
267         if files[file]["type"] == "dsc":
268             package = dsc["source"]
269             version = dsc["version"]  # NB: not files[file]["version"], that has no epoch
270             maintainer = dsc["maintainer"]
271             maintainer = maintainer.replace("'", "\\'")
272             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
273             fingerprint_id = db_access.get_or_set_fingerprint_id(dsc["fingerprint"]);
274             install_date = time.strftime("%Y-%m-%d");
275             filename = files[file]["pool name"] + file;
276             dsc_component = files[file]["component"];
277             dsc_location_id = files[file]["location id"];
278             if not files[file].has_key("files id") or not files[file]["files id"]:
279                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], dsc_location_id)
280             projectB.query("INSERT INTO source (source, version, maintainer, file, install_date, sig_fpr) VALUES ('%s', '%s', %d, %d, '%s', %s)"
281                            % (package, version, maintainer_id, files[file]["files id"], install_date, fingerprint_id));
282
283             for suite in changes["distribution"].keys():
284                 suite_id = db_access.get_suite_id(suite);
285                 projectB.query("INSERT INTO src_associations (suite, source) VALUES (%d, currval('source_id_seq'))" % (suite_id))
286
287             # Add the source files to the DB (files and dsc_files)
288             projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files[file]["files id"]));
289             for dsc_file in dsc_files.keys():
290                 filename = files[file]["pool name"] + dsc_file;
291                 # If the .orig.tar.gz is already in the pool, it's
292                 # files id is stored in dsc_files by check_dsc().
293                 files_id = dsc_files[dsc_file].get("files id", None);
294                 if files_id == None:
295                     files_id = db_access.get_files_id(filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
296                 # FIXME: needs to check for -1/-2 and or handle exception
297                 if files_id == None:
298                     files_id = db_access.set_files_id (filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
299                 projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files_id));
300
301     # Add the .deb files to the DB
302     for file in files.keys():
303         if files[file]["type"] == "deb":
304             package = files[file]["package"]
305             version = files[file]["version"]
306             maintainer = files[file]["maintainer"]
307             maintainer = maintainer.replace("'", "\\'")
308             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
309             fingerprint_id = db_access.get_or_set_fingerprint_id(changes["fingerprint"]);
310             architecture = files[file]["architecture"]
311             architecture_id = db_access.get_architecture_id (architecture);
312             type = files[file]["dbtype"];
313             source = files[file]["source package"]
314             source_version = files[file]["source version"];
315             filename = files[file]["pool name"] + file;
316             if not files[file].has_key("location id") or not files[file]["location id"]:
317                 files[file]["location id"] = db_access.get_location_id(Cnf["Dir::Pool"],files[file]["component"],utils.where_am_i());
318             if not files[file].has_key("files id") or not files[file]["files id"]:
319                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
320             source_id = db_access.get_source_id (source, source_version);
321             if source_id:
322                 projectB.query("INSERT INTO binaries (package, version, maintainer, source, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, %d, '%s', %d)"
323                                % (package, version, maintainer_id, source_id, architecture_id, files[file]["files id"], type, fingerprint_id));
324             else:
325                 projectB.query("INSERT INTO binaries (package, version, maintainer, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, '%s', %d)"
326                                % (package, version, maintainer_id, architecture_id, files[file]["files id"], type, fingerprint_id));
327             for suite in changes["distribution"].keys():
328                 suite_id = db_access.get_suite_id(suite);
329                 projectB.query("INSERT INTO bin_associations (suite, bin) VALUES (%d, currval('binaries_id_seq'))" % (suite_id));
330
331     # If the .orig.tar.gz is in a legacy directory we need to poolify
332     # it, so that apt-get source (and anything else that goes by the
333     # "Directory:" field in the Sources.gz file) works.
334     orig_tar_id = Katie.pkg.orig_tar_id;
335     orig_tar_location = Katie.pkg.orig_tar_location;
336     legacy_source_untouchable = Katie.pkg.legacy_source_untouchable;
337     if orig_tar_id and orig_tar_location == "legacy":
338         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));
339         qd = q.dictresult();
340         for qid in qd:
341             # Is this an old upload superseded by a newer -sa upload?  (See check_dsc() for details)
342             if legacy_source_untouchable.has_key(qid["files_id"]):
343                 continue;
344             # First move the files to the new location
345             legacy_filename = qid["path"] + qid["filename"];
346             pool_location = utils.poolify (changes["source"], files[file]["component"]);
347             pool_filename = pool_location + os.path.basename(qid["filename"]);
348             destination = Cnf["Dir::Pool"] + pool_location
349             utils.move(legacy_filename, destination);
350             # Then Update the DB's files table
351             q = projectB.query("UPDATE files SET filename = '%s', location = '%s' WHERE id = '%s'" % (pool_filename, dsc_location_id, qid["files_id"]));
352
353     # If this is a sourceful diff only upload that is moving non-legacy
354     # cross-component we need to copy the .orig.tar.gz into the new
355     # component too for the same reasons as above.
356     #
357     if changes["architecture"].has_key("source") and orig_tar_id and \
358        orig_tar_location != "legacy" and orig_tar_location != dsc_location_id:
359         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));
360         ql = q.getresult()[0];
361         old_filename = ql[0] + ql[1];
362         file_size = ql[2];
363         file_md5sum = ql[3];
364         new_filename = utils.poolify(changes["source"], dsc_component) + os.path.basename(old_filename);
365         new_files_id = db_access.get_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
366         if new_files_id == None:
367             utils.copy(old_filename, Cnf["Dir::Pool"] + new_filename);
368             new_files_id = db_access.set_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
369             projectB.query("UPDATE dsc_files SET file = %s WHERE source = %s AND file = %s" % (new_files_id, source_id, orig_tar_id));
370
371     # Install the files into the pool
372     for file in files.keys():
373         destination = Cnf["Dir::Pool"] + files[file]["pool name"] + file;
374         utils.move(file, destination);
375         Logger.log(["installed", file, files[file]["type"], files[file]["size"], files[file]["architecture"]]);
376         install_bytes += float(files[file]["size"]);
377
378     # Copy the .changes file across for suite which need it.
379     copy_changes = {};
380     copy_katie = {};
381     for suite in changes["distribution"].keys():
382         if Cnf.has_key("Suite::%s::CopyChanges" % (suite)):
383             copy_changes[Cnf["Suite::%s::CopyChanges" % (suite)]] = "";
384         # and the .katie file...
385         if Cnf.has_key("Suite::%s::CopyKatie" % (suite)):
386             copy_katie[Cnf["Suite::%s::CopyKatie" % (suite)]] = "";
387     for dest in copy_changes.keys():
388         utils.copy(pkg.changes_file, Cnf["Dir::Root"] + dest);
389     for dest in copy_katie.keys():
390         utils.copy(Katie.pkg.changes_file[:-8]+".katie", dest);
391
392     projectB.query("COMMIT WORK");
393
394     # Move the .changes into the 'done' directory
395     utils.move (pkg.changes_file,
396                 os.path.join(Cnf["Dir::Queue::Done"], os.path.basename(pkg.changes_file)));
397
398     # Remove the .katie file
399     os.unlink(Katie.pkg.changes_file[:-8]+".katie");
400
401     if changes["architecture"].has_key("source") and Urgency_Logger:
402         Urgency_Logger.log(dsc["source"], dsc["version"], changes["urgency"]);
403
404     # Undo the work done in katie.py(accept) to help auto-building
405     # from accepted.
406     projectB.query("BEGIN WORK");
407     for suite in changes["distribution"].keys():
408         if suite not in Cnf.ValueList("Dinstall::AcceptedAutoBuildSuites"):
409             continue;
410         now_date = time.strftime("%Y-%m-%d %H:%M");
411         suite_id = db_access.get_suite_id(suite);
412         dest_dir = Cnf["Dir::AcceptedAutoBuild"];
413         if Cnf.FindB("Dinstall::SecurityAcceptedAutoBuild"):
414             dest_dir = os.path.join(dest_dir, suite);
415         for file in files.keys():
416             dest = os.path.join(dest_dir, file);
417             # Remove it from the list of packages for later processing by apt-ftparchive
418             projectB.query("UPDATE accepted_autobuild SET in_accepted = 'f', last_used = '%s' WHERE filename = '%s' AND suite = %s" % (now_date, dest, suite_id));
419             if not Cnf.FindB("Dinstall::SecurityAcceptedAutoBuild"):
420                 # Update the symlink to point to the new location in the pool
421                 pool_location = utils.poolify (changes["source"], files[file]["component"]);
422                 src = os.path.join(Cnf["Dir::Pool"], pool_location, os.path.basename(file));
423                 if os.path.islink(dest):
424                     os.unlink(dest);
425                 os.symlink(src, dest);
426         # Update last_used on any non-upload .orig.tar.gz symlink
427         if orig_tar_id:
428             # Determine the .orig.tar.gz file name
429             for dsc_file in dsc_files.keys():
430                 if dsc_file.endswith(".orig.tar.gz"):
431                     orig_tar_gz = os.path.join(dest_dir, dsc_file);
432             # Remove it from the list of packages for later processing by apt-ftparchive
433             projectB.query("UPDATE accepted_autobuild SET in_accepted = 'f', last_used = '%s' WHERE filename = '%s' AND suite = %s" % (now_date, orig_tar_gz, suite_id));
434     projectB.query("COMMIT WORK");
435
436     # Finally...
437     install_count += 1;
438
439 ################################################################################
440
441 def stable_install (summary, short_summary):
442     global install_count;
443
444     print "Installing to stable.";
445
446     # Begin a transaction; if we bomb out anywhere between here and
447     # the COMMIT WORK below, the DB won't be changed.
448     projectB.query("BEGIN WORK");
449
450     # Add the source to stable (and remove it from proposed-updates)
451     for file in files.keys():
452         if files[file]["type"] == "dsc":
453             package = dsc["source"];
454             version = dsc["version"];  # NB: not files[file]["version"], that has no epoch
455             q = projectB.query("SELECT id FROM source WHERE source = '%s' AND version = '%s'" % (package, version))
456             ql = q.getresult();
457             if not ql:
458                 utils.fubar("[INTERNAL ERROR] couldn't find '%s' (%s) in source table." % (package, version));
459             source_id = ql[0][0];
460             suite_id = db_access.get_suite_id('proposed-updates');
461             projectB.query("DELETE FROM src_associations WHERE suite = '%s' AND source = '%s'" % (suite_id, source_id));
462             suite_id = db_access.get_suite_id('stable');
463             projectB.query("INSERT INTO src_associations (suite, source) VALUES ('%s', '%s')" % (suite_id, source_id));
464
465     # Add the binaries to stable (and remove it/them from proposed-updates)
466     for file in files.keys():
467         if files[file]["type"] == "deb":
468             package = files[file]["package"];
469             version = files[file]["version"];
470             architecture = files[file]["architecture"];
471             q = projectB.query("SELECT b.id FROM binaries b, architecture a WHERE b.package = '%s' AND b.version = '%s' AND (a.arch_string = '%s' OR a.arch_string = 'all') AND b.architecture = a.id" % (package, version, architecture));
472             ql = q.getresult();
473             if not ql:
474                 utils.fubar("[INTERNAL ERROR] couldn't find '%s' (%s for %s architecture) in binaries table." % (package, version, architecture));
475             binary_id = ql[0][0];
476             suite_id = db_access.get_suite_id('proposed-updates');
477             projectB.query("DELETE FROM bin_associations WHERE suite = '%s' AND bin = '%s'" % (suite_id, binary_id));
478             suite_id = db_access.get_suite_id('stable');
479             projectB.query("INSERT INTO bin_associations (suite, bin) VALUES ('%s', '%s')" % (suite_id, binary_id));
480
481     projectB.query("COMMIT WORK");
482
483     utils.move (pkg.changes_file, Cnf["Dir::Morgue"] + '/katie/' + os.path.basename(pkg.changes_file));
484
485     ## Update the Stable ChangeLog file
486     new_changelog_filename = Cnf["Dir::Root"] + Cnf["Suite::Stable::ChangeLogBase"] + ".ChangeLog";
487     changelog_filename = Cnf["Dir::Root"] + Cnf["Suite::Stable::ChangeLogBase"] + "ChangeLog";
488     if os.path.exists(new_changelog_filename):
489         os.unlink (new_changelog_filename);
490
491     new_changelog = utils.open_file(new_changelog_filename, 'w');
492     for file in files.keys():
493         if files[file]["type"] == "deb":
494             new_changelog.write("stable/%s/binary-%s/%s\n" % (files[file]["component"], files[file]["architecture"], file));
495         elif utils.re_issource.match(file):
496             new_changelog.write("stable/%s/source/%s\n" % (files[file]["component"], file));
497         else:
498             new_changelog.write("%s\n" % (file));
499     chop_changes = katie.re_fdnic.sub("\n", changes["changes"]);
500     new_changelog.write(chop_changes + '\n\n');
501     if os.access(changelog_filename, os.R_OK) != 0:
502         changelog = utils.open_file(changelog_filename);
503         new_changelog.write(changelog.read());
504     new_changelog.close();
505     if os.access(changelog_filename, os.R_OK) != 0:
506         os.unlink(changelog_filename);
507     utils.move(new_changelog_filename, changelog_filename);
508
509     install_count += 1;
510
511     if not Options["No-Mail"] and changes["architecture"].has_key("source"):
512         Subst["__SUITE__"] = " into stable";
513         Subst["__SUMMARY__"] = summary;
514         mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/kelly.installed");
515         utils.send_mail(mail_message);
516         Katie.announce(short_summary, 1)
517
518     # Finally remove the .katie file
519     katie_file = os.path.join(Cnf["Suite::Proposed-Updates::CopyKatie"], os.path.basename(Katie.pkg.changes_file[:-8]+".katie"));
520     os.unlink(katie_file);
521
522 ################################################################################
523
524 def process_it (changes_file):
525     global reject_message;
526
527     reject_message = "";
528
529     # Absolutize the filename to avoid the requirement of being in the
530     # same directory as the .changes file.
531     pkg.changes_file = os.path.abspath(changes_file);
532
533     # And since handling of installs to stable munges with the CWD;
534     # save and restore it.
535     pkg.directory = os.getcwd();
536
537     if installing_to_stable:
538         old = Katie.pkg.changes_file;
539         Katie.pkg.changes_file = os.path.basename(old);
540         os.chdir(Cnf["Suite::Proposed-Updates::CopyKatie"]);
541
542     Katie.init_vars();
543     Katie.update_vars();
544     Katie.update_subst();
545
546     if installing_to_stable:
547         Katie.pkg.changes_file = old;
548
549     check();
550     action();
551
552     # Restore CWD
553     os.chdir(pkg.directory);
554
555 ###############################################################################
556
557 def main():
558     global projectB, Logger, Urgency_Logger, installing_to_stable;
559
560     changes_files = init();
561
562     # -n/--dry-run invalidates some other options which would involve things happening
563     if Options["No-Action"]:
564         Options["Automatic"] = "";
565
566     # Check that we aren't going to clash with the daily cron job
567
568     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
569         utils.fubar("Archive maintenance in progress.  Try again later.");
570
571     # If running from within proposed-updates; assume an install to stable
572     if os.getcwd().find('proposed-updates') != -1:
573         installing_to_stable = 1;
574
575     # Obtain lock if not in no-action mode and initialize the log
576     if not Options["No-Action"]:
577         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
578         try:
579             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB);
580         except IOError, e:
581             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
582                 utils.fubar("Couldn't obtain lock; assuming another kelly is already running.");
583             else:
584                 raise;
585         Logger = Katie.Logger = logging.Logger(Cnf, "kelly");
586         if not installing_to_stable and Cnf.get("Dir::UrgencyLog"):
587             Urgency_Logger = Urgency_Log(Cnf);
588
589     # Initialize the substitution template mapping global
590     bcc = "X-Katie: %s" % (kelly_version);
591     if Cnf.has_key("Dinstall::Bcc"):
592         Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
593     else:
594         Subst["__BCC__"] = bcc;
595
596     # Sort the .changes files so that we process sourceful ones first
597     changes_files.sort(utils.changes_compare);
598
599     # Process the changes files
600     for changes_file in changes_files:
601         print "\n" + changes_file;
602         process_it (changes_file);
603
604     if install_count:
605         sets = "set"
606         if install_count > 1:
607             sets = "sets"
608         sys.stderr.write("Installed %d package %s, %s.\n" % (install_count, sets, utils.size_type(int(install_bytes))));
609         Logger.log(["total",install_count,install_bytes]);
610
611     if not Options["No-Action"]:
612         Logger.close();
613         if Urgency_Logger:
614             Urgency_Logger.close();
615
616 ###############################################################################
617
618 if __name__ == '__main__':
619     main();