archive.py 47.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""module to manipulate the archive

This module provides classes to manipulate the archive.
"""

A
Ansgar Burchardt 已提交
22
from daklib.dbconn import *
23 24 25 26
import daklib.checks as checks
from daklib.config import Config
import daklib.upload as upload
import daklib.utils as utils
A
Ansgar Burchardt 已提交
27 28
from daklib.fstransactions import FilesystemTransaction
from daklib.regexes import re_changelog_versions, re_bin_only_nmu
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

import apt_pkg
from datetime import datetime
import os
import shutil
import subprocess
from sqlalchemy.orm.exc import NoResultFound
import tempfile
import traceback

class ArchiveException(Exception):
    pass

class HashMismatchException(ArchiveException):
    pass

class ArchiveTransaction(object):
    """manipulate the archive in a transaction
    """
    def __init__(self):
        self.fs = FilesystemTransaction()
        self.session = DBConn().session()

52
    def get_file(self, hashed_file, source_name, check_hashes=True):
A
Ansgar Burchardt 已提交
53
        """Look for file C{hashed_file} in database
54

A
Ansgar Burchardt 已提交
55 56
        @type  hashed_file: L{daklib.upload.HashedFile}
        @param hashed_file: file to look for in the database
57

58 59 60 61 62 63
        @type  source_name: str
        @param source_name: source package name

        @type  check_hashes: bool
        @param check_hashes: check size and hashes match

A
Ansgar Burchardt 已提交
64 65
        @raise KeyError: file was not found in the database
        @raise HashMismatchException: hash mismatch
66

A
Ansgar Burchardt 已提交
67 68
        @rtype:  L{daklib.dbconn.PoolFile}
        @return: database entry for the file
69 70 71 72
        """
        poolname = os.path.join(utils.poolify(source_name), hashed_file.filename)
        try:
            poolfile = self.session.query(PoolFile).filter_by(filename=poolname).one()
73 74 75 76
            if check_hashes and (poolfile.filesize != hashed_file.size
                                 or poolfile.md5sum != hashed_file.md5sum
                                 or poolfile.sha1sum != hashed_file.sha1sum
                                 or poolfile.sha256sum != hashed_file.sha256sum):
77 78 79 80 81 82 83 84 85 86
                raise HashMismatchException('{0}: Does not match file already existing in the pool.'.format(hashed_file.filename))
            return poolfile
        except NoResultFound:
            raise KeyError('{0} not found in database.'.format(poolname))

    def _install_file(self, directory, hashed_file, archive, component, source_name):
        """Install a file

        Will not give an error when the file is already present.

A
Ansgar Burchardt 已提交
87 88
        @rtype:  L{daklib.dbconn.PoolFile}
        @return: batabase object for the new file
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        """
        session = self.session

        poolname = os.path.join(utils.poolify(source_name), hashed_file.filename)
        try:
            poolfile = self.get_file(hashed_file, source_name)
        except KeyError:
            poolfile = PoolFile(filename=poolname, filesize=hashed_file.size)
            poolfile.md5sum = hashed_file.md5sum
            poolfile.sha1sum = hashed_file.sha1sum
            poolfile.sha256sum = hashed_file.sha256sum
            session.add(poolfile)
            session.flush()

        try:
            session.query(ArchiveFile).filter_by(archive=archive, component=component, file=poolfile).one()
        except NoResultFound:
            archive_file = ArchiveFile(archive, component, poolfile)
            session.add(archive_file)
            session.flush()

            path = os.path.join(archive.path, 'pool', component.component_name, poolname)
            hashed_file_path = os.path.join(directory, hashed_file.filename)
            self.fs.copy(hashed_file_path, path, link=False, mode=archive.mode)

        return poolfile

    def install_binary(self, directory, binary, suite, component, allow_tainted=False, fingerprint=None, source_suites=None, extra_source_archives=None):
        """Install a binary package

A
Ansgar Burchardt 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        @type  directory: str
        @param directory: directory the binary package is located in

        @type  binary: L{daklib.upload.Binary}
        @param binary: binary package to install

        @type  suite: L{daklib.dbconn.Suite}
        @param suite: target suite

        @type  component: L{daklib.dbconn.Component}
        @param component: target component

        @type  allow_tainted: bool
        @param allow_tainted: allow to copy additional files from tainted archives

        @type  fingerprint: L{daklib.dbconn.Fingerprint}
        @param fingerprint: optional fingerprint

137
        @type  source_suites: SQLAlchemy subquery for C{daklib.dbconn.Suite} or C{True}
A
Ansgar Burchardt 已提交
138 139 140 141 142 143 144 145 146
        @param source_suites: suites to copy the source from if they are not
                              in C{suite} or C{True} to allow copying from any
                              suite.

        @type  extra_source_archives: list of L{daklib.dbconn.Archive}
        @param extra_source_archives: extra archives to copy Built-Using sources from

        @rtype:  L{daklib.dbconn.DBBinary}
        @return: databse object for the new package
147 148 149 150 151 152 153 154 155 156 157
        """
        session = self.session
        control = binary.control
        maintainer = get_or_set_maintainer(control['Maintainer'], session)
        architecture = get_architecture(control['Architecture'], session)

        (source_name, source_version) = binary.source
        source_query = session.query(DBSource).filter_by(source=source_name, version=source_version)
        source = source_query.filter(DBSource.suites.contains(suite)).first()
        if source is None:
            if source_suites != True:
158 159
                source_query = source_query.join(DBSource.suites) \
                    .filter(Suite.suite_id == source_suites.c.id)
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            source = source_query.first()
            if source is None:
                raise ArchiveException('{0}: trying to install to {1}, but could not find source'.format(binary.hashed_file.filename, suite.suite_name))
            self.copy_source(source, suite, component)

        db_file = self._install_file(directory, binary.hashed_file, suite.archive, component, source_name)

        unique = dict(
            package=control['Package'],
            version=control['Version'],
            architecture=architecture,
            )
        rest = dict(
            source=source,
            maintainer=maintainer,
            poolfile=db_file,
            binarytype=binary.type,
            fingerprint=fingerprint,
            )

        try:
            db_binary = session.query(DBBinary).filter_by(**unique).one()
            for key, value in rest.iteritems():
                if getattr(db_binary, key) != value:
                    raise ArchiveException('{0}: Does not match binary in database.'.format(binary.hashed_file.filename))
        except NoResultFound:
            db_binary = DBBinary(**unique)
            for key, value in rest.iteritems():
                setattr(db_binary, key, value)
            session.add(db_binary)
            session.flush()
            import_metadata_into_db(db_binary, session)

            self._add_built_using(db_binary, binary.hashed_file.filename, control, suite, extra_archives=extra_source_archives)

        if suite not in db_binary.suites:
            db_binary.suites.append(suite)

        session.flush()

        return db_binary

    def _ensure_extra_source_exists(self, filename, source, archive, extra_archives=None):
        """ensure source exists in the given archive

        This is intended to be used to check that Built-Using sources exist.

A
Ansgar Burchardt 已提交
207 208 209 210 211 212 213 214
        @type  filename: str
        @param filename: filename to use in error messages

        @type  source: L{daklib.dbconn.DBSource}
        @param source: source to look for

        @type  archive: L{daklib.dbconn.Archive}
        @param archive: archive to look in
215

A
Ansgar Burchardt 已提交
216 217 218
        @type  extra_archives: list of L{daklib.dbconn.Archive}
        @param extra_archives: list of archives to copy the source package from
                               if it is not yet present in C{archive}
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        """
        session = self.session
        db_file = session.query(ArchiveFile).filter_by(file=source.poolfile, archive=archive).first()
        if db_file is not None:
            return True

        # Try to copy file from one extra archive
        if extra_archives is None:
            extra_archives = []
        db_file = session.query(ArchiveFile).filter_by(file=source.poolfile).filter(ArchiveFile.archive_id.in_([ a.archive_id for a in extra_archives])).first()
        if db_file is None:
            raise ArchiveException('{0}: Built-Using refers to package {1} (= {2}) not in target archive {3}.'.format(filename, source.source, source.version, archive.archive_name))

        source_archive = db_file.archive
        for dsc_file in source.srcfiles:
            af = session.query(ArchiveFile).filter_by(file=dsc_file.poolfile, archive=source_archive, component=db_file.component).one()
            # We were given an explicit list of archives so it is okay to copy from tainted archives.
            self._copy_file(af.file, archive, db_file.component, allow_tainted=True)

    def _add_built_using(self, db_binary, filename, control, suite, extra_archives=None):
A
Ansgar Burchardt 已提交
239
        """Add Built-Using sources to C{db_binary.extra_sources}
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        """
        session = self.session
        built_using = control.get('Built-Using', None)

        if built_using is not None:
            for dep in apt_pkg.parse_depends(built_using):
                assert len(dep) == 1, 'Alternatives are not allowed in Built-Using field'
                bu_source_name, bu_source_version, comp = dep[0]
                assert comp == '=', 'Built-Using must contain strict dependencies'

                bu_source = session.query(DBSource).filter_by(source=bu_source_name, version=bu_source_version).first()
                if bu_source is None:
                    raise ArchiveException('{0}: Built-Using refers to non-existing source package {1} (= {2})'.format(filename, bu_source_name, bu_source_version))

                self._ensure_extra_source_exists(filename, bu_source, suite.archive, extra_archives=extra_archives)

                db_binary.extra_sources.append(bu_source)

    def install_source(self, directory, source, suite, component, changed_by, allow_tainted=False, fingerprint=None):
        """Install a source package

A
Ansgar Burchardt 已提交
261 262 263 264 265 266 267 268 269 270 271
        @type  directory: str
        @param directory: directory the source package is located in

        @type  source: L{daklib.upload.Source}
        @param source: source package to install

        @type  suite: L{daklib.dbconn.Suite}
        @param suite: target suite

        @type  component: L{daklib.dbconn.Component}
        @param component: target component
272

A
Ansgar Burchardt 已提交
273 274
        @type  changed_by: L{daklib.dbconn.Maintainer}
        @param changed_by: person who prepared this version of the package
275

A
Ansgar Burchardt 已提交
276 277 278 279 280 281 282 283
        @type  allow_tainted: bool
        @param allow_tainted: allow to copy additional files from tainted archives

        @type  fingerprint: L{daklib.dbconn.Fingerprint}
        @param fingerprint: optional fingerprint

        @rtype:  L{daklib.dbconn.DBSource}
        @return: database object for the new source
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        """
        session = self.session
        archive = suite.archive
        control = source.dsc
        maintainer = get_or_set_maintainer(control['Maintainer'], session)
        source_name = control['Source']

        ### Add source package to database

        # We need to install the .dsc first as the DBSource object refers to it.
        db_file_dsc = self._install_file(directory, source._dsc_file, archive, component, source_name)

        unique = dict(
            source=source_name,
            version=control['Version'],
            )
        rest = dict(
            maintainer=maintainer,
            changedby=changed_by,
            #install_date=datetime.now().date(),
            poolfile=db_file_dsc,
            fingerprint=fingerprint,
            dm_upload_allowed=(control.get('DM-Upload-Allowed', 'no') == 'yes'),
            )

        created = False
        try:
            db_source = session.query(DBSource).filter_by(**unique).one()
            for key, value in rest.iteritems():
                if getattr(db_source, key) != value:
                    raise ArchiveException('{0}: Does not match source in database.'.format(source._dsc_file.filename))
        except NoResultFound:
            created = True
            db_source = DBSource(**unique)
            for key, value in rest.iteritems():
                setattr(db_source, key, value)
            # XXX: set as default in postgres?
            db_source.install_date = datetime.now().date()
            session.add(db_source)
            session.flush()

            # Add .dsc file. Other files will be added later.
            db_dsc_file = DSCFile()
            db_dsc_file.source = db_source
            db_dsc_file.poolfile = db_file_dsc
            session.add(db_dsc_file)
            session.flush()

        if suite in db_source.suites:
            return db_source

        db_source.suites.append(suite)

        if not created:
            return db_source

        ### Now add remaining files and copy them to the archive.

        for hashed_file in source.files.itervalues():
            hashed_file_path = os.path.join(directory, hashed_file.filename)
            if os.path.exists(hashed_file_path):
                db_file = self._install_file(directory, hashed_file, archive, component, source_name)
                session.add(db_file)
            else:
                db_file = self.get_file(hashed_file, source_name)
                self._copy_file(db_file, archive, component, allow_tainted=allow_tainted)

            db_dsc_file = DSCFile()
            db_dsc_file.source = db_source
            db_dsc_file.poolfile = db_file
            session.add(db_dsc_file)

        session.flush()

        # Importing is safe as we only arrive here when we did not find the source already installed earlier.
        import_metadata_into_db(db_source, session)

        # Uploaders are the maintainer and co-maintainers from the Uploaders field
        db_source.uploaders.append(maintainer)
        if 'Uploaders' in control:
364
            from daklib.textutils import split_uploaders
365 366 367 368 369 370 371 372 373
            for u in split_uploaders(control['Uploaders']):
                db_source.uploaders.append(get_or_set_maintainer(u, session))
        session.flush()

        return db_source

    def _copy_file(self, db_file, archive, component, allow_tainted=False):
        """Copy a file to the given archive and component

A
Ansgar Burchardt 已提交
374 375 376 377 378 379 380 381
        @type  db_file: L{daklib.dbconn.PoolFile}
        @param db_file: file to copy

        @type  archive: L{daklib.dbconn.Archive}
        @param archive: target archive

        @type  component: L{daklib.dbconn.Archive}
        @param component: target component
382

A
Ansgar Burchardt 已提交
383 384
        @type  allow_tainted: bool
        @param allow_tainted: allow to copy from tainted archives (such as NEW)
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        """
        session = self.session

        if session.query(ArchiveFile).filter_by(archive=archive, component=component, file=db_file).first() is None:
            query = session.query(ArchiveFile).filter_by(file=db_file, component=component)
            if not allow_tainted:
                query = query.join(Archive).filter(Archive.tainted == False)

            source_af = query.first()
            if source_af is None:
                raise ArchiveException('cp: Could not find {0} in component {1} in any archive.'.format(db_file.filename, component.component_name))
            target_af = ArchiveFile(archive, component, db_file)
            session.add(target_af)
            session.flush()
            self.fs.copy(source_af.path, target_af.path, link=False, mode=archive.mode)

    def copy_binary(self, db_binary, suite, component, allow_tainted=False, extra_archives=None):
        """Copy a binary package to the given suite and component

A
Ansgar Burchardt 已提交
404 405 406 407 408 409 410 411 412 413 414
        @type  db_binary: L{daklib.dbconn.DBBinary}
        @param db_binary: binary to copy

        @type  suite: L{daklib.dbconn.Suite}
        @param suite: target suite

        @type  component: L{daklib.dbconn.Component}
        @param component: target component

        @type  allow_tainted: bool
        @param allow_tainted: allow to copy from tainted archives (such as NEW)
415

A
Ansgar Burchardt 已提交
416 417
        @type  extra_archives: list of L{daklib.dbconn.Archive}
        @param extra_archives: extra archives to copy Built-Using sources from
418 419 420 421 422 423 424
        """
        session = self.session
        archive = suite.archive
        if archive.tainted:
            allow_tainted = True

        filename = db_binary.poolfile.filename
425 426 427 428 429 430 431

        # make sure source is present in target archive
        db_source = db_binary.source
        if session.query(ArchiveFile).filter_by(archive=archive, file=db_source.poolfile).first() is None:
            raise ArchiveException('{0}: cannot copy to {1}: source is not present in target archive'.format(filename, suite.suite_name))

        # make sure built-using packages are present in target archive
432 433 434 435 436 437 438 439 440 441 442 443 444
        for db_source in db_binary.extra_sources:
            self._ensure_extra_source_exists(filename, db_source, archive, extra_archives=extra_archives)

        # copy binary
        db_file = db_binary.poolfile
        self._copy_file(db_file, suite.archive, component, allow_tainted=allow_tainted)
        if suite not in db_binary.suites:
            db_binary.suites.append(suite)
        self.session.flush()

    def copy_source(self, db_source, suite, component, allow_tainted=False):
        """Copy a source package to the given suite and component

A
Ansgar Burchardt 已提交
445 446
        @type  db_source: L{daklib.dbconn.DBSource}
        @param db_source: source to copy
447

A
Ansgar Burchardt 已提交
448 449 450 451 452 453 454 455
        @type  suite: L{daklib.dbconn.Suite}
        @param suite: target suite

        @type  component: L{daklib.dbconn.Component}
        @param component: target component

        @type  allow_tainted: bool
        @param allow_tainted: allow to copy from tainted archives (such as NEW)
456 457 458 459 460 461 462 463 464 465 466 467 468
        """
        archive = suite.archive
        if archive.tainted:
            allow_tainted = True
        for db_dsc_file in db_source.srcfiles:
            self._copy_file(db_dsc_file.poolfile, archive, component, allow_tainted=allow_tainted)
        if suite not in db_source.suites:
            db_source.suites.append(suite)
        self.session.flush()

    def remove_file(self, db_file, archive, component):
        """Remove a file from a given archive and component

A
Ansgar Burchardt 已提交
469 470 471 472 473 474 475 476
        @type  db_file: L{daklib.dbconn.PoolFile}
        @param db_file: file to remove

        @type  archive: L{daklib.dbconn.Archive}
        @param archive: archive to remove the file from

        @type  component: L{daklib.dbconn.Component}
        @param component: component to remove the file from
477 478 479 480 481 482 483 484
        """
        af = self.session.query(ArchiveFile).filter_by(file=db_file, archive=archive, component=component)
        self.fs.unlink(af.path)
        self.session.delete(af)

    def remove_binary(self, binary, suite):
        """Remove a binary from a given suite and component

A
Ansgar Burchardt 已提交
485 486 487 488 489
        @type  binary: L{daklib.dbconn.DBBinary}
        @param binary: binary to remove

        @type  suite: L{daklib.dbconn.Suite}
        @param suite: suite to remove the package from
490 491 492 493 494 495 496
        """
        binary.suites.remove(suite)
        self.session.flush()

    def remove_source(self, source, suite):
        """Remove a source from a given suite and component

A
Ansgar Burchardt 已提交
497 498 499 500 501
        @type  source: L{daklib.dbconn.DBSource}
        @param source: source to remove

        @type  suite: L{daklib.dbconn.Suite}
        @param suite: suite to remove the package from
502

A
Ansgar Burchardt 已提交
503 504
        @raise ArchiveException: source package is still referenced by other
                                 binaries in the suite
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        """
        session = self.session

        query = session.query(DBBinary).filter_by(source=source) \
            .filter(DBBinary.suites.contains(suite))
        if query.first() is not None:
            raise ArchiveException('src:{0} is still used by binaries in suite {1}'.format(source.source, suite.suite_name))

        source.suites.remove(suite)
        session.flush()

    def commit(self):
        """commit changes"""
        try:
            self.session.commit()
            self.fs.commit()
        finally:
            self.session.rollback()
            self.fs.rollback()

    def rollback(self):
        """rollback changes"""
        self.session.rollback()
        self.fs.rollback()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if type is None:
            self.commit()
        else:
            self.rollback()
        return None

class ArchiveUpload(object):
    """handle an upload

A
Ansgar Burchardt 已提交
543
    This class can be used in a with-statement::
544 545 546 547 548 549 550 551 552

       with ArchiveUpload(...) as upload:
          ...

    Doing so will automatically run any required cleanup and also rollback the
    transaction if it was not committed.
    """
    def __init__(self, directory, changes, keyrings):
        self.transaction = ArchiveTransaction()
A
Ansgar Burchardt 已提交
553 554 555 556
        """transaction used to handle the upload
        @type: L{daklib.archive.ArchiveTransaction}
        """

557
        self.session = self.transaction.session
A
Ansgar Burchardt 已提交
558
        """database session"""
559 560 561

        self.original_directory = directory
        self.original_changes = changes
A
Ansgar Burchardt 已提交
562

563
        self.changes = None
A
Ansgar Burchardt 已提交
564 565 566 567
        """upload to process
        @type: L{daklib.upload.Changes}
        """

568
        self.directory = None
A
Ansgar Burchardt 已提交
569 570 571 572
        """directory with temporary copy of files. set by C{prepare}
        @type: str
        """

573 574 575
        self.keyrings = keyrings

        self.fingerprint = self.session.query(Fingerprint).filter_by(fingerprint=changes.primary_fingerprint).one()
A
Ansgar Burchardt 已提交
576 577 578
        """fingerprint of the key used to sign the upload
        @type: L{daklib.dbconn.Fingerprint}
        """
579 580

        self.reject_reasons = []
A
Ansgar Burchardt 已提交
581 582 583 584
        """reasons why the upload cannot by accepted
        @type: list of str
        """

585
        self.warnings = []
A
Ansgar Burchardt 已提交
586 587 588 589 590
        """warnings
        @note: Not used yet.
        @type: list of str
        """

591
        self.final_suites = None
A
Ansgar Burchardt 已提交
592

593
        self.new = False
A
Ansgar Burchardt 已提交
594 595 596
        """upload is NEW. set by C{check}
        @type: bool
        """
597

598 599 600 601 602
        self._checked = False
        """checks passes. set by C{check}
        @type: bool
        """

603 604 605 606 607 608 609 610
        self._new_queue = self.session.query(PolicyQueue).filter_by(queue_name='new').one()
        self._new = self._new_queue.suite

    def prepare(self):
        """prepare upload for further processing

        This copies the files involved to a temporary directory.  If you use
        this method directly, you have to remove the directory given by the
A
Ansgar Burchardt 已提交
611
        C{directory} attribute later on your own.
612

A
Ansgar Burchardt 已提交
613
        Instead of using the method directly, you can also use a with-statement::
614 615 616 617 618 619 620 621 622 623 624 625

           with ArchiveUpload(...) as upload:
              ...

        This will automatically handle any required cleanup.
        """
        assert self.directory is None
        assert self.original_changes.valid_signature

        cnf = Config()
        session = self.transaction.session

626
        self.directory = utils.temp_dirname(parent=cnf.get('Dir::TempPath'),
627
                                            mode=0o2750, group=cnf.unprivgroup)
628 629 630
        with FilesystemTransaction() as fs:
            src = os.path.join(self.original_directory, self.original_changes.filename)
            dst = os.path.join(self.directory, self.original_changes.filename)
J
Joerg Jaspert 已提交
631
            fs.copy(src, dst, mode=0o640)
632 633 634 635 636 637

            self.changes = upload.Changes(self.directory, self.original_changes.filename, self.keyrings)

            for f in self.changes.files.itervalues():
                src = os.path.join(self.original_directory, f.filename)
                dst = os.path.join(self.directory, f.filename)
638 639
                if not os.path.exists(src):
                    continue
J
Joerg Jaspert 已提交
640
                fs.copy(src, dst, mode=0o640)
641 642 643 644 645 646

            source = self.changes.source
            if source is not None:
                for f in source.files.itervalues():
                    src = os.path.join(self.original_directory, f.filename)
                    dst = os.path.join(self.directory, f.filename)
647
                    if not os.path.exists(dst):
648
                        try:
649
                            db_file = self.transaction.get_file(f, source.dsc['Source'], check_hashes=False)
650 651 652 653 654 655
                            db_archive_file = session.query(ArchiveFile).filter_by(file=db_file).first()
                            fs.copy(db_archive_file.path, dst, symlink=True)
                        except KeyError:
                            # Ignore if get_file could not find it. Upload will
                            # probably be rejected later.
                            pass
656 657 658 659 660

    def unpacked_source(self):
        """Path to unpacked source

        Get path to the unpacked source. This method does unpack the source
A
Ansgar Burchardt 已提交
661
        into a temporary directory under C{self.directory} if it has not
662 663
        been done so already.

A
Ansgar Burchardt 已提交
664 665 666
        @rtype:  str or C{None}
        @return: string giving the path to the unpacked source directory
                 or C{None} if no source was included in the upload.
667 668 669 670 671 672 673 674 675 676
        """
        assert self.directory is not None

        source = self.changes.source
        if source is None:
            return None
        dsc_path = os.path.join(self.directory, source._dsc_file.filename)

        sourcedir = os.path.join(self.directory, 'source')
        if not os.path.exists(sourcedir):
677 678
            devnull = open('/dev/null', 'w')
            subprocess.check_call(["dpkg-source", "--no-copy", "--no-check", "-x", dsc_path, sourcedir], shell=False, stdout=devnull)
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
        if not os.path.isdir(sourcedir):
            raise Exception("{0} is not a directory after extracting source package".format(sourcedir))
        return sourcedir

    def _map_suite(self, suite_name):
        for rule in Config().value_list("SuiteMappings"):
            fields = rule.split()
            rtype = fields[0]
            if rtype == "map" or rtype == "silent-map":
                (src, dst) = fields[1:3]
                if src == suite_name:
                    suite_name = dst
                    if rtype != "silent-map":
                        self.warnings.append('Mapping {0} to {0}.'.format(src, dst))
            elif rtype == "ignore":
                ignored = fields[1]
                if suite_name == ignored:
                    self.warnings.append('Ignoring target suite {0}.'.format(ignored))
                    suite_name = None
            elif rtype == "reject":
                rejected = fields[1]
                if suite_name == rejected:
                    self.reject_reasons.append('Uploads to {0} are not accepted.'.format(suite))
            ## XXX: propup-version and map-unreleased not yet implemented
        return suite_name

    def _mapped_suites(self):
        """Get target suites after mappings

A
Ansgar Burchardt 已提交
708 709
        @rtype:  list of L{daklib.dbconn.Suite}
        @return: list giving the mapped target suites of this upload
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
        """
        session = self.session

        suite_names = []
        for dist in self.changes.distributions:
            suite_name = self._map_suite(dist)
            if suite_name is not None:
                suite_names.append(suite_name)

        suites = session.query(Suite).filter(Suite.suite_name.in_(suite_names))
        return suites

    def _check_new(self, suite):
        """Check if upload is NEW

        An upload is NEW if it has binary or source packages that do not have
A
Ansgar Burchardt 已提交
726
        an override in C{suite} OR if it references files ONLY in a tainted
727 728
        archive (eg. when it references files in NEW).

A
Ansgar Burchardt 已提交
729 730
        @rtype:  bool
        @return: C{True} if the upload is NEW, C{False} otherwise
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
        """
        session = self.session

        # Check for missing overrides
        for b in self.changes.binaries:
            override = self._binary_override(suite, b)
            if override is None:
                return True

        if self.changes.source is not None:
            override = self._source_override(suite, self.changes.source)
            if override is None:
                return True

        # Check if we reference a file only in a tainted archive
        files = self.changes.files.values()
        if self.changes.source is not None:
            files.extend(self.changes.source.files.values())
        for f in files:
            query = session.query(ArchiveFile).join(PoolFile).filter(PoolFile.sha1sum == f.sha1sum)
            query_untainted = query.join(Archive).filter(Archive.tainted == False)

            in_archive = (query.first() is not None)
            in_untainted_archive = (query_untainted.first() is not None)

            if in_archive and not in_untainted_archive:
                return True

    def _final_suites(self):
        session = self.session

        mapped_suites = self._mapped_suites()
        final_suites = set()

        for suite in mapped_suites:
            overridesuite = suite
            if suite.overridesuite is not None:
                overridesuite = session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
            if self._check_new(overridesuite):
                self.new = True
            final_suites.add(suite)

        return final_suites

    def _binary_override(self, suite, binary):
        """Get override entry for a binary

A
Ansgar Burchardt 已提交
778 779
        @type  suite: L{daklib.dbconn.Suite}
        @param suite: suite to get override for
780

A
Ansgar Burchardt 已提交
781 782 783 784 785
        @type  binary: L{daklib.upload.Binary}
        @param binary: binary to get override for

        @rtype:  L{daklib.dbconn.Override} or C{None}
        @return: override for the given binary or C{None}
786 787
        """
        if suite.overridesuite is not None:
788
            suite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
789 790 791 792 793 794 795 796 797 798 799 800 801

        query = self.session.query(Override).filter_by(suite=suite, package=binary.control['Package']) \
                .join(Component).filter(Component.component_name == binary.component) \
                .join(OverrideType).filter(OverrideType.overridetype == binary.type)

        try:
            return query.one()
        except NoResultFound:
            return None

    def _source_override(self, suite, source):
        """Get override entry for a source

A
Ansgar Burchardt 已提交
802 803 804 805 806
        @type  suite: L{daklib.dbconn.Suite}
        @param suite: suite to get override for

        @type  source: L{daklib.upload.Source}
        @param source: source to get override for
807

A
Ansgar Burchardt 已提交
808 809
        @rtype:  L{daklib.dbconn.Override} or C{None}
        @return: override for the given source or C{None}
810 811
        """
        if suite.overridesuite is not None:
812
            suite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
813 814 815 816 817 818 819 820 821 822

        # XXX: component for source?
        query = self.session.query(Override).filter_by(suite=suite, package=source.dsc['Source']) \
                .join(OverrideType).filter(OverrideType.overridetype == 'dsc')

        try:
            return query.one()
        except NoResultFound:
            return None

823 824 825 826
    def _binary_component(self, suite, binary, only_overrides=True):
        """get component for a binary

        By default this will only look at overrides to get the right component;
A
Ansgar Burchardt 已提交
827 828
        if C{only_overrides} is C{False} this method will also look at the
        Section field.
829

A
Ansgar Burchardt 已提交
830
        @type  suite: L{daklib.dbconn.Suite}
831

A
Ansgar Burchardt 已提交
832
        @type  binary: L{daklib.upload.Binary}
833

A
Ansgar Burchardt 已提交
834 835 836 837
        @type  only_overrides: bool
        @param only_overrides: only use overrides to get the right component

        @rtype: L{daklib.dbconn.Component} or C{None}
838 839 840 841 842 843
        """
        override = self._binary_override(suite, binary)
        if override is not None:
            return override.component
        if only_overrides:
            return None
844
        return get_mapped_component(binary.component, self.session)
845

846 847 848
    def check(self, force=False):
        """run checks against the upload

A
Ansgar Burchardt 已提交
849 850
        @type  force: bool
        @param force: ignore failing forcable checks
851

A
Ansgar Burchardt 已提交
852 853
        @rtype:  bool
        @return: C{True} if all checks passed, C{False} otherwise
854 855 856 857 858
        """
        # XXX: needs to be better structured.
        assert self.changes.valid_signature

        try:
859
            # Validate signatures and hashes before we do any real work:
860 861 862 863
            for chk in (
                    checks.SignatureCheck,
                    checks.ChangesCheck,
                    checks.HashesCheck,
864
                    checks.ExternalHashesCheck,
865 866
                    checks.SourceCheck,
                    checks.BinaryCheck,
A
Ansgar Burchardt 已提交
867
                    checks.BinaryTimestampCheck,
868 869 870 871 872 873
                    checks.SingleDistributionCheck,
                    ):
                chk().check(self)

            final_suites = self._final_suites()
            if len(final_suites) == 0:
874
                self.reject_reasons.append('No target suite found. Please check your target distribution and that you uploaded to the right archive.')
875 876
                return False

877 878
            self.final_suites = final_suites

879 880 881 882 883 884 885 886
            for chk in (
                    checks.TransitionCheck,
                    checks.ACLCheck,
                    checks.NoSourceOnlyCheck,
                    checks.LintianCheck,
                    ):
                chk().check(self)

887
            for chk in (
888
                    checks.ACLCheck,
889 890 891 892 893 894 895 896 897 898
                    checks.SourceFormatCheck,
                    checks.SuiteArchitectureCheck,
                    checks.VersionCheck,
                    ):
                for suite in final_suites:
                    chk().per_suite_check(self, suite)

            if len(self.reject_reasons) != 0:
                return False

899
            self._checked = True
900 901 902 903 904 905 906 907 908 909
            return True
        except checks.Reject as e:
            self.reject_reasons.append(unicode(e))
        except Exception as e:
            self.reject_reasons.append("Processing raised an exception: {0}.\n{1}".format(e, traceback.format_exc()))
        return False

    def _install_to_suite(self, suite, source_component_func, binary_component_func, source_suites=None, extra_source_archives=None):
        """Install upload to the given suite

A
Ansgar Burchardt 已提交
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
        @type  suite: L{daklib.dbconn.Suite}
        @param suite: suite to install the package into. This is the real suite,
                      ie. after any redirection to NEW or a policy queue

        @param source_component_func: function to get the L{daklib.dbconn.Component}
                                      for a L{daklib.upload.Source} object

        @param binary_component_func: function to get the L{daklib.dbconn.Component}
                                      for a L{daklib.upload.Binary} object

        @param source_suites: see L{daklib.archive.ArchiveTransaction.install_binary}

        @param extra_source_archives: see L{daklib.archive.ArchiveTransaction.install_binary}

        @return: tuple with two elements. The first is a L{daklib.dbconn.DBSource}
                 object for the install source or C{None} if no source was
                 included. The second is a list of L{daklib.dbconn.DBBinary}
                 objects for the installed binary packages.
928 929 930 931 932 933 934
        """
        # XXX: move this function to ArchiveTransaction?

        control = self.changes.changes
        changed_by = get_or_set_maintainer(control.get('Changed-By', control['Maintainer']), self.session)

        if source_suites is None:
935
            source_suites = self.session.query(Suite).join((VersionCheck, VersionCheck.reference_id == Suite.suite_id)).filter(VersionCheck.check == 'Enhances').filter(VersionCheck.suite == suite).subquery()
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

        source = self.changes.source
        if source is not None:
            component = source_component_func(source)
            db_source = self.transaction.install_source(self.directory, source, suite, component, changed_by, fingerprint=self.fingerprint)
        else:
            db_source = None

        db_binaries = []
        for binary in self.changes.binaries:
            component = binary_component_func(binary)
            db_binary = self.transaction.install_binary(self.directory, binary, suite, component, fingerprint=self.fingerprint, source_suites=source_suites, extra_source_archives=extra_source_archives)
            db_binaries.append(db_binary)

        if suite.copychanges:
            src = os.path.join(self.directory, self.changes.filename)
            dst = os.path.join(suite.archive.path, 'dists', suite.suite_name, self.changes.filename)
            self.transaction.fs.copy(src, dst)

        return (db_source, db_binaries)

    def _install_changes(self):
        assert self.changes.valid_signature
        control = self.changes.changes
        session = self.transaction.session
        config = Config()

        changelog_id = None
        # Only add changelog for sourceful uploads and binNMUs
        if 'source' in self.changes.architectures or re_bin_only_nmu.search(control['Version']):
            query = 'INSERT INTO changelogs_text (changelog) VALUES (:changelog) RETURNING id'
            changelog_id = session.execute(query, {'changelog': control['Changes']}).scalar()
            assert changelog_id is not None

        db_changes = DBChange()
        db_changes.changesname = self.changes.filename
        db_changes.source = control['Source']
        db_changes.binaries = control.get('Binary', None)
        db_changes.architecture = control['Architecture']
        db_changes.version = control['Version']
        db_changes.distribution = control['Distribution']
        db_changes.urgency = control['Urgency']
        db_changes.maintainer = control['Maintainer']
        db_changes.changedby = control.get('Changed-By', control['Maintainer'])
        db_changes.date = control['Date']
        db_changes.fingerprint = self.fingerprint.fingerprint
        db_changes.changelog_id = changelog_id
        db_changes.closes = self.changes.closed_bugs

        self.transaction.session.add(db_changes)
        self.transaction.session.flush()

        return db_changes

    def _install_policy(self, policy_queue, target_suite, db_changes, db_source, db_binaries):
        u = PolicyQueueUpload()
        u.policy_queue = policy_queue
        u.target_suite = target_suite
        u.changes = db_changes
        u.source = db_source
        u.binaries = db_binaries
        self.transaction.session.add(u)
        self.transaction.session.flush()

        dst = os.path.join(policy_queue.path, self.changes.filename)
        self.transaction.fs.copy(self.changes.path, dst)

        return u

    def try_autobyhand(self):
        """Try AUTOBYHAND

        Try to handle byhand packages automatically.

A
Ansgar Burchardt 已提交
1010 1011
        @rtype:  list of L{daklib.upload.HashedFile}
        @return: list of remaining byhand files
1012 1013 1014 1015
        """
        assert len(self.reject_reasons) == 0
        assert self.changes.valid_signature
        assert self.final_suites is not None
1016
        assert self._checked
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

        byhand = self.changes.byhand_files
        if len(byhand) == 0:
            return True

        suites = list(self.final_suites)
        assert len(suites) == 1, "BYHAND uploads must be to a single suite"
        suite = suites[0]

        cnf = Config()
        control = self.changes.changes
        automatic_byhand_packages = cnf.subtree("AutomaticByHandPackages")

        remaining = []
        for f in byhand:
1032 1033 1034 1035 1036 1037 1038
            parts = f.filename.split('_', 2)
            if len(parts) != 3:
                print "W: unexpected byhand filename {0}. No automatic processing.".format(f.filename)
                remaining.append(f)
                continue

            package, version, archext = parts
1039 1040
            arch, ext = archext.split('.', 1)

1041 1042 1043
            try:
                rule = automatic_byhand_packages.subtree(package)
            except KeyError:
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
                remaining.append(f)
                continue

            if rule['Source'] != control['Source'] or rule['Section'] != f.section or rule['Extension'] != ext:
                remaining.append(f)
                continue

            script = rule['Script']
            retcode = subprocess.call([script, os.path.join(self.directory, f.filename), control['Version'], arch, os.path.join(self.directory, self.changes.filename)], shell=False)
            if retcode != 0:
                print "W: error processing {0}.".format(f.filename)
                remaining.append(f)

        return len(remaining) == 0

    def _install_byhand(self, policy_queue_upload, hashed_file):
A
Ansgar Burchardt 已提交
1060 1061 1062 1063 1064
        """install byhand file

        @type  policy_queue_upload: L{daklib.dbconn.PolicyQueueUpload}

        @type  hashed_file: L{daklib.upload.HashedFile}
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        """
        fs = self.transaction.fs
        session = self.transaction.session
        policy_queue = policy_queue_upload.policy_queue

        byhand_file = PolicyQueueByhandFile()
        byhand_file.upload = policy_queue_upload
        byhand_file.filename = hashed_file.filename
        session.add(byhand_file)
        session.flush()

        src = os.path.join(self.directory, hashed_file.filename)
        dst = os.path.join(policy_queue.path, hashed_file.filename)
        fs.copy(src, dst)

        return byhand_file

    def _do_bts_versiontracking(self):
        cnf = Config()
        fs = self.transaction.fs

        btsdir = cnf.get('Dir::BTSVersionTrack')
        if btsdir is None or btsdir == '':
            return

        base = os.path.join(btsdir, self.changes.filename[:-8])

        # version history
        sourcedir = self.unpacked_source()
        if sourcedir is not None:
            fh = open(os.path.join(sourcedir, 'debian', 'changelog'), 'r')
            versions = fs.create("{0}.versions".format(base), mode=0o644)
            for line in fh.readlines():
                if re_changelog_versions.match(line):
                    versions.write(line)
            fh.close()
            versions.close()

        # binary -> source mapping
        debinfo = fs.create("{0}.debinfo".format(base), mode=0o644)
        for binary in self.changes.binaries:
            control = binary.control
            source_package, source_version = binary.source
            line = " ".join([control['Package'], control['Version'], source_package, source_version])
            print >>debinfo, line
        debinfo.close()

1112 1113 1114 1115 1116
    def _policy_queue(self, suite):
        if suite.policy_queue is not None:
            return suite.policy_queue
        return None

1117 1118 1119
    def install(self):
        """install upload

A
Ansgar Burchardt 已提交
1120
        Install upload to a suite or policy queue.  This method does B{not}
1121 1122
        handle uploads to NEW.

A
Ansgar Burchardt 已提交
1123
        You need to have called the C{check} method before calling this method.
1124 1125 1126 1127
        """
        assert len(self.reject_reasons) == 0
        assert self.changes.valid_signature
        assert self.final_suites is not None
1128
        assert self._checked
1129 1130 1131 1132 1133 1134 1135 1136 1137
        assert not self.new

        db_changes = self._install_changes()

        for suite in self.final_suites:
            overridesuite = suite
            if suite.overridesuite is not None:
                overridesuite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()

1138 1139
            policy_queue = self._policy_queue(suite)

1140
            redirected_suite = suite
1141 1142
            if policy_queue is not None:
                redirected_suite = policy_queue.suite
1143

1144 1145
            source_suites = self.session.query(Suite).filter(Suite.suite_id.in_([suite.suite_id, redirected_suite.suite_id])).subquery()

1146
            source_component_func = lambda source: self._source_override(overridesuite, source).component
1147
            binary_component_func = lambda binary: self._binary_component(overridesuite, binary)
1148

1149
            (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])
1150

1151 1152
            if policy_queue is not None:
                self._install_policy(policy_queue, suite, db_changes, db_source, db_binaries)
1153 1154

            # copy to build queues
1155
            if policy_queue is None or policy_queue.send_to_build_queues:
1156
                for build_queue in suite.copy_queues:
1157
                    self._install_to_suite(build_queue.suite, source_component_func, binary_component_func, source_suites=source_suites, extra_source_archives=[suite.archive])
1158 1159 1160 1161 1162 1163

        self._do_bts_versiontracking()

    def install_to_new(self):
        """install upload to NEW

A
Ansgar Burchardt 已提交
1164
        Install upload to NEW.  This method does B{not} handle regular uploads
1165 1166
        to suites or policy queues.

A
Ansgar Burchardt 已提交
1167
        You need to have called the C{check} method before calling this method.
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        """
        # Uploads to NEW are special as we don't have overrides.
        assert len(self.reject_reasons) == 0
        assert self.changes.valid_signature
        assert self.final_suites is not None

        source = self.changes.source
        binaries = self.changes.binaries
        byhand = self.changes.byhand_files

        # we need a suite to guess components
        suites = list(self.final_suites)
        assert len(suites) == 1, "NEW uploads must be to a single suite"
        suite = suites[0]

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
        # decide which NEW queue to use
        if suite.new_queue is None:
            new_queue = self.transaction.session.query(PolicyQueue).filter_by(queue_name='new').one()
        else:
            new_queue = suite.new_queue
        if len(byhand) > 0:
            # There is only one global BYHAND queue
            new_queue = self.transaction.session.query(PolicyQueue).filter_by(queue_name='byhand').one()
        new_suite = new_queue.suite


1194
        def binary_component_func(binary):
1195
            return self._binary_component(suite, binary, only_overrides=False)
1196 1197 1198 1199 1200 1201 1202 1203

        # guess source component
        # XXX: should be moved into an extra method
        binary_component_names = set()
        for binary in binaries:
            component = binary_component_func(binary)
            binary_component_names.add(component.component_name)
        source_component_name = None
1204 1205
        for c in self.session.query(Component).order_by(Component.component_id):
            guess = c.component_name
1206 1207 1208 1209
            if guess in binary_component_names:
                source_component_name = guess
                break
        if source_component_name is None:
1210 1211 1212
            source_component = self.session.query(Component).order_by(Component.component_id).first()
        else:
            source_component = self.session.query(Component).filter_by(component_name=source_component_name).one()
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        source_component_func = lambda source: source_component

        db_changes = self._install_changes()
        (db_source, db_binaries) = self._install_to_suite(new_suite, source_component_func, binary_component_func, source_suites=True, extra_source_archives=[suite.archive])
        policy_upload = self._install_policy(new_queue, suite, db_changes, db_source, db_binaries)

        for f in byhand:
            self._install_byhand(policy_upload, f)

        self._do_bts_versiontracking()

    def commit(self):
        """commit changes"""
        self.transaction.commit()

    def rollback(self):
        """rollback changes"""
        self.transaction.rollback()

    def __enter__(self):
        self.prepare()
        return self

    def __exit__(self, type, value, traceback):
        if self.directory is not None:
            shutil.rmtree(self.directory)
            self.directory = None
        self.changes = None
        self.transaction.rollback()
        return None