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