]> git.decadent.org.uk Git - dak.git/blob - dak/process_accepted.py
check keyring uids for uploader address before adding presumed sponsor to recipient
[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 src_uploaders to the DB
313             if dsc.get("dm-upload-allowed", "no") == "yes":
314                 uploader_ids = [maintainer_id]
315                 if dsc.has_key("uploaders"):
316                     for u in dsc["uploaders"].split(","):
317                         u = u.replace("'", "\\'")
318                         u = u.strip()
319                         uploader_ids.append(
320                             daklib.database.get_or_set_maintainer_id(u))
321                 added_ids = {}
322                 for u in uploader_ids:
323                     if added_ids.has_key(u):
324                         daklib.utils.warn("Already saw uploader %s for source %s" % (u, package))
325                         continue
326                     added_ids[u]=1
327                     projectB.query("INSERT INTO src_uploaders (source, maintainer) VALUES (currval('source_id_seq'), %d)" % (u))
328
329
330     # Add the .deb files to the DB
331     for file in files.keys():
332         if files[file]["type"] == "deb":
333             package = files[file]["package"]
334             version = files[file]["version"]
335             maintainer = files[file]["maintainer"]
336             maintainer = maintainer.replace("'", "\\'")
337             maintainer_id = daklib.database.get_or_set_maintainer_id(maintainer)
338             fingerprint_id = daklib.database.get_or_set_fingerprint_id(changes["fingerprint"])
339             architecture = files[file]["architecture"]
340             architecture_id = daklib.database.get_architecture_id (architecture)
341             type = files[file]["dbtype"]
342             source = files[file]["source package"]
343             source_version = files[file]["source version"]
344             filename = files[file]["pool name"] + file
345             if not files[file].has_key("location id") or not files[file]["location id"]:
346                 files[file]["location id"] = daklib.database.get_location_id(Cnf["Dir::Pool"],files[file]["component"],daklib.utils.where_am_i())
347             if not files[file].has_key("files id") or not files[file]["files id"]:
348                 files[file]["files id"] = daklib.database.set_files_id (filename, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
349             source_id = daklib.database.get_source_id (source, source_version)
350             if source_id:
351                 projectB.query("INSERT INTO binaries (package, version, maintainer, source, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, %d, '%s', %d)"
352                                % (package, version, maintainer_id, source_id, architecture_id, files[file]["files id"], type, fingerprint_id))
353             else:
354                 projectB.query("INSERT INTO binaries (package, version, maintainer, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, '%s', %d)"
355                                % (package, version, maintainer_id, architecture_id, files[file]["files id"], type, fingerprint_id))
356             for suite in changes["distribution"].keys():
357                 suite_id = daklib.database.get_suite_id(suite)
358                 projectB.query("INSERT INTO bin_associations (suite, bin) VALUES (%d, currval('binaries_id_seq'))" % (suite_id))
359
360     # If the .orig.tar.gz is in a legacy directory we need to poolify
361     # it, so that apt-get source (and anything else that goes by the
362     # "Directory:" field in the Sources.gz file) works.
363     orig_tar_id = Upload.pkg.orig_tar_id
364     orig_tar_location = Upload.pkg.orig_tar_location
365     legacy_source_untouchable = Upload.pkg.legacy_source_untouchable
366     if orig_tar_id and orig_tar_location == "legacy":
367         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))
368         qd = q.dictresult()
369         for qid in qd:
370             # Is this an old upload superseded by a newer -sa upload?  (See check_dsc() for details)
371             if legacy_source_untouchable.has_key(qid["files_id"]):
372                 continue
373             # First move the files to the new location
374             legacy_filename = qid["path"] + qid["filename"]
375             pool_location = daklib.utils.poolify (changes["source"], files[file]["component"])
376             pool_filename = pool_location + os.path.basename(qid["filename"])
377             destination = Cnf["Dir::Pool"] + pool_location
378             daklib.utils.move(legacy_filename, destination)
379             # Then Update the DB's files table
380             q = projectB.query("UPDATE files SET filename = '%s', location = '%s' WHERE id = '%s'" % (pool_filename, dsc_location_id, qid["files_id"]))
381
382     # If this is a sourceful diff only upload that is moving non-legacy
383     # cross-component we need to copy the .orig.tar.gz into the new
384     # component too for the same reasons as above.
385     #
386     if changes["architecture"].has_key("source") and orig_tar_id and \
387        orig_tar_location != "legacy" and orig_tar_location != dsc_location_id:
388         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))
389         ql = q.getresult()[0]
390         old_filename = ql[0] + ql[1]
391         file_size = ql[2]
392         file_md5sum = ql[3]
393         new_filename = daklib.utils.poolify(changes["source"], dsc_component) + os.path.basename(old_filename)
394         new_files_id = daklib.database.get_files_id(new_filename, file_size, file_md5sum, dsc_location_id)
395         if new_files_id == None:
396             daklib.utils.copy(old_filename, Cnf["Dir::Pool"] + new_filename)
397             new_files_id = daklib.database.set_files_id(new_filename, file_size, file_md5sum, dsc_location_id)
398             projectB.query("UPDATE dsc_files SET file = %s WHERE source = %s AND file = %s" % (new_files_id, source_id, orig_tar_id))
399
400     # Install the files into the pool
401     for file in files.keys():
402         destination = Cnf["Dir::Pool"] + files[file]["pool name"] + file
403         daklib.utils.move(file, destination)
404         Logger.log(["installed", file, files[file]["type"], files[file]["size"], files[file]["architecture"]])
405         install_bytes += float(files[file]["size"])
406
407     # Copy the .changes file across for suite which need it.
408     copy_changes = {}
409     copy_dot_dak = {}
410     for suite in changes["distribution"].keys():
411         if Cnf.has_key("Suite::%s::CopyChanges" % (suite)):
412             copy_changes[Cnf["Suite::%s::CopyChanges" % (suite)]] = ""
413         # and the .dak file...
414         if Cnf.has_key("Suite::%s::CopyDotDak" % (suite)):
415             copy_dot_dak[Cnf["Suite::%s::CopyDotDak" % (suite)]] = ""
416     for dest in copy_changes.keys():
417         daklib.utils.copy(pkg.changes_file, Cnf["Dir::Root"] + dest)
418     for dest in copy_dot_dak.keys():
419         daklib.utils.copy(Upload.pkg.changes_file[:-8]+".dak", dest)
420
421     projectB.query("COMMIT WORK")
422
423     # Move the .changes into the 'done' directory
424     daklib.utils.move (pkg.changes_file,
425                 os.path.join(Cnf["Dir::Queue::Done"], os.path.basename(pkg.changes_file)))
426
427     # Remove the .dak file
428     os.unlink(Upload.pkg.changes_file[:-8]+".dak")
429
430     if changes["architecture"].has_key("source") and Urgency_Logger:
431         Urgency_Logger.log(dsc["source"], dsc["version"], changes["urgency"])
432
433     # Undo the work done in queue.py(accept) to help auto-building
434     # from accepted.
435     projectB.query("BEGIN WORK")
436     for suite in changes["distribution"].keys():
437         if suite not in Cnf.ValueList("Dinstall::QueueBuildSuites"):
438             continue
439         now_date = time.strftime("%Y-%m-%d %H:%M")
440         suite_id = daklib.database.get_suite_id(suite)
441         dest_dir = Cnf["Dir::QueueBuild"]
442         if Cnf.FindB("Dinstall::SecurityQueueBuild"):
443             dest_dir = os.path.join(dest_dir, suite)
444         for file in files.keys():
445             dest = os.path.join(dest_dir, file)
446             # Remove it from the list of packages for later processing by apt-ftparchive
447             projectB.query("UPDATE queue_build SET in_queue = 'f', last_used = '%s' WHERE filename = '%s' AND suite = %s" % (now_date, dest, suite_id))
448             if not Cnf.FindB("Dinstall::SecurityQueueBuild"):
449                 # Update the symlink to point to the new location in the pool
450                 pool_location = daklib.utils.poolify (changes["source"], files[file]["component"])
451                 src = os.path.join(Cnf["Dir::Pool"], pool_location, os.path.basename(file))
452                 if os.path.islink(dest):
453                     os.unlink(dest)
454                 os.symlink(src, dest)
455         # Update last_used on any non-upload .orig.tar.gz symlink
456         if orig_tar_id:
457             # Determine the .orig.tar.gz file name
458             for dsc_file in dsc_files.keys():
459                 if dsc_file.endswith(".orig.tar.gz"):
460                     orig_tar_gz = os.path.join(dest_dir, dsc_file)
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, orig_tar_gz, suite_id))
463     projectB.query("COMMIT WORK")
464
465     # Finally...
466     install_count += 1
467
468 ################################################################################
469
470 def stable_install (summary, short_summary):
471     global install_count
472
473     print "Installing to stable."
474
475     # Begin a transaction; if we bomb out anywhere between here and
476     # the COMMIT WORK below, the DB won't be changed.
477     projectB.query("BEGIN WORK")
478
479     # Add the source to stable (and remove it from proposed-updates)
480     for file in files.keys():
481         if files[file]["type"] == "dsc":
482             package = dsc["source"]
483             version = dsc["version"];  # NB: not files[file]["version"], that has no epoch
484             q = projectB.query("SELECT id FROM source WHERE source = '%s' AND version = '%s'" % (package, version))
485             ql = q.getresult()
486             if not ql:
487                 daklib.utils.fubar("[INTERNAL ERROR] couldn't find '%s' (%s) in source table." % (package, version))
488             source_id = ql[0][0]
489             suite_id = daklib.database.get_suite_id('proposed-updates')
490             projectB.query("DELETE FROM src_associations WHERE suite = '%s' AND source = '%s'" % (suite_id, source_id))
491             suite_id = daklib.database.get_suite_id('stable')
492             projectB.query("INSERT INTO src_associations (suite, source) VALUES ('%s', '%s')" % (suite_id, source_id))
493
494     # Add the binaries to stable (and remove it/them from proposed-updates)
495     for file in files.keys():
496         if files[file]["type"] == "deb":
497             package = files[file]["package"]
498             version = files[file]["version"]
499             architecture = files[file]["architecture"]
500             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))
501             ql = q.getresult()
502             if not ql:
503                 daklib.utils.fubar("[INTERNAL ERROR] couldn't find '%s' (%s for %s architecture) in binaries table." % (package, version, architecture))
504
505             binary_id = ql[0][0]
506             suite_id = daklib.database.get_suite_id('proposed-updates')
507             projectB.query("DELETE FROM bin_associations WHERE suite = '%s' AND bin = '%s'" % (suite_id, binary_id))
508             suite_id = daklib.database.get_suite_id('stable')
509             projectB.query("INSERT INTO bin_associations (suite, bin) VALUES ('%s', '%s')" % (suite_id, binary_id))
510
511     projectB.query("COMMIT WORK")
512
513     daklib.utils.move (pkg.changes_file, Cnf["Dir::Morgue"] + '/process-accepted/' + os.path.basename(pkg.changes_file))
514
515     ## Update the Stable ChangeLog file
516     new_changelog_filename = Cnf["Dir::Root"] + Cnf["Suite::Stable::ChangeLogBase"] + ".ChangeLog"
517     changelog_filename = Cnf["Dir::Root"] + Cnf["Suite::Stable::ChangeLogBase"] + "ChangeLog"
518     if os.path.exists(new_changelog_filename):
519         os.unlink (new_changelog_filename)
520
521     new_changelog = daklib.utils.open_file(new_changelog_filename, 'w')
522     for file in files.keys():
523         if files[file]["type"] == "deb":
524             new_changelog.write("stable/%s/binary-%s/%s\n" % (files[file]["component"], files[file]["architecture"], file))
525         elif daklib.utils.re_issource.match(file):
526             new_changelog.write("stable/%s/source/%s\n" % (files[file]["component"], file))
527         else:
528             new_changelog.write("%s\n" % (file))
529     chop_changes = daklib.queue.re_fdnic.sub("\n", changes["changes"])
530     new_changelog.write(chop_changes + '\n\n')
531     if os.access(changelog_filename, os.R_OK) != 0:
532         changelog = daklib.utils.open_file(changelog_filename)
533         new_changelog.write(changelog.read())
534     new_changelog.close()
535     if os.access(changelog_filename, os.R_OK) != 0:
536         os.unlink(changelog_filename)
537     daklib.utils.move(new_changelog_filename, changelog_filename)
538
539     install_count += 1
540
541     if not Options["No-Mail"] and changes["architecture"].has_key("source"):
542         Subst["__SUITE__"] = " into stable"
543         Subst["__SUMMARY__"] = summary
544         mail_message = daklib.utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/process-accepted.install")
545         daklib.utils.send_mail(mail_message)
546         Upload.announce(short_summary, 1)
547
548     # Finally remove the .dak file
549     dot_dak_file = os.path.join(Cnf["Suite::Proposed-Updates::CopyDotDak"], os.path.basename(Upload.pkg.changes_file[:-8]+".dak"))
550     os.unlink(dot_dak_file)
551
552 ################################################################################
553
554 def process_it (changes_file):
555     global reject_message
556
557     reject_message = ""
558
559     # Absolutize the filename to avoid the requirement of being in the
560     # same directory as the .changes file.
561     pkg.changes_file = os.path.abspath(changes_file)
562
563     # And since handling of installs to stable munges with the CWD
564     # save and restore it.
565     pkg.directory = os.getcwd()
566
567     if installing_to_stable:
568         old = Upload.pkg.changes_file
569         Upload.pkg.changes_file = os.path.basename(old)
570         os.chdir(Cnf["Suite::Proposed-Updates::CopyDotDak"])
571
572     Upload.init_vars()
573     Upload.update_vars()
574     Upload.update_subst()
575
576     if installing_to_stable:
577         Upload.pkg.changes_file = old
578
579     check()
580     action()
581
582     # Restore CWD
583     os.chdir(pkg.directory)
584
585 ###############################################################################
586
587 def main():
588     global projectB, Logger, Urgency_Logger, installing_to_stable
589
590     changes_files = init()
591
592     # -n/--dry-run invalidates some other options which would involve things happening
593     if Options["No-Action"]:
594         Options["Automatic"] = ""
595
596     # Check that we aren't going to clash with the daily cron job
597
598     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
599         daklib.utils.fubar("Archive maintenance in progress.  Try again later.")
600
601     # If running from within proposed-updates; assume an install to stable
602     if os.getcwd().find('proposed-updates') != -1:
603         installing_to_stable = 1
604
605     # Obtain lock if not in no-action mode and initialize the log
606     if not Options["No-Action"]:
607         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
608         try:
609             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
610         except IOError, e:
611             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
612                 daklib.utils.fubar("Couldn't obtain lock; assuming another 'dak process-accepted' is already running.")
613             else:
614                 raise
615         Logger = Upload.Logger = daklib.logging.Logger(Cnf, "process-accepted")
616         if not installing_to_stable and Cnf.get("Dir::UrgencyLog"):
617             Urgency_Logger = Urgency_Log(Cnf)
618
619     # Initialize the substitution template mapping global
620     bcc = "X-DAK: dak process-accepted\nX-Katie: $Revision: 1.18 $"
621     if Cnf.has_key("Dinstall::Bcc"):
622         Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"])
623     else:
624         Subst["__BCC__"] = bcc
625
626     # Sort the .changes files so that we process sourceful ones first
627     changes_files.sort(daklib.utils.changes_compare)
628
629     # Process the changes files
630     for changes_file in changes_files:
631         print "\n" + changes_file
632         process_it (changes_file)
633
634     if install_count:
635         sets = "set"
636         if install_count > 1:
637             sets = "sets"
638         sys.stderr.write("Installed %d package %s, %s.\n" % (install_count, sets, daklib.utils.size_type(int(install_bytes))))
639         Logger.log(["total",install_count,install_bytes])
640
641     if not Options["No-Action"]:
642         Logger.close()
643         if Urgency_Logger:
644             Urgency_Logger.close()
645
646 ###############################################################################
647
648 if __name__ == '__main__':
649     main()