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