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