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