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