]> git.decadent.org.uk Git - dak.git/blob - daklib/archive.py
make use of dak-unpriv
[dak.git] / daklib / archive.py
1 # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16
17 """module to manipulate the archive
18
19 This module provides classes to manipulate the archive.
20 """
21
22 from daklib.dbconn import *
23 import daklib.checks as checks
24 from daklib.config import Config
25 import daklib.upload as upload
26 import daklib.utils as utils
27 from daklib.fstransactions import FilesystemTransaction
28 from daklib.regexes import re_changelog_versions, re_bin_only_nmu
29
30 import apt_pkg
31 from datetime import datetime
32 import os
33 import shutil
34 import subprocess
35 from sqlalchemy.orm.exc import NoResultFound
36 import tempfile
37 import traceback
38
39 class ArchiveException(Exception):
40     pass
41
42 class HashMismatchException(ArchiveException):
43     pass
44
45 class ArchiveTransaction(object):
46     """manipulate the archive in a transaction
47     """
48     def __init__(self):
49         self.fs = FilesystemTransaction()
50         self.session = DBConn().session()
51
52     def get_file(self, hashed_file, source_name, check_hashes=True):
53         """Look for file C{hashed_file} in database
54
55         @type  hashed_file: L{daklib.upload.HashedFile}
56         @param hashed_file: file to look for in the database
57
58         @type  source_name: str
59         @param source_name: source package name
60
61         @type  check_hashes: bool
62         @param check_hashes: check size and hashes match
63
64         @raise KeyError: file was not found in the database
65         @raise HashMismatchException: hash mismatch
66
67         @rtype:  L{daklib.dbconn.PoolFile}
68         @return: database entry for the file
69         """
70         poolname = os.path.join(utils.poolify(source_name), hashed_file.filename)
71         try:
72             poolfile = self.session.query(PoolFile).filter_by(filename=poolname).one()
73             if check_hashes and (poolfile.filesize != hashed_file.size
74                                  or poolfile.md5sum != hashed_file.md5sum
75                                  or poolfile.sha1sum != hashed_file.sha1sum
76                                  or poolfile.sha256sum != hashed_file.sha256sum):
77                 raise HashMismatchException('{0}: Does not match file already existing in the pool.'.format(hashed_file.filename))
78             return poolfile
79         except NoResultFound:
80             raise KeyError('{0} not found in database.'.format(poolname))
81
82     def _install_file(self, directory, hashed_file, archive, component, source_name):
83         """Install a file
84
85         Will not give an error when the file is already present.
86
87         @rtype:  L{daklib.dbconn.PoolFile}
88         @return: batabase object for the new file
89         """
90         session = self.session
91
92         poolname = os.path.join(utils.poolify(source_name), hashed_file.filename)
93         try:
94             poolfile = self.get_file(hashed_file, source_name)
95         except KeyError:
96             poolfile = PoolFile(filename=poolname, filesize=hashed_file.size)
97             poolfile.md5sum = hashed_file.md5sum
98             poolfile.sha1sum = hashed_file.sha1sum
99             poolfile.sha256sum = hashed_file.sha256sum
100             session.add(poolfile)
101             session.flush()
102
103         try:
104             session.query(ArchiveFile).filter_by(archive=archive, component=component, file=poolfile).one()
105         except NoResultFound:
106             archive_file = ArchiveFile(archive, component, poolfile)
107             session.add(archive_file)
108             session.flush()
109
110             path = os.path.join(archive.path, 'pool', component.component_name, poolname)
111             hashed_file_path = os.path.join(directory, hashed_file.filename)
112             self.fs.copy(hashed_file_path, path, link=False, mode=archive.mode)
113
114         return poolfile
115
116     def install_binary(self, directory, binary, suite, component, allow_tainted=False, fingerprint=None, source_suites=None, extra_source_archives=None):
117         """Install a binary package
118
119         @type  directory: str
120         @param directory: directory the binary package is located in
121
122         @type  binary: L{daklib.upload.Binary}
123         @param binary: binary package to install
124
125         @type  suite: L{daklib.dbconn.Suite}
126         @param suite: target suite
127
128         @type  component: L{daklib.dbconn.Component}
129         @param component: target component
130
131         @type  allow_tainted: bool
132         @param allow_tainted: allow to copy additional files from tainted archives
133
134         @type  fingerprint: L{daklib.dbconn.Fingerprint}
135         @param fingerprint: optional fingerprint
136
137         @type  source_suites: SQLAlchemy subquery for C{daklib.dbconn.Suite} or C{True}
138         @param source_suites: suites to copy the source from if they are not
139                               in C{suite} or C{True} to allow copying from any
140                               suite.
141
142         @type  extra_source_archives: list of L{daklib.dbconn.Archive}
143         @param extra_source_archives: extra archives to copy Built-Using sources from
144
145         @rtype:  L{daklib.dbconn.DBBinary}
146         @return: databse object for the new package
147         """
148         session = self.session
149         control = binary.control
150         maintainer = get_or_set_maintainer(control['Maintainer'], session)
151         architecture = get_architecture(control['Architecture'], session)
152
153         (source_name, source_version) = binary.source
154         source_query = session.query(DBSource).filter_by(source=source_name, version=source_version)
155         source = source_query.filter(DBSource.suites.contains(suite)).first()
156         if source is None:
157             if source_suites != True:
158                 source_query = source_query.join(DBSource.suites) \
159                     .filter(Suite.suite_id == source_suites.c.id)
160             source = source_query.first()
161             if source is None:
162                 raise ArchiveException('{0}: trying to install to {1}, but could not find source'.format(binary.hashed_file.filename, suite.suite_name))
163             self.copy_source(source, suite, component)
164
165         db_file = self._install_file(directory, binary.hashed_file, suite.archive, component, source_name)
166
167         unique = dict(
168             package=control['Package'],
169             version=control['Version'],
170             architecture=architecture,
171             )
172         rest = dict(
173             source=source,
174             maintainer=maintainer,
175             poolfile=db_file,
176             binarytype=binary.type,
177             fingerprint=fingerprint,
178             )
179
180         try:
181             db_binary = session.query(DBBinary).filter_by(**unique).one()
182             for key, value in rest.iteritems():
183                 if getattr(db_binary, key) != value:
184                     raise ArchiveException('{0}: Does not match binary in database.'.format(binary.hashed_file.filename))
185         except NoResultFound:
186             db_binary = DBBinary(**unique)
187             for key, value in rest.iteritems():
188                 setattr(db_binary, key, value)
189             session.add(db_binary)
190             session.flush()
191             import_metadata_into_db(db_binary, session)
192
193             self._add_built_using(db_binary, binary.hashed_file.filename, control, suite, extra_archives=extra_source_archives)
194
195         if suite not in db_binary.suites:
196             db_binary.suites.append(suite)
197
198         session.flush()
199
200         return db_binary
201
202     def _ensure_extra_source_exists(self, filename, source, archive, extra_archives=None):
203         """ensure source exists in the given archive
204
205         This is intended to be used to check that Built-Using sources exist.
206
207         @type  filename: str
208         @param filename: filename to use in error messages
209
210         @type  source: L{daklib.dbconn.DBSource}
211         @param source: source to look for
212
213         @type  archive: L{daklib.dbconn.Archive}
214         @param archive: archive to look in
215
216         @type  extra_archives: list of L{daklib.dbconn.Archive}
217         @param extra_archives: list of archives to copy the source package from
218                                if it is not yet present in C{archive}
219         """
220         session = self.session
221         db_file = session.query(ArchiveFile).filter_by(file=source.poolfile, archive=archive).first()
222         if db_file is not None:
223             return True
224
225         # Try to copy file from one extra archive
226         if extra_archives is None:
227             extra_archives = []
228         db_file = session.query(ArchiveFile).filter_by(file=source.poolfile).filter(ArchiveFile.archive_id.in_([ a.archive_id for a in extra_archives])).first()
229         if db_file is None:
230             raise ArchiveException('{0}: Built-Using refers to package {1} (= {2}) not in target archive {3}.'.format(filename, source.source, source.version, archive.archive_name))
231
232         source_archive = db_file.archive
233         for dsc_file in source.srcfiles:
234             af = session.query(ArchiveFile).filter_by(file=dsc_file.poolfile, archive=source_archive, component=db_file.component).one()
235             # We were given an explicit list of archives so it is okay to copy from tainted archives.
236             self._copy_file(af.file, archive, db_file.component, allow_tainted=True)
237
238     def _add_built_using(self, db_binary, filename, control, suite, extra_archives=None):
239         """Add Built-Using sources to C{db_binary.extra_sources}
240         """
241         session = self.session
242         built_using = control.get('Built-Using', None)
243
244         if built_using is not None:
245             for dep in apt_pkg.parse_depends(built_using):
246                 assert len(dep) == 1, 'Alternatives are not allowed in Built-Using field'
247                 bu_source_name, bu_source_version, comp = dep[0]
248                 assert comp == '=', 'Built-Using must contain strict dependencies'
249
250                 bu_source = session.query(DBSource).filter_by(source=bu_source_name, version=bu_source_version).first()
251                 if bu_source is None:
252                     raise ArchiveException('{0}: Built-Using refers to non-existing source package {1} (= {2})'.format(filename, bu_source_name, bu_source_version))
253
254                 self._ensure_extra_source_exists(filename, bu_source, suite.archive, extra_archives=extra_archives)
255
256                 db_binary.extra_sources.append(bu_source)
257
258     def install_source(self, directory, source, suite, component, changed_by, allow_tainted=False, fingerprint=None):
259         """Install a source package
260
261         @type  directory: str
262         @param directory: directory the source package is located in
263
264         @type  source: L{daklib.upload.Source}
265         @param source: source package to install
266
267         @type  suite: L{daklib.dbconn.Suite}
268         @param suite: target suite
269
270         @type  component: L{daklib.dbconn.Component}
271         @param component: target component
272
273         @type  changed_by: L{daklib.dbconn.Maintainer}
274         @param changed_by: person who prepared this version of the package
275
276         @type  allow_tainted: bool
277         @param allow_tainted: allow to copy additional files from tainted archives
278
279         @type  fingerprint: L{daklib.dbconn.Fingerprint}
280         @param fingerprint: optional fingerprint
281
282         @rtype:  L{daklib.dbconn.DBSource}
283         @return: database object for the new source
284         """
285         session = self.session
286         archive = suite.archive
287         control = source.dsc
288         maintainer = get_or_set_maintainer(control['Maintainer'], session)
289         source_name = control['Source']
290
291         ### Add source package to database
292
293         # We need to install the .dsc first as the DBSource object refers to it.
294         db_file_dsc = self._install_file(directory, source._dsc_file, archive, component, source_name)
295
296         unique = dict(
297             source=source_name,
298             version=control['Version'],
299             )
300         rest = dict(
301             maintainer=maintainer,
302             changedby=changed_by,
303             #install_date=datetime.now().date(),
304             poolfile=db_file_dsc,
305             fingerprint=fingerprint,
306             dm_upload_allowed=(control.get('DM-Upload-Allowed', 'no') == 'yes'),
307             )
308
309         created = False
310         try:
311             db_source = session.query(DBSource).filter_by(**unique).one()
312             for key, value in rest.iteritems():
313                 if getattr(db_source, key) != value:
314                     raise ArchiveException('{0}: Does not match source in database.'.format(source._dsc_file.filename))
315         except NoResultFound:
316             created = True
317             db_source = DBSource(**unique)
318             for key, value in rest.iteritems():
319                 setattr(db_source, key, value)
320             # XXX: set as default in postgres?
321             db_source.install_date = datetime.now().date()
322             session.add(db_source)
323             session.flush()
324
325             # Add .dsc file. Other files will be added later.
326             db_dsc_file = DSCFile()
327             db_dsc_file.source = db_source
328             db_dsc_file.poolfile = db_file_dsc
329             session.add(db_dsc_file)
330             session.flush()
331
332         if suite in db_source.suites:
333             return db_source
334
335         db_source.suites.append(suite)
336
337         if not created:
338             return db_source
339
340         ### Now add remaining files and copy them to the archive.
341
342         for hashed_file in source.files.itervalues():
343             hashed_file_path = os.path.join(directory, hashed_file.filename)
344             if os.path.exists(hashed_file_path):
345                 db_file = self._install_file(directory, hashed_file, archive, component, source_name)
346                 session.add(db_file)
347             else:
348                 db_file = self.get_file(hashed_file, source_name)
349                 self._copy_file(db_file, archive, component, allow_tainted=allow_tainted)
350
351             db_dsc_file = DSCFile()
352             db_dsc_file.source = db_source
353             db_dsc_file.poolfile = db_file
354             session.add(db_dsc_file)
355
356         session.flush()
357
358         # Importing is safe as we only arrive here when we did not find the source already installed earlier.
359         import_metadata_into_db(db_source, session)
360
361         # Uploaders are the maintainer and co-maintainers from the Uploaders field
362         db_source.uploaders.append(maintainer)
363         if 'Uploaders' in control:
364             from daklib.textutils import split_uploaders
365             for u in split_uploaders(control['Uploaders']):
366                 db_source.uploaders.append(get_or_set_maintainer(u, session))
367         session.flush()
368
369         return db_source
370
371     def _copy_file(self, db_file, archive, component, allow_tainted=False):
372         """Copy a file to the given archive and component
373
374         @type  db_file: L{daklib.dbconn.PoolFile}
375         @param db_file: file to copy
376
377         @type  archive: L{daklib.dbconn.Archive}
378         @param archive: target archive
379
380         @type  component: L{daklib.dbconn.Archive}
381         @param component: target component
382
383         @type  allow_tainted: bool
384         @param allow_tainted: allow to copy from tainted archives (such as NEW)
385         """
386         session = self.session
387
388         if session.query(ArchiveFile).filter_by(archive=archive, component=component, file=db_file).first() is None:
389             query = session.query(ArchiveFile).filter_by(file=db_file, component=component)
390             if not allow_tainted:
391                 query = query.join(Archive).filter(Archive.tainted == False)
392
393             source_af = query.first()
394             if source_af is None:
395                 raise ArchiveException('cp: Could not find {0} in component {1} in any archive.'.format(db_file.filename, component.component_name))
396             target_af = ArchiveFile(archive, component, db_file)
397             session.add(target_af)
398             session.flush()
399             self.fs.copy(source_af.path, target_af.path, link=False, mode=archive.mode)
400
401     def copy_binary(self, db_binary, suite, component, allow_tainted=False, extra_archives=None):
402         """Copy a binary package to the given suite and component
403
404         @type  db_binary: L{daklib.dbconn.DBBinary}
405         @param db_binary: binary to copy
406
407         @type  suite: L{daklib.dbconn.Suite}
408         @param suite: target suite
409
410         @type  component: L{daklib.dbconn.Component}
411         @param component: target component
412
413         @type  allow_tainted: bool
414         @param allow_tainted: allow to copy from tainted archives (such as NEW)
415
416         @type  extra_archives: list of L{daklib.dbconn.Archive}
417         @param extra_archives: extra archives to copy Built-Using sources from
418         """
419         session = self.session
420         archive = suite.archive
421         if archive.tainted:
422             allow_tainted = True
423
424         filename = db_binary.poolfile.filename
425
426         # make sure source is present in target archive
427         db_source = db_binary.source
428         if session.query(ArchiveFile).filter_by(archive=archive, file=db_source.poolfile).first() is None:
429             raise ArchiveException('{0}: cannot copy to {1}: source is not present in target archive'.format(filename, suite.suite_name))
430
431         # make sure built-using packages are present in target archive
432         for db_source in db_binary.extra_sources:
433             self._ensure_extra_source_exists(filename, db_source, archive, extra_archives=extra_archives)
434
435         # copy binary
436         db_file = db_binary.poolfile
437         self._copy_file(db_file, suite.archive, component, allow_tainted=allow_tainted)
438         if suite not in db_binary.suites:
439             db_binary.suites.append(suite)
440         self.session.flush()
441
442     def copy_source(self, db_source, suite, component, allow_tainted=False):
443         """Copy a source package to the given suite and component
444
445         @type  db_source: L{daklib.dbconn.DBSource}
446         @param db_source: source to copy
447
448         @type  suite: L{daklib.dbconn.Suite}
449         @param suite: target suite
450
451         @type  component: L{daklib.dbconn.Component}
452         @param component: target component
453
454         @type  allow_tainted: bool
455         @param allow_tainted: allow to copy from tainted archives (such as NEW)
456         """
457         archive = suite.archive
458         if archive.tainted:
459             allow_tainted = True
460         for db_dsc_file in db_source.srcfiles:
461             self._copy_file(db_dsc_file.poolfile, archive, component, allow_tainted=allow_tainted)
462         if suite not in db_source.suites:
463             db_source.suites.append(suite)
464         self.session.flush()
465
466     def remove_file(self, db_file, archive, component):
467         """Remove a file from a given archive and component
468
469         @type  db_file: L{daklib.dbconn.PoolFile}
470         @param db_file: file to remove
471
472         @type  archive: L{daklib.dbconn.Archive}
473         @param archive: archive to remove the file from
474
475         @type  component: L{daklib.dbconn.Component}
476         @param component: component to remove the file from
477         """
478         af = self.session.query(ArchiveFile).filter_by(file=db_file, archive=archive, component=component)
479         self.fs.unlink(af.path)
480         self.session.delete(af)
481
482     def remove_binary(self, binary, suite):
483         """Remove a binary from a given suite and component
484
485         @type  binary: L{daklib.dbconn.DBBinary}
486         @param binary: binary to remove
487
488         @type  suite: L{daklib.dbconn.Suite}
489         @param suite: suite to remove the package from
490         """
491         binary.suites.remove(suite)
492         self.session.flush()
493
494     def remove_source(self, source, suite):
495         """Remove a source from a given suite and component
496
497         @type  source: L{daklib.dbconn.DBSource}
498         @param source: source to remove
499
500         @type  suite: L{daklib.dbconn.Suite}
501         @param suite: suite to remove the package from
502
503         @raise ArchiveException: source package is still referenced by other
504                                  binaries in the suite
505         """
506         session = self.session
507
508         query = session.query(DBBinary).filter_by(source=source) \
509             .filter(DBBinary.suites.contains(suite))
510         if query.first() is not None:
511             raise ArchiveException('src:{0} is still used by binaries in suite {1}'.format(source.source, suite.suite_name))
512
513         source.suites.remove(suite)
514         session.flush()
515
516     def commit(self):
517         """commit changes"""
518         try:
519             self.session.commit()
520             self.fs.commit()
521         finally:
522             self.session.rollback()
523             self.fs.rollback()
524
525     def rollback(self):
526         """rollback changes"""
527         self.session.rollback()
528         self.fs.rollback()
529
530     def __enter__(self):
531         return self
532
533     def __exit__(self, type, value, traceback):
534         if type is None:
535             self.commit()
536         else:
537             self.rollback()
538         return None
539
540 class ArchiveUpload(object):
541     """handle an upload
542
543     This class can be used in a with-statement::
544
545        with ArchiveUpload(...) as upload:
546           ...
547
548     Doing so will automatically run any required cleanup and also rollback the
549     transaction if it was not committed.
550     """
551     def __init__(self, directory, changes, keyrings):
552         self.transaction = ArchiveTransaction()
553         """transaction used to handle the upload
554         @type: L{daklib.archive.ArchiveTransaction}
555         """
556
557         self.session = self.transaction.session
558         """database session"""
559
560         self.original_directory = directory
561         self.original_changes = changes
562
563         self.changes = None
564         """upload to process
565         @type: L{daklib.upload.Changes}
566         """
567
568         self.directory = None
569         """directory with temporary copy of files. set by C{prepare}
570         @type: str
571         """
572
573         self.keyrings = keyrings
574
575         self.fingerprint = self.session.query(Fingerprint).filter_by(fingerprint=changes.primary_fingerprint).one()
576         """fingerprint of the key used to sign the upload
577         @type: L{daklib.dbconn.Fingerprint}
578         """
579
580         self.reject_reasons = []
581         """reasons why the upload cannot by accepted
582         @type: list of str
583         """
584
585         self.warnings = []
586         """warnings
587         @note: Not used yet.
588         @type: list of str
589         """
590
591         self.final_suites = None
592
593         self.new = False
594         """upload is NEW. set by C{check}
595         @type: bool
596         """
597
598         self._new_queue = self.session.query(PolicyQueue).filter_by(queue_name='new').one()
599         self._new = self._new_queue.suite
600
601     def prepare(self):
602         """prepare upload for further processing
603
604         This copies the files involved to a temporary directory.  If you use
605         this method directly, you have to remove the directory given by the
606         C{directory} attribute later on your own.
607
608         Instead of using the method directly, you can also use a with-statement::
609
610            with ArchiveUpload(...) as upload:
611               ...
612
613         This will automatically handle any required cleanup.
614         """
615         assert self.directory is None
616         assert self.original_changes.valid_signature
617
618         cnf = Config()
619         session = self.transaction.session
620
621         (None, self.directory) = utils.temp_dirname(parent=cnf.get('Dir::TempPath'),
622                                                     mode=0o2750, cnf.unprivgroup)
623         with FilesystemTransaction() as fs:
624             src = os.path.join(self.original_directory, self.original_changes.filename)
625             dst = os.path.join(self.directory, self.original_changes.filename)
626             fs.copy(src, dst, mode=0o640)
627
628             self.changes = upload.Changes(self.directory, self.original_changes.filename, self.keyrings)
629
630             for f in self.changes.files.itervalues():
631                 src = os.path.join(self.original_directory, f.filename)
632                 dst = os.path.join(self.directory, f.filename)
633                 if not os.path.exists(src):
634                     continue
635                 fs.copy(src, dst, mode=0o640)
636
637             source = self.changes.source
638             if source is not None:
639                 for f in source.files.itervalues():
640                     src = os.path.join(self.original_directory, f.filename)
641                     dst = os.path.join(self.directory, f.filename)
642                     if not os.path.exists(dst):
643                         try:
644                             db_file = self.transaction.get_file(f, source.dsc['Source'], check_hashes=False)
645                             db_archive_file = session.query(ArchiveFile).filter_by(file=db_file).first()
646                             fs.copy(db_archive_file.path, dst, symlink=True)
647                         except KeyError:
648                             # Ignore if get_file could not find it. Upload will
649                             # probably be rejected later.
650                             pass
651
652     def unpacked_source(self):
653         """Path to unpacked source
654
655         Get path to the unpacked source. This method does unpack the source
656         into a temporary directory under C{self.directory} if it has not
657         been done so already.
658
659         @rtype:  str or C{None}
660         @return: string giving the path to the unpacked source directory
661                  or C{None} if no source was included in the upload.
662         """
663         assert self.directory is not None
664
665         source = self.changes.source
666         if source is None:
667             return None
668         dsc_path = os.path.join(self.directory, source._dsc_file.filename)
669
670         sourcedir = os.path.join(self.directory, 'source')
671         if not os.path.exists(sourcedir):
672             devnull = open('/dev/null', 'w')
673             subprocess.check_call(["dpkg-source", "--no-copy", "--no-check", "-x", dsc_path, sourcedir], shell=False, stdout=devnull)
674         if not os.path.isdir(sourcedir):
675             raise Exception("{0} is not a directory after extracting source package".format(sourcedir))
676         return sourcedir
677
678     def _map_suite(self, suite_name):
679         for rule in Config().value_list("SuiteMappings"):
680             fields = rule.split()
681             rtype = fields[0]
682             if rtype == "map" or rtype == "silent-map":
683                 (src, dst) = fields[1:3]
684                 if src == suite_name:
685                     suite_name = dst
686                     if rtype != "silent-map":
687                         self.warnings.append('Mapping {0} to {0}.'.format(src, dst))
688             elif rtype == "ignore":
689                 ignored = fields[1]
690                 if suite_name == ignored:
691                     self.warnings.append('Ignoring target suite {0}.'.format(ignored))
692                     suite_name = None
693             elif rtype == "reject":
694                 rejected = fields[1]
695                 if suite_name == rejected:
696                     self.reject_reasons.append('Uploads to {0} are not accepted.'.format(suite))
697             ## XXX: propup-version and map-unreleased not yet implemented
698         return suite_name
699
700     def _mapped_suites(self):
701         """Get target suites after mappings
702
703         @rtype:  list of L{daklib.dbconn.Suite}
704         @return: list giving the mapped target suites of this upload
705         """
706         session = self.session
707
708         suite_names = []
709         for dist in self.changes.distributions:
710             suite_name = self._map_suite(dist)
711             if suite_name is not None:
712                 suite_names.append(suite_name)
713
714         suites = session.query(Suite).filter(Suite.suite_name.in_(suite_names))
715         return suites
716
717     def _check_new(self, suite):
718         """Check if upload is NEW
719
720         An upload is NEW if it has binary or source packages that do not have
721         an override in C{suite} OR if it references files ONLY in a tainted
722         archive (eg. when it references files in NEW).
723
724         @rtype:  bool
725         @return: C{True} if the upload is NEW, C{False} otherwise
726         """
727         session = self.session
728
729         # Check for missing overrides
730         for b in self.changes.binaries:
731             override = self._binary_override(suite, b)
732             if override is None:
733                 return True
734
735         if self.changes.source is not None:
736             override = self._source_override(suite, self.changes.source)
737             if override is None:
738                 return True
739
740         # Check if we reference a file only in a tainted archive
741         files = self.changes.files.values()
742         if self.changes.source is not None:
743             files.extend(self.changes.source.files.values())
744         for f in files:
745             query = session.query(ArchiveFile).join(PoolFile).filter(PoolFile.sha1sum == f.sha1sum)
746             query_untainted = query.join(Archive).filter(Archive.tainted == False)
747
748             in_archive = (query.first() is not None)
749             in_untainted_archive = (query_untainted.first() is not None)
750
751             if in_archive and not in_untainted_archive:
752                 return True
753
754     def _final_suites(self):
755         session = self.session
756
757         mapped_suites = self._mapped_suites()
758         final_suites = set()
759
760         for suite in mapped_suites:
761             overridesuite = suite
762             if suite.overridesuite is not None:
763                 overridesuite = session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
764             if self._check_new(overridesuite):
765                 self.new = True
766             final_suites.add(suite)
767
768         return final_suites
769
770     def _binary_override(self, suite, binary):
771         """Get override entry for a binary
772
773         @type  suite: L{daklib.dbconn.Suite}
774         @param suite: suite to get override for
775
776         @type  binary: L{daklib.upload.Binary}
777         @param binary: binary to get override for
778
779         @rtype:  L{daklib.dbconn.Override} or C{None}
780         @return: override for the given binary or C{None}
781         """
782         if suite.overridesuite is not None:
783             suite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
784
785         query = self.session.query(Override).filter_by(suite=suite, package=binary.control['Package']) \
786                 .join(Component).filter(Component.component_name == binary.component) \
787                 .join(OverrideType).filter(OverrideType.overridetype == binary.type)
788
789         try:
790             return query.one()
791         except NoResultFound:
792             return None
793
794     def _source_override(self, suite, source):
795         """Get override entry for a source
796
797         @type  suite: L{daklib.dbconn.Suite}
798         @param suite: suite to get override for
799
800         @type  source: L{daklib.upload.Source}
801         @param source: source to get override for
802
803         @rtype:  L{daklib.dbconn.Override} or C{None}
804         @return: override for the given source or C{None}
805         """
806         if suite.overridesuite is not None:
807             suite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
808
809         # XXX: component for source?
810         query = self.session.query(Override).filter_by(suite=suite, package=source.dsc['Source']) \
811                 .join(OverrideType).filter(OverrideType.overridetype == 'dsc')
812
813         try:
814             return query.one()
815         except NoResultFound:
816             return None
817
818     def _binary_component(self, suite, binary, only_overrides=True):
819         """get component for a binary
820
821         By default this will only look at overrides to get the right component;
822         if C{only_overrides} is C{False} this method will also look at the
823         Section field.
824
825         @type  suite: L{daklib.dbconn.Suite}
826
827         @type  binary: L{daklib.upload.Binary}
828
829         @type  only_overrides: bool
830         @param only_overrides: only use overrides to get the right component
831
832         @rtype: L{daklib.dbconn.Component} or C{None}
833         """
834         override = self._binary_override(suite, binary)
835         if override is not None:
836             return override.component
837         if only_overrides:
838             return None
839         return get_mapped_component(binary.component, self.session)
840
841     def check(self, force=False):
842         """run checks against the upload
843
844         @type  force: bool
845         @param force: ignore failing forcable checks
846
847         @rtype:  bool
848         @return: C{True} if all checks passed, C{False} otherwise
849         """
850         # XXX: needs to be better structured.
851         assert self.changes.valid_signature
852
853         try:
854             for chk in (
855                     checks.SignatureCheck,
856                     checks.ChangesCheck,
857                     checks.TransitionCheck,
858                     checks.UploadBlockCheck,
859                     checks.HashesCheck,
860                     checks.SourceCheck,
861                     checks.BinaryCheck,
862                     checks.BinaryTimestampCheck,
863                     checks.ACLCheck,
864                     checks.SingleDistributionCheck,
865                     checks.NoSourceOnlyCheck,
866                     checks.LintianCheck,
867                     ):
868                 chk().check(self)
869
870             final_suites = self._final_suites()
871             if len(final_suites) == 0:
872                 self.reject_reasons.append('Ended with no suite to install to.')
873                 return False
874
875             for chk in (
876                     checks.SourceFormatCheck,
877                     checks.SuiteArchitectureCheck,
878                     checks.VersionCheck,
879                     ):
880                 for suite in final_suites:
881                     chk().per_suite_check(self, suite)
882
883             if len(self.reject_reasons) != 0:
884                 return False
885
886             self.final_suites = final_suites
887             return True
888         except checks.Reject as e:
889             self.reject_reasons.append(unicode(e))
890         except Exception as e:
891             self.reject_reasons.append("Processing raised an exception: {0}.\n{1}".format(e, traceback.format_exc()))
892         return False
893
894     def _install_to_suite(self, suite, source_component_func, binary_component_func, source_suites=None, extra_source_archives=None):
895         """Install upload to the given suite
896
897         @type  suite: L{daklib.dbconn.Suite}
898         @param suite: suite to install the package into. This is the real suite,
899                       ie. after any redirection to NEW or a policy queue
900
901         @param source_component_func: function to get the L{daklib.dbconn.Component}
902                                       for a L{daklib.upload.Source} object
903
904         @param binary_component_func: function to get the L{daklib.dbconn.Component}
905                                       for a L{daklib.upload.Binary} object
906
907         @param source_suites: see L{daklib.archive.ArchiveTransaction.install_binary}
908
909         @param extra_source_archives: see L{daklib.archive.ArchiveTransaction.install_binary}
910
911         @return: tuple with two elements. The first is a L{daklib.dbconn.DBSource}
912                  object for the install source or C{None} if no source was
913                  included. The second is a list of L{daklib.dbconn.DBBinary}
914                  objects for the installed binary packages.
915         """
916         # XXX: move this function to ArchiveTransaction?
917
918         control = self.changes.changes
919         changed_by = get_or_set_maintainer(control.get('Changed-By', control['Maintainer']), self.session)
920
921         if source_suites is None:
922             source_suites = self.session.query(Suite).join((VersionCheck, VersionCheck.reference_id == Suite.suite_id)).filter(VersionCheck.check == 'Enhances').filter(VersionCheck.suite == suite).subquery()
923
924         source = self.changes.source
925         if source is not None:
926             component = source_component_func(source)
927             db_source = self.transaction.install_source(self.directory, source, suite, component, changed_by, fingerprint=self.fingerprint)
928         else:
929             db_source = None
930
931         db_binaries = []
932         for binary in self.changes.binaries:
933             component = binary_component_func(binary)
934             db_binary = self.transaction.install_binary(self.directory, binary, suite, component, fingerprint=self.fingerprint, source_suites=source_suites, extra_source_archives=extra_source_archives)
935             db_binaries.append(db_binary)
936
937         if suite.copychanges:
938             src = os.path.join(self.directory, self.changes.filename)
939             dst = os.path.join(suite.archive.path, 'dists', suite.suite_name, self.changes.filename)
940             self.transaction.fs.copy(src, dst)
941
942         return (db_source, db_binaries)
943
944     def _install_changes(self):
945         assert self.changes.valid_signature
946         control = self.changes.changes
947         session = self.transaction.session
948         config = Config()
949
950         changelog_id = None
951         # Only add changelog for sourceful uploads and binNMUs
952         if 'source' in self.changes.architectures or re_bin_only_nmu.search(control['Version']):
953             query = 'INSERT INTO changelogs_text (changelog) VALUES (:changelog) RETURNING id'
954             changelog_id = session.execute(query, {'changelog': control['Changes']}).scalar()
955             assert changelog_id is not None
956
957         db_changes = DBChange()
958         db_changes.changesname = self.changes.filename
959         db_changes.source = control['Source']
960         db_changes.binaries = control.get('Binary', None)
961         db_changes.architecture = control['Architecture']
962         db_changes.version = control['Version']
963         db_changes.distribution = control['Distribution']
964         db_changes.urgency = control['Urgency']
965         db_changes.maintainer = control['Maintainer']
966         db_changes.changedby = control.get('Changed-By', control['Maintainer'])
967         db_changes.date = control['Date']
968         db_changes.fingerprint = self.fingerprint.fingerprint
969         db_changes.changelog_id = changelog_id
970         db_changes.closes = self.changes.closed_bugs
971
972         self.transaction.session.add(db_changes)
973         self.transaction.session.flush()
974
975         return db_changes
976
977     def _install_policy(self, policy_queue, target_suite, db_changes, db_source, db_binaries):
978         u = PolicyQueueUpload()
979         u.policy_queue = policy_queue
980         u.target_suite = target_suite
981         u.changes = db_changes
982         u.source = db_source
983         u.binaries = db_binaries
984         self.transaction.session.add(u)
985         self.transaction.session.flush()
986
987         dst = os.path.join(policy_queue.path, self.changes.filename)
988         self.transaction.fs.copy(self.changes.path, dst)
989
990         return u
991
992     def try_autobyhand(self):
993         """Try AUTOBYHAND
994
995         Try to handle byhand packages automatically.
996
997         @rtype:  list of L{daklib.upload.HashedFile}
998         @return: list of remaining byhand files
999         """
1000         assert len(self.reject_reasons) == 0
1001         assert self.changes.valid_signature
1002         assert self.final_suites is not None
1003
1004         byhand = self.changes.byhand_files
1005         if len(byhand) == 0:
1006             return True
1007
1008         suites = list(self.final_suites)
1009         assert len(suites) == 1, "BYHAND uploads must be to a single suite"
1010         suite = suites[0]
1011
1012         cnf = Config()
1013         control = self.changes.changes
1014         automatic_byhand_packages = cnf.subtree("AutomaticByHandPackages")
1015
1016         remaining = []
1017         for f in byhand:
1018             parts = f.filename.split('_', 2)
1019             if len(parts) != 3:
1020                 print "W: unexpected byhand filename {0}. No automatic processing.".format(f.filename)
1021                 remaining.append(f)
1022                 continue
1023
1024             package, version, archext = parts
1025             arch, ext = archext.split('.', 1)
1026
1027             try:
1028                 rule = automatic_byhand_packages.subtree(package)
1029             except KeyError:
1030                 remaining.append(f)
1031                 continue
1032
1033             if rule['Source'] != control['Source'] or rule['Section'] != f.section or rule['Extension'] != ext:
1034                 remaining.append(f)
1035                 continue
1036
1037             script = rule['Script']
1038             retcode = subprocess.call([script, os.path.join(self.directory, f.filename), control['Version'], arch, os.path.join(self.directory, self.changes.filename)], shell=False)
1039             if retcode != 0:
1040                 print "W: error processing {0}.".format(f.filename)
1041                 remaining.append(f)
1042
1043         return len(remaining) == 0
1044
1045     def _install_byhand(self, policy_queue_upload, hashed_file):
1046         """install byhand file
1047
1048         @type  policy_queue_upload: L{daklib.dbconn.PolicyQueueUpload}
1049
1050         @type  hashed_file: L{daklib.upload.HashedFile}
1051         """
1052         fs = self.transaction.fs
1053         session = self.transaction.session
1054         policy_queue = policy_queue_upload.policy_queue
1055
1056         byhand_file = PolicyQueueByhandFile()
1057         byhand_file.upload = policy_queue_upload
1058         byhand_file.filename = hashed_file.filename
1059         session.add(byhand_file)
1060         session.flush()
1061
1062         src = os.path.join(self.directory, hashed_file.filename)
1063         dst = os.path.join(policy_queue.path, hashed_file.filename)
1064         fs.copy(src, dst)
1065
1066         return byhand_file
1067
1068     def _do_bts_versiontracking(self):
1069         cnf = Config()
1070         fs = self.transaction.fs
1071
1072         btsdir = cnf.get('Dir::BTSVersionTrack')
1073         if btsdir is None or btsdir == '':
1074             return
1075
1076         base = os.path.join(btsdir, self.changes.filename[:-8])
1077
1078         # version history
1079         sourcedir = self.unpacked_source()
1080         if sourcedir is not None:
1081             fh = open(os.path.join(sourcedir, 'debian', 'changelog'), 'r')
1082             versions = fs.create("{0}.versions".format(base), mode=0o644)
1083             for line in fh.readlines():
1084                 if re_changelog_versions.match(line):
1085                     versions.write(line)
1086             fh.close()
1087             versions.close()
1088
1089         # binary -> source mapping
1090         debinfo = fs.create("{0}.debinfo".format(base), mode=0o644)
1091         for binary in self.changes.binaries:
1092             control = binary.control
1093             source_package, source_version = binary.source
1094             line = " ".join([control['Package'], control['Version'], source_package, source_version])
1095             print >>debinfo, line
1096         debinfo.close()
1097
1098     def _policy_queue(self, suite):
1099         if suite.policy_queue is not None:
1100             return suite.policy_queue
1101         return None
1102
1103     def install(self):
1104         """install upload
1105
1106         Install upload to a suite or policy queue.  This method does B{not}
1107         handle uploads to NEW.
1108
1109         You need to have called the C{check} method before calling this method.
1110         """
1111         assert len(self.reject_reasons) == 0
1112         assert self.changes.valid_signature
1113         assert self.final_suites is not None
1114         assert not self.new
1115
1116         db_changes = self._install_changes()
1117
1118         for suite in self.final_suites:
1119             overridesuite = suite
1120             if suite.overridesuite is not None:
1121                 overridesuite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
1122
1123             policy_queue = self._policy_queue(suite)
1124
1125             redirected_suite = suite
1126             if policy_queue is not None:
1127                 redirected_suite = policy_queue.suite
1128
1129             source_suites = self.session.query(Suite).filter(Suite.suite_id.in_([suite.suite_id, redirected_suite.suite_id])).subquery()
1130
1131             source_component_func = lambda source: self._source_override(overridesuite, source).component
1132             binary_component_func = lambda binary: self._binary_component(overridesuite, binary)
1133
1134             (db_source, db_binaries) = self._install_to_suite(redirected_suite, source_component_func, binary_component_func, source_suites=source_suites, extra_source_archives=[suite.archive])
1135
1136             if policy_queue is not None:
1137                 self._install_policy(policy_queue, suite, db_changes, db_source, db_binaries)
1138
1139             # copy to build queues
1140             if policy_queue is None or policy_queue.send_to_build_queues:
1141                 for build_queue in suite.copy_queues:
1142                     self._install_to_suite(build_queue.suite, source_component_func, binary_component_func, source_suites=source_suites, extra_source_archives=[suite.archive])
1143
1144         self._do_bts_versiontracking()
1145
1146     def install_to_new(self):
1147         """install upload to NEW
1148
1149         Install upload to NEW.  This method does B{not} handle regular uploads
1150         to suites or policy queues.
1151
1152         You need to have called the C{check} method before calling this method.
1153         """
1154         # Uploads to NEW are special as we don't have overrides.
1155         assert len(self.reject_reasons) == 0
1156         assert self.changes.valid_signature
1157         assert self.final_suites is not None
1158
1159         source = self.changes.source
1160         binaries = self.changes.binaries
1161         byhand = self.changes.byhand_files
1162
1163         new_queue = self.transaction.session.query(PolicyQueue).filter_by(queue_name='new').one()
1164         if len(byhand) > 0:
1165             new_queue = self.transaction.session.query(PolicyQueue).filter_by(queue_name='byhand').one()
1166         new_suite = new_queue.suite
1167
1168         # we need a suite to guess components
1169         suites = list(self.final_suites)
1170         assert len(suites) == 1, "NEW uploads must be to a single suite"
1171         suite = suites[0]
1172
1173         def binary_component_func(binary):
1174             return self._binary_component(suite, binary, only_overrides=False)
1175
1176         # guess source component
1177         # XXX: should be moved into an extra method
1178         binary_component_names = set()
1179         for binary in binaries:
1180             component = binary_component_func(binary)
1181             binary_component_names.add(component.component_name)
1182         source_component_name = None
1183         for c in self.session.query(Component).order_by(Component.component_id):
1184             guess = c.component_name
1185             if guess in binary_component_names:
1186                 source_component_name = guess
1187                 break
1188         if source_component_name is None:
1189             source_component = self.session.query(Component).order_by(Component.component_id).first()
1190         else:
1191             source_component = self.session.query(Component).filter_by(component_name=source_component_name).one()
1192         source_component_func = lambda source: source_component
1193
1194         db_changes = self._install_changes()
1195         (db_source, db_binaries) = self._install_to_suite(new_suite, source_component_func, binary_component_func, source_suites=True, extra_source_archives=[suite.archive])
1196         policy_upload = self._install_policy(new_queue, suite, db_changes, db_source, db_binaries)
1197
1198         for f in byhand:
1199             self._install_byhand(policy_upload, f)
1200
1201         self._do_bts_versiontracking()
1202
1203     def commit(self):
1204         """commit changes"""
1205         self.transaction.commit()
1206
1207     def rollback(self):
1208         """rollback changes"""
1209         self.transaction.rollback()
1210
1211     def __enter__(self):
1212         self.prepare()
1213         return self
1214
1215     def __exit__(self, type, value, traceback):
1216         if self.directory is not None:
1217             shutil.rmtree(self.directory)
1218             self.directory = None
1219         self.changes = None
1220         self.transaction.rollback()
1221         return None