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