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