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