2 # vim:set et ts=4 sw=4:
4 """ Handles packages from policy queues
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2001, 2002, 2003, 2004, 2005, 2006 James Troup <james@nocrew.org>
8 @copyright: 2009 Joerg Jaspert <joerg@debian.org>
9 @copyright: 2009 Frank Lichtenheld <djpig@debian.org>
10 @copyright: 2009 Mark Hymers <mhy@debian.org>
11 @license: GNU General Public License version 2 or later
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 ################################################################################
29 # <mhy> So how do we handle that at the moment?
30 # <stew> Probably incorrectly.
32 ################################################################################
41 from daklib.dbconn import *
42 from daklib import daklog
43 from daklib import utils
44 from daklib.dak_exceptions import CantOpenError, AlreadyLockedError, CantGetLockError
45 from daklib.config import Config
46 from daklib.archive import ArchiveTransaction
47 from daklib.urgencylog import UrgencyLog
49 import daklib.announce
55 ################################################################################
57 def do_comments(dir, srcqueue, opref, npref, line, fn, transaction):
58 session = transaction.session
60 for comm in [ x for x in os.listdir(dir) if x.startswith(opref) ]:
61 lines = open(os.path.join(dir, comm)).readlines()
62 if len(lines) == 0 or lines[0] != line + "\n": continue
64 # If the ACCEPT includes a _<arch> we only accept that .changes.
65 # Otherwise we accept all .changes that start with the given prefix
66 changes_prefix = comm[len(opref):]
67 if changes_prefix.count('_') < 2:
68 changes_prefix = changes_prefix + '_'
70 changes_prefix = changes_prefix + '.changes'
72 # We need to escape "_" as we use it with the LIKE operator (via the
73 # SQLA startwith) later.
74 changes_prefix = changes_prefix.replace("_", r"\_")
76 uploads = session.query(PolicyQueueUpload).filter_by(policy_queue=srcqueue) \
77 .join(PolicyQueueUpload.changes).filter(DBChange.changesname.startswith(changes_prefix)) \
78 .order_by(PolicyQueueUpload.source_id)
79 reason = "".join(lines[1:])
80 actions.extend((u, reason) for u in uploads)
83 newcomm = npref + comm[len(opref):]
84 newcomm = utils.find_next_free(os.path.join(dir, newcomm))
85 transaction.fs.move(os.path.join(dir, comm), newcomm)
89 for u, reason in actions:
90 print("Processing changes file: {0}".format(u.changes.changesname))
91 fn(u, srcqueue, reason, transaction)
93 ################################################################################
95 def try_or_reject(function):
96 def wrapper(upload, srcqueue, comments, transaction):
98 function(upload, srcqueue, comments, transaction)
99 except Exception as e:
100 comments = 'An exception was raised while processing the package:\n{0}\nOriginal comments:\n{1}'.format(traceback.format_exc(), comments)
102 transaction.rollback()
103 real_comment_reject(upload, srcqueue, comments, transaction)
104 except Exception as e:
105 comments = 'In addition an exception was raised while trying to reject the upload:\n{0}\nOriginal rejection:\n{1}'.format(traceback.format_exc(), comments)
106 transaction.rollback()
107 real_comment_reject(upload, srcqueue, comments, transaction, notify=False)
108 if not Options['No-Action']:
112 ################################################################################
115 def comment_accept(upload, srcqueue, comments, transaction):
116 for byhand in upload.byhand:
117 path = os.path.join(srcqueue.path, byhand.filename)
118 if os.path.exists(path):
119 raise Exception('E: cannot ACCEPT upload with unprocessed byhand file {0}'.format(byhand.filename))
124 session = transaction.session
125 changesname = upload.changes.changesname
126 allow_tainted = srcqueue.suite.archive.tainted
128 # We need overrides to get the target component
129 overridesuite = upload.target_suite
130 if overridesuite.overridesuite is not None:
131 overridesuite = session.query(Suite).filter_by(suite_name=overridesuite.overridesuite).one()
133 def binary_component_func(db_binary):
134 override = session.query(Override).filter_by(suite=overridesuite, package=db_binary.package) \
135 .join(OverrideType).filter(OverrideType.overridetype == db_binary.binarytype) \
136 .join(Component).one()
137 return override.component
139 def source_component_func(db_source):
140 override = session.query(Override).filter_by(suite=overridesuite, package=db_source.source) \
141 .join(OverrideType).filter(OverrideType.overridetype == 'dsc') \
142 .join(Component).one()
143 return override.component
145 all_target_suites = [upload.target_suite]
146 all_target_suites.extend([q.suite for q in upload.target_suite.copy_queues])
148 for suite in all_target_suites:
149 if upload.source is not None:
150 transaction.copy_source(upload.source, suite, source_component_func(upload.source), allow_tainted=allow_tainted)
151 for db_binary in upload.binaries:
152 # build queues may miss the source package if this is a binary-only upload
153 if suite != upload.target_suite:
154 transaction.copy_source(db_binary.source, suite, source_component_func(db_binary.source), allow_tainted=allow_tainted)
155 transaction.copy_binary(db_binary, suite, binary_component_func(db_binary), allow_tainted=allow_tainted, extra_archives=[upload.target_suite.archive])
157 # Copy .changes if needed
158 if upload.target_suite.copychanges:
159 src = os.path.join(upload.policy_queue.path, upload.changes.changesname)
160 dst = os.path.join(upload.target_suite.path, upload.changes.changesname)
161 fs.copy(src, dst, mode=upload.target_suite.archive.mode)
163 # Copy upload to Process-Policy::CopyDir
164 # Used on security.d.o to sync accepted packages to ftp-master, but this
165 # should eventually be replaced by something else.
166 copydir = cnf.get('Process-Policy::CopyDir') or None
167 if copydir is not None:
168 mode = upload.target_suite.archive.mode
169 if upload.source is not None:
170 for f in [ df.poolfile for df in upload.source.srcfiles ]:
171 dst = os.path.join(copydir, f.basename)
172 if not os.path.exists(dst):
173 fs.copy(f.fullpath, dst, mode=mode)
175 for db_binary in upload.binaries:
176 f = db_binary.poolfile
177 dst = os.path.join(copydir, f.basename)
178 if not os.path.exists(dst):
179 fs.copy(f.fullpath, dst, mode=mode)
181 src = os.path.join(upload.policy_queue.path, upload.changes.changesname)
182 dst = os.path.join(copydir, upload.changes.changesname)
183 if not os.path.exists(dst):
184 fs.copy(src, dst, mode=mode)
186 if upload.source is not None and not Options['No-Action']:
187 urgency = upload.changes.urgency
188 if urgency not in cnf.value_list('Urgency::Valid'):
189 urgency = cnf['Urgency::Default']
190 UrgencyLog().log(upload.source.source, upload.source.version, urgency)
193 if not Options['No-Action']:
194 Logger.log(["Policy Queue ACCEPT", srcqueue.queue_name, changesname])
196 pu = get_processed_upload(upload)
197 daklib.announce.announce_accept(pu)
199 # TODO: code duplication. Similar code is in process-upload.
200 # Move .changes to done
201 src = os.path.join(upload.policy_queue.path, upload.changes.changesname)
202 now = datetime.datetime.now()
203 donedir = os.path.join(cnf['Dir::Done'], now.strftime('%Y/%m/%d'))
204 dst = os.path.join(donedir, upload.changes.changesname)
205 dst = utils.find_next_free(dst)
206 fs.copy(src, dst, mode=0o644)
208 remove_upload(upload, transaction)
210 ################################################################################
213 def comment_reject(*args):
214 real_comment_reject(*args, manual=True)
216 def real_comment_reject(upload, srcqueue, comments, transaction, notify=True, manual=False):
220 session = transaction.session
221 changesname = upload.changes.changesname
222 queuedir = upload.policy_queue.path
223 rejectdir = cnf['Dir::Reject']
225 ### Copy files to reject/
227 poolfiles = [b.poolfile for b in upload.binaries]
228 if upload.source is not None:
229 poolfiles.extend([df.poolfile for df in upload.source.srcfiles])
231 files = [ af.path for af in session.query(ArchiveFile) \
232 .filter_by(archive=upload.policy_queue.suite.archive) \
233 .join(ArchiveFile.file) \
234 .filter(PoolFile.file_id.in_([ f.file_id for f in poolfiles ])) ]
235 for byhand in upload.byhand:
236 path = os.path.join(queuedir, byhand.filename)
237 if os.path.exists(path):
239 files.append(os.path.join(queuedir, changesname))
242 dst = utils.find_next_free(os.path.join(rejectdir, os.path.basename(fn)))
243 fs.copy(fn, dst, link=True)
247 dst = utils.find_next_free(os.path.join(rejectdir, '{0}.reason'.format(changesname)))
252 ### Send mail notification
258 # Try to use From: from comment file if there is one.
259 # This is not very elegant...
260 match = re.match(r"\AFrom: ([^\n]+)\n\n", comments)
262 rejected_by = match.group(1)
263 reason = '\n'.join(comments.splitlines()[2:])
265 pu = get_processed_upload(upload)
266 daklib.announce.announce_reject(pu, reason, rejected_by)
269 if not Options["No-Action"]:
270 Logger.log(["Policy Queue REJECT", srcqueue.queue_name, upload.changes.changesname])
272 changes = upload.changes
273 remove_upload(upload, transaction)
274 session.delete(changes)
276 ################################################################################
278 def remove_upload(upload, transaction):
280 session = transaction.session
281 changes = upload.changes
283 # Remove byhand and changes files. Binary and source packages will be
284 # removed from {bin,src}_associations and eventually removed by clean-suites automatically.
285 queuedir = upload.policy_queue.path
286 for byhand in upload.byhand:
287 path = os.path.join(queuedir, byhand.filename)
288 if os.path.exists(path):
290 session.delete(byhand)
291 fs.unlink(os.path.join(queuedir, upload.changes.changesname))
293 session.delete(upload)
296 ################################################################################
298 def get_processed_upload(upload):
299 pu = daklib.announce.ProcessedUpload()
301 pu.maintainer = upload.changes.maintainer
302 pu.changed_by = upload.changes.changedby
303 pu.fingerprint = upload.changes.fingerprint
305 pu.suites = [ upload.target_suite ]
306 pu.from_policy_suites = [ upload.target_suite ]
308 changes_path = os.path.join(upload.policy_queue.path, upload.changes.changesname)
309 pu.changes = open(changes_path, 'r').read()
310 pu.changes_filename = upload.changes.changesname
311 pu.sourceful = upload.source is not None
312 pu.source = upload.changes.source
313 pu.version = upload.changes.version
314 pu.architecture = upload.changes.architecture
315 pu.bugs = upload.changes.closes
317 pu.program = "process-policy"
321 ################################################################################
323 def remove_unreferenced_binaries(policy_queue, transaction):
324 """Remove binaries that are no longer referenced by an upload
326 @type policy_queue: L{daklib.dbconn.PolicyQueue}
328 @type transaction: L{daklib.archive.ArchiveTransaction}
330 session = transaction.session
331 suite = policy_queue.suite
336 JOIN bin_associations ba ON b.id = ba.bin
337 WHERE ba.suite = :suite_id
338 AND NOT EXISTS (SELECT 1 FROM policy_queue_upload_binaries_map pqubm
339 JOIN policy_queue_upload pqu ON pqubm.policy_queue_upload_id = pqu.id
340 WHERE pqu.policy_queue_id = :policy_queue_id
341 AND pqubm.binary_id = b.id)"""
342 binaries = session.query(DBBinary).from_statement(query) \
343 .params({'suite_id': policy_queue.suite_id, 'policy_queue_id': policy_queue.policy_queue_id})
345 for binary in binaries:
346 Logger.log(["removed binary from policy queue", policy_queue.queue_name, binary.package, binary.version])
347 transaction.remove_binary(binary, suite)
349 def remove_unreferenced_sources(policy_queue, transaction):
350 """Remove sources that are no longer referenced by an upload or a binary
352 @type policy_queue: L{daklib.dbconn.PolicyQueue}
354 @type transaction: L{daklib.archive.ArchiveTransaction}
356 session = transaction.session
357 suite = policy_queue.suite
362 JOIN src_associations sa ON s.id = sa.source
363 WHERE sa.suite = :suite_id
364 AND NOT EXISTS (SELECT 1 FROM policy_queue_upload pqu
365 WHERE pqu.policy_queue_id = :policy_queue_id
366 AND pqu.source_id = s.id)
367 AND NOT EXISTS (SELECT 1 FROM binaries b
368 JOIN bin_associations ba ON b.id = ba.bin
369 WHERE b.source = s.id
370 AND ba.suite = :suite_id)"""
371 sources = session.query(DBSource).from_statement(query) \
372 .params({'suite_id': policy_queue.suite_id, 'policy_queue_id': policy_queue.policy_queue_id})
374 for source in sources:
375 Logger.log(["removed source from policy queue", policy_queue.queue_name, source.source, source.version])
376 transaction.remove_source(source, suite)
378 ################################################################################
381 global Options, Logger
384 session = DBConn().session()
386 Arguments = [('h',"help","Process-Policy::Options::Help"),
387 ('n',"no-action","Process-Policy::Options::No-Action")]
389 for i in ["help", "no-action"]:
390 if not cnf.has_key("Process-Policy::Options::%s" % (i)):
391 cnf["Process-Policy::Options::%s" % (i)] = ""
393 queue_name = apt_pkg.parse_commandline(cnf.Cnf,Arguments,sys.argv)
395 if len(queue_name) != 1:
396 print "E: Specify exactly one policy queue"
399 queue_name = queue_name[0]
401 Options = cnf.subtree("Process-Policy::Options")
406 Logger = daklog.Logger("process-policy")
407 if not Options["No-Action"]:
408 urgencylog = UrgencyLog()
410 with ArchiveTransaction() as transaction:
411 session = transaction.session
413 pq = session.query(PolicyQueue).filter_by(queue_name=queue_name).one()
414 except NoResultFound:
415 print "E: Cannot find policy queue %s" % queue_name
418 commentsdir = os.path.join(pq.path, 'COMMENTS')
419 # The comments stuff relies on being in the right directory
422 do_comments(commentsdir, pq, "ACCEPT.", "ACCEPTED.", "OK", comment_accept, transaction)
423 do_comments(commentsdir, pq, "ACCEPTED.", "ACCEPTED.", "OK", comment_accept, transaction)
424 do_comments(commentsdir, pq, "REJECT.", "REJECTED.", "NOTOK", comment_reject, transaction)
426 remove_unreferenced_binaries(pq, transaction)
427 remove_unreferenced_sources(pq, transaction)
429 if not Options['No-Action']:
432 ################################################################################
434 if __name__ == '__main__':