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