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