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