]> git.donarmstrong.com Git - dak.git/blob - dak/process_policy.py
Remove old (and slow) code
[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     actions = []
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
63
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 + '_'
69         else:
70             changes_prefix = changes_prefix + '.changes'
71
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"\_")
75
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)
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     actions.sort()
88
89     for u, reason in actions:
90         print("Processing changes file: {0}".format(u.changes.changesname))
91         fn(u, srcqueue, reason, transaction)
92
93 ################################################################################
94
95 def try_or_reject(function):
96     def wrapper(upload, srcqueue, comments, transaction):
97         try:
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)
101             try:
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']:
109             transaction.commit()
110     return wrapper
111
112 ################################################################################
113
114 @try_or_reject
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))
120
121     cnf = Config()
122
123     fs = transaction.fs
124     session = transaction.session
125     changesname = upload.changes.changesname
126     allow_tainted = srcqueue.suite.archive.tainted
127
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()
132
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
138
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
144
145     all_target_suites = [upload.target_suite]
146     all_target_suites.extend([q.suite for q in upload.target_suite.copy_queues])
147
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])
156
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)
162
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)
174
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)
180
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)
185
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)
191
192     print "  ACCEPT"
193     if not Options['No-Action']:
194         Logger.log(["Policy Queue ACCEPT", srcqueue.queue_name, changesname])
195
196     pu = get_processed_upload(upload)
197     daklib.announce.announce_accept(pu)
198
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)
207
208     remove_upload(upload, transaction)
209
210 ################################################################################
211
212 @try_or_reject
213 def comment_reject(*args):
214     real_comment_reject(*args, manual=True)
215
216 def real_comment_reject(upload, srcqueue, comments, transaction, notify=True, manual=False):
217     cnf = Config()
218
219     fs = transaction.fs
220     session = transaction.session
221     changesname = upload.changes.changesname
222     queuedir = upload.policy_queue.path
223     rejectdir = cnf['Dir::Reject']
224
225     ### Copy files to reject/
226
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])
230     # Not beautiful...
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):
238             files.append(path)
239     files.append(os.path.join(queuedir, changesname))
240
241     for fn in files:
242         dst = utils.find_next_free(os.path.join(rejectdir, os.path.basename(fn)))
243         fs.copy(fn, dst, link=True)
244
245     ### Write reason
246
247     dst = utils.find_next_free(os.path.join(rejectdir, '{0}.reason'.format(changesname)))
248     fh = fs.create(dst)
249     fh.write(comments)
250     fh.close()
251
252     ### Send mail notification
253
254     if notify:
255         rejected_by = None
256         reason = comments
257
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)
261         if match:
262             rejected_by = match.group(1)
263             reason = '\n'.join(comments.splitlines()[2:])
264
265         pu = get_processed_upload(upload)
266         daklib.announce.announce_reject(pu, reason, rejected_by)
267
268     print "  REJECT"
269     if not Options["No-Action"]:
270         Logger.log(["Policy Queue REJECT", srcqueue.queue_name, upload.changes.changesname])
271
272     changes = upload.changes
273     remove_upload(upload, transaction)
274     session.delete(changes)
275
276 ################################################################################
277
278 def remove_upload(upload, transaction):
279     fs = transaction.fs
280     session = transaction.session
281     changes = upload.changes
282
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):
289             fs.unlink(path)
290         session.delete(byhand)
291     fs.unlink(os.path.join(queuedir, upload.changes.changesname))
292
293     session.delete(upload)
294     session.flush()
295
296 ################################################################################
297
298 def get_processed_upload(upload):
299     pu = daklib.announce.ProcessedUpload()
300
301     pu.maintainer = upload.changes.maintainer
302     pu.changed_by = upload.changes.changedby
303     pu.fingerprint = upload.changes.fingerprint
304
305     pu.suites = [ upload.target_suite ]
306     pu.from_policy_suites = [ upload.target_suite ]
307
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
316
317     pu.program = "process-policy"
318
319     return pu
320
321 ################################################################################
322
323 def remove_unreferenced_binaries(policy_queue, transaction):
324     """Remove binaries that are no longer referenced by an upload
325
326     @type  policy_queue: L{daklib.dbconn.PolicyQueue}
327
328     @type  transaction: L{daklib.archive.ArchiveTransaction}
329     """
330     session = transaction.session
331     suite = policy_queue.suite
332
333     query = """
334        SELECT b.*
335          FROM binaries b
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})
344
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)
348
349 def remove_unreferenced_sources(policy_queue, transaction):
350     """Remove sources that are no longer referenced by an upload or a binary
351
352     @type  policy_queue: L{daklib.dbconn.PolicyQueue}
353
354     @type  transaction: L{daklib.archive.ArchiveTransaction}
355     """
356     session = transaction.session
357     suite = policy_queue.suite
358
359     query = """
360        SELECT s.*
361          FROM source s
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})
373
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)
377
378 ################################################################################
379
380 def main():
381     global Options, Logger
382
383     cnf = Config()
384     session = DBConn().session()
385
386     Arguments = [('h',"help","Process-Policy::Options::Help"),
387                  ('n',"no-action","Process-Policy::Options::No-Action")]
388
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)] = ""
392
393     queue_name = apt_pkg.parse_commandline(cnf.Cnf,Arguments,sys.argv)
394
395     if len(queue_name) != 1:
396         print "E: Specify exactly one policy queue"
397         sys.exit(1)
398
399     queue_name = queue_name[0]
400
401     Options = cnf.subtree("Process-Policy::Options")
402
403     if Options["Help"]:
404         usage()
405
406     Logger = daklog.Logger("process-policy")
407     if not Options["No-Action"]:
408         urgencylog = UrgencyLog()
409
410     with ArchiveTransaction() as transaction:
411         session = transaction.session
412         try:
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
416             sys.exit(1)
417
418         commentsdir = os.path.join(pq.path, 'COMMENTS')
419         # The comments stuff relies on being in the right directory
420         os.chdir(pq.path)
421
422         do_comments(commentsdir, pq, "REJECT.", "REJECTED.", "NOTOK", comment_reject, transaction)
423         do_comments(commentsdir, pq, "ACCEPT.", "ACCEPTED.", "OK", comment_accept, transaction)
424         do_comments(commentsdir, pq, "ACCEPTED.", "ACCEPTED.", "OK", comment_accept, transaction)
425
426         remove_unreferenced_binaries(pq, transaction)
427         remove_unreferenced_sources(pq, transaction)
428
429     if not Options['No-Action']:
430         urgencylog.close()
431
432 ################################################################################
433
434 if __name__ == '__main__':
435     main()