]> git.decadent.org.uk Git - dak.git/blob - dak/process_policy.py
dak/process_policy.py: handle rejecting the same package twice
[dak.git] / dak / process_policy.py
1 #!/usr/bin/env python
2 # vim:set et ts=4 sw=4:
3
4 """ Handles packages from policy queues
5
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
12 """
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.
17
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.
22
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
26
27 ################################################################################
28
29 # <mhy> So how do we handle that at the moment?
30 # <stew> Probably incorrectly.
31
32 ################################################################################
33
34 import os
35 import datetime
36 import re
37 import sys
38 import traceback
39 import apt_pkg
40
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
48
49 import daklib.announce
50
51 # Globals
52 Options = None
53 Logger = None
54
55 ################################################################################
56
57 def do_comments(dir, srcqueue, opref, npref, line, fn, transaction):
58     session = transaction.session
59     for comm in [ x for x in os.listdir(dir) if x.startswith(opref) ]:
60         lines = open(os.path.join(dir, comm)).readlines()
61         if len(lines) == 0 or lines[0] != line + "\n": continue
62
63         # If the ACCEPT includes a _<arch> we only accept that .changes.
64         # Otherwise we accept all .changes that start with the given prefix
65         changes_prefix = comm[len(opref):]
66         if changes_prefix.count('_') < 2:
67             changes_prefix = changes_prefix + '_'
68         else:
69             changes_prefix = changes_prefix + '.changes'
70
71         # We need to escape "_" as we use it with the LIKE operator (via the
72         # SQLA startwith) later.
73         changes_prefix = changes_prefix.replace("_", r"\_")
74
75         uploads = session.query(PolicyQueueUpload).filter_by(policy_queue=srcqueue) \
76             .join(PolicyQueueUpload.changes).filter(DBChange.changesname.startswith(changes_prefix)) \
77             .order_by(PolicyQueueUpload.source_id)
78         for u in uploads:
79             print "Processing changes file: %s" % u.changes.changesname
80             fn(u, srcqueue, "".join(lines[1:]), transaction)
81
82         if opref != npref:
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)
86
87 ################################################################################
88
89 def try_or_reject(function):
90     def wrapper(upload, srcqueue, comments, transaction):
91         try:
92             function(upload, srcqueue, comments, transaction)
93         except Exception as e:
94             comments = 'An exception was raised while processing the package:\n{0}\nOriginal comments:\n{1}'.format(traceback.format_exc(), comments)
95             try:
96                 transaction.rollback()
97                 real_comment_reject(upload, srcqueue, comments, transaction)
98             except Exception as e:
99                 comments = 'In addition an exception was raised while trying to reject the upload:\n{0}\nOriginal rejection:\n{1}'.format(traceback.format_exc(), comments)
100                 transaction.rollback()
101                 real_comment_reject(upload, srcqueue, comments, transaction, notify=False)
102         if not Options['No-Action']:
103             transaction.commit()
104     return wrapper
105
106 ################################################################################
107
108 @try_or_reject
109 def comment_accept(upload, srcqueue, comments, transaction):
110     for byhand in upload.byhand:
111         path = os.path.join(srcqueue.path, byhand.filename)
112         if os.path.exists(path):
113             raise Exception('E: cannot ACCEPT upload with unprocessed byhand file {0}'.format(byhand.filename))
114
115     cnf = Config()
116
117     fs = transaction.fs
118     session = transaction.session
119     changesname = upload.changes.changesname
120     allow_tainted = srcqueue.suite.archive.tainted
121
122     # We need overrides to get the target component
123     overridesuite = upload.target_suite
124     if overridesuite.overridesuite is not None:
125         overridesuite = session.query(Suite).filter_by(suite_name=overridesuite.overridesuite).one()
126
127     def binary_component_func(db_binary):
128         override = session.query(Override).filter_by(suite=overridesuite, package=db_binary.package) \
129             .join(OverrideType).filter(OverrideType.overridetype == db_binary.binarytype) \
130             .join(Component).one()
131         return override.component
132
133     def source_component_func(db_source):
134         override = session.query(Override).filter_by(suite=overridesuite, package=db_source.source) \
135             .join(OverrideType).filter(OverrideType.overridetype == 'dsc') \
136             .join(Component).one()
137         return override.component
138
139     all_target_suites = [upload.target_suite]
140     all_target_suites.extend([q.suite for q in upload.target_suite.copy_queues])
141
142     for suite in all_target_suites:
143         if upload.source is not None:
144             transaction.copy_source(upload.source, suite, source_component_func(upload.source), allow_tainted=allow_tainted)
145         for db_binary in upload.binaries:
146             # build queues may miss the source package if this is a binary-only upload
147             if suite != upload.target_suite:
148                 transaction.copy_source(db_binary.source, suite, source_component_func(db_binary.source), allow_tainted=allow_tainted)
149             transaction.copy_binary(db_binary, suite, binary_component_func(db_binary), allow_tainted=allow_tainted, extra_archives=[upload.target_suite.archive])
150
151     # Copy .changes if needed
152     if upload.target_suite.copychanges:
153         src = os.path.join(upload.policy_queue.path, upload.changes.changesname)
154         dst = os.path.join(upload.target_suite.path, upload.changes.changesname)
155         fs.copy(src, dst, mode=upload.target_suite.archive.mode)
156
157     # Copy upload to Process-Policy::CopyDir
158     # Used on security.d.o to sync accepted packages to ftp-master, but this
159     # should eventually be replaced by something else.
160     copydir = cnf.get('Process-Policy::CopyDir') or None
161     if copydir is not None:
162         mode = upload.target_suite.archive.mode
163         if upload.source is not None:
164             for f in [ df.poolfile for df in upload.source.srcfiles ]:
165                 dst = os.path.join(copydir, f.basename)
166                 if not os.path.exists(dst):
167                     fs.copy(f.fullpath, dst, mode=mode)
168
169         for db_binary in upload.binaries:
170             f = db_binary.poolfile
171             dst = os.path.join(copydir, f.basename)
172             if not os.path.exists(dst):
173                 fs.copy(f.fullpath, dst, mode=mode)
174
175         src = os.path.join(upload.policy_queue.path, upload.changes.changesname)
176         dst = os.path.join(copydir, upload.changes.changesname)
177         if not os.path.exists(dst):
178             fs.copy(src, dst, mode=mode)
179
180     if upload.source is not None and not Options['No-Action']:
181         urgency = upload.changes.urgency
182         if urgency not in cnf.value_list('Urgency::Valid'):
183             urgency = cnf['Urgency::Default']
184         UrgencyLog().log(upload.source.source, upload.source.version, urgency)
185
186     print "  ACCEPT"
187     if not Options['No-Action']:
188         Logger.log(["Policy Queue ACCEPT", srcqueue.queue_name, changesname])
189
190     pu = get_processed_upload(upload)
191     daklib.announce.announce_accept(pu)
192
193     # TODO: code duplication. Similar code is in process-upload.
194     # Move .changes to done
195     src = os.path.join(upload.policy_queue.path, upload.changes.changesname)
196     now = datetime.datetime.now()
197     donedir = os.path.join(cnf['Dir::Done'], now.strftime('%Y/%m/%d'))
198     dst = os.path.join(donedir, upload.changes.changesname)
199     dst = utils.find_next_free(dst)
200     fs.copy(src, dst, mode=0o644)
201
202     remove_upload(upload, transaction)
203
204 ################################################################################
205
206 @try_or_reject
207 def comment_reject(*args):
208     real_comment_reject(*args, manual=True)
209
210 def real_comment_reject(upload, srcqueue, comments, transaction, notify=True, manual=False):
211     cnf = Config()
212
213     fs = transaction.fs
214     session = transaction.session
215     changesname = upload.changes.changesname
216     queuedir = upload.policy_queue.path
217     rejectdir = cnf['Dir::Reject']
218
219     ### Copy files to reject/
220
221     poolfiles = [b.poolfile for b in upload.binaries]
222     if upload.source is not None:
223         poolfiles.extend([df.poolfile for df in upload.source.srcfiles])
224     # Not beautiful...
225     files = [ af.path for af in session.query(ArchiveFile) \
226                   .filter_by(archive=upload.policy_queue.suite.archive) \
227                   .join(ArchiveFile.file) \
228                   .filter(PoolFile.file_id.in_([ f.file_id for f in poolfiles ])) ]
229     for byhand in upload.byhand:
230         path = os.path.join(queuedir, byhand.filename)
231         if os.path.exists(path):
232             files.append(path)
233     files.append(os.path.join(queuedir, changesname))
234
235     for fn in files:
236         dst = utils.find_next_free(os.path.join(rejectdir, os.path.basename(fn)))
237         fs.copy(fn, dst, link=True)
238
239     ### Write reason
240
241     dst = utils.find_next_free(os.path.join(rejectdir, '{0}.reason'.format(changesname)))
242     fh = fs.create(dst)
243     fh.write(comments)
244     fh.close()
245
246     ### Send mail notification
247
248     if notify:
249         rejected_by = None
250         reason = comments
251
252         # Try to use From: from comment file if there is one.
253         # This is not very elegant...
254         match = re.match(r"\AFrom: ([^\n]+)\n\n", comments)
255         if match:
256             rejected_by = match.group(1)
257             reason = '\n'.join(comments.splitlines()[2:])
258
259         pu = get_processed_upload(upload)
260         daklib.announce.announce_reject(pu, reason, rejected_by)
261
262     print "  REJECT"
263     if not Options["No-Action"]:
264         Logger.log(["Policy Queue REJECT", srcqueue.queue_name, upload.changes.changesname])
265
266     changes = upload.changes
267     remove_upload(upload, transaction)
268     session.delete(changes)
269
270 ################################################################################
271
272 def remove_upload(upload, transaction):
273     fs = transaction.fs
274     session = transaction.session
275     changes = upload.changes
276
277     # Remove byhand and changes files. Binary and source packages will be
278     # removed from {bin,src}_associations and eventually removed by clean-suites automatically.
279     queuedir = upload.policy_queue.path
280     for byhand in upload.byhand:
281         path = os.path.join(queuedir, byhand.filename)
282         if os.path.exists(path):
283             fs.unlink(path)
284         session.delete(byhand)
285     fs.unlink(os.path.join(queuedir, upload.changes.changesname))
286
287     session.delete(upload)
288     session.flush()
289
290 ################################################################################
291
292 def get_processed_upload(upload):
293     pu = daklib.announce.ProcessedUpload()
294
295     pu.maintainer = upload.changes.maintainer
296     pu.changed_by = upload.changes.changedby
297     pu.fingerprint = upload.changes.fingerprint
298
299     pu.suites = [ upload.target_suite ]
300     pu.from_policy_suites = [ upload.target_suite ]
301
302     changes_path = os.path.join(upload.policy_queue.path, upload.changes.changesname)
303     pu.changes = open(changes_path, 'r').read()
304     pu.changes_filename = upload.changes.changesname
305     pu.sourceful = upload.source is not None
306     pu.source = upload.changes.source
307     pu.version = upload.changes.version
308     pu.architecture = upload.changes.architecture
309     pu.bugs = upload.changes.closes
310
311     pu.program = "process-policy"
312
313     return pu
314
315 ################################################################################
316
317 def remove_unreferenced_binaries(policy_queue, transaction):
318     """Remove binaries that are no longer referenced by an upload
319
320     @type  policy_queue: L{daklib.dbconn.PolicyQueue}
321
322     @type  transaction: L{daklib.archive.ArchiveTransaction}
323     """
324     session = transaction.session
325     suite = policy_queue.suite
326
327     query = """
328        SELECT b.*
329          FROM binaries b
330          JOIN bin_associations ba ON b.id = ba.bin
331         WHERE ba.suite = :suite_id
332           AND NOT EXISTS (SELECT 1 FROM policy_queue_upload_binaries_map pqubm
333                                    JOIN policy_queue_upload pqu ON pqubm.policy_queue_upload_id = pqu.id
334                                   WHERE pqu.policy_queue_id = :policy_queue_id
335                                     AND pqubm.binary_id = b.id)"""
336     binaries = session.query(DBBinary).from_statement(query) \
337         .params({'suite_id': policy_queue.suite_id, 'policy_queue_id': policy_queue.policy_queue_id})
338
339     for binary in binaries:
340         Logger.log(["removed binary from policy queue", policy_queue.queue_name, binary.package, binary.version])
341         transaction.remove_binary(binary, suite)
342
343 def remove_unreferenced_sources(policy_queue, transaction):
344     """Remove sources that are no longer referenced by an upload or a binary
345
346     @type  policy_queue: L{daklib.dbconn.PolicyQueue}
347
348     @type  transaction: L{daklib.archive.ArchiveTransaction}
349     """
350     session = transaction.session
351     suite = policy_queue.suite
352
353     query = """
354        SELECT s.*
355          FROM source s
356          JOIN src_associations sa ON s.id = sa.source
357         WHERE sa.suite = :suite_id
358           AND NOT EXISTS (SELECT 1 FROM policy_queue_upload pqu
359                                   WHERE pqu.policy_queue_id = :policy_queue_id
360                                     AND pqu.source_id = s.id)
361           AND NOT EXISTS (SELECT 1 FROM binaries b
362                                    JOIN bin_associations ba ON b.id = ba.bin
363                                   WHERE b.source = s.id
364                                     AND ba.suite = :suite_id)"""
365     sources = session.query(DBSource).from_statement(query) \
366         .params({'suite_id': policy_queue.suite_id, 'policy_queue_id': policy_queue.policy_queue_id})
367
368     for source in sources:
369         Logger.log(["removed source from policy queue", policy_queue.queue_name, source.source, source.version])
370         transaction.remove_source(source, suite)
371
372 ################################################################################
373
374 def main():
375     global Options, Logger
376
377     cnf = Config()
378     session = DBConn().session()
379
380     Arguments = [('h',"help","Process-Policy::Options::Help"),
381                  ('n',"no-action","Process-Policy::Options::No-Action")]
382
383     for i in ["help", "no-action"]:
384         if not cnf.has_key("Process-Policy::Options::%s" % (i)):
385             cnf["Process-Policy::Options::%s" % (i)] = ""
386
387     queue_name = apt_pkg.parse_commandline(cnf.Cnf,Arguments,sys.argv)
388
389     if len(queue_name) != 1:
390         print "E: Specify exactly one policy queue"
391         sys.exit(1)
392
393     queue_name = queue_name[0]
394
395     Options = cnf.subtree("Process-Policy::Options")
396
397     if Options["Help"]:
398         usage()
399
400     Logger = daklog.Logger("process-policy")
401     if not Options["No-Action"]:
402         urgencylog = UrgencyLog()
403
404     with ArchiveTransaction() as transaction:
405         session = transaction.session
406         try:
407             pq = session.query(PolicyQueue).filter_by(queue_name=queue_name).one()
408         except NoResultFound:
409             print "E: Cannot find policy queue %s" % queue_name
410             sys.exit(1)
411
412         commentsdir = os.path.join(pq.path, 'COMMENTS')
413         # The comments stuff relies on being in the right directory
414         os.chdir(pq.path)
415
416         do_comments(commentsdir, pq, "ACCEPT.", "ACCEPTED.", "OK", comment_accept, transaction)
417         do_comments(commentsdir, pq, "ACCEPTED.", "ACCEPTED.", "OK", comment_accept, transaction)
418         do_comments(commentsdir, pq, "REJECT.", "REJECTED.", "NOTOK", comment_reject, transaction)
419
420         remove_unreferenced_binaries(pq, transaction)
421         remove_unreferenced_sources(pq, transaction)
422
423     if not Options['No-Action']:
424         urgencylog.close()
425
426 ################################################################################
427
428 if __name__ == '__main__':
429     main()