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