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