dbconn.py 100.3 KB
Newer Older
1
#!/usr/bin/python
M
Mark Hymers 已提交
2

3 4 5 6 7
""" DB access class

@contact: Debian FTPMaster <ftpmaster@debian.org>
@copyright: 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
@copyright: 2008-2009  Mark Hymers <mhy@debian.org>
J
Joerg Jaspert 已提交
8
@copyright: 2009, 2010  Joerg Jaspert <joerg@debian.org>
9
@copyright: 2009  Mike O'Connor <stew@debian.org>
10 11
@license: GNU General Public License version 2 or later
"""
M
Mark Hymers 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

################################################################################

# < mhy> I need a funny comment
# < sgran> two peanuts were walking down a dark street
# < sgran> one was a-salted
#  * mhy looks up the definition of "funny"

################################################################################

36
import os
M
Mark Hymers 已提交
37
import re
M
Mark Hymers 已提交
38
import psycopg2
39
import traceback
J
Joerg Jaspert 已提交
40
import commands
M
Mark Hymers 已提交
41 42 43
from datetime import datetime, timedelta
from errno import ENOENT
from tempfile import mkstemp, mkdtemp
M
Mark Hymers 已提交
44

45 46
from inspect import getargspec

47
import sqlalchemy
48
from sqlalchemy import create_engine, Table, MetaData, Column, Integer
M
Mark Hymers 已提交
49
from sqlalchemy.orm import sessionmaker, mapper, relation
50
from sqlalchemy import types as sqltypes
M
Mark Hymers 已提交
51

M
Mark Hymers 已提交
52 53
# Don't remove this, we re-export the exceptions to scripts which import us
from sqlalchemy.exc import *
54
from sqlalchemy.orm.exc import NoResultFound
M
Mark Hymers 已提交
55

56 57 58
# Only import Config until Queue stuff is changed to store its config
# in the database
from config import Config
M
Mark Hymers 已提交
59
from textutils import fix_maintainer
60
from dak_exceptions import NoSourceFieldError
M
Mark Hymers 已提交
61 62 63

################################################################################

64 65 66
# Patch in support for the debversion field type so that it works during
# reflection

T
Torsten Werner 已提交
67 68 69 70 71 72 73 74
try:
    # that is for sqlalchemy 0.6
    UserDefinedType = sqltypes.UserDefinedType
except:
    # this one for sqlalchemy 0.5
    UserDefinedType = sqltypes.TypeEngine

class DebVersion(UserDefinedType):
75 76 77
    def get_col_spec(self):
        return "DEBVERSION"

78 79 80
    def bind_processor(self, dialect):
        return None

T
Torsten Werner 已提交
81 82
    # ' = None' is needed for sqlalchemy 0.5:
    def result_processor(self, dialect, coltype = None):
83 84
        return None

85
sa_major_version = sqlalchemy.__version__[0:3]
M
Mark Hymers 已提交
86
if sa_major_version in ["0.5", "0.6"]:
C
Chris Lamb 已提交
87 88
    from sqlalchemy.databases import postgres
    postgres.ischema_names['debversion'] = DebVersion
89
else:
M
Mark Hymers 已提交
90
    raise Exception("dak only ported to SQLA versions 0.5 and 0.6.  See daklib/dbconn.py")
91 92 93

################################################################################

94
__all__ = ['IntegrityError', 'SQLAlchemyError', 'DebVersion']
95 96 97

################################################################################

98
def session_wrapper(fn):
C
Chris Lamb 已提交
99 100 101 102
    """
    Wrapper around common ".., session=None):" handling. If the wrapped
    function is called without passing 'session', we create a local one
    and destroy it when the function ends.
103 104 105 106

    Also attaches a commit_or_flush method to the session; if we created a
    local session, this is a synonym for session.commit(), otherwise it is a
    synonym for session.flush().
C
Chris Lamb 已提交
107 108
    """

109 110 111
    def wrapped(*args, **kwargs):
        private_transaction = False

112
        # Find the session object
C
Chris Lamb 已提交
113 114 115
        session = kwargs.get('session')

        if session is None:
116 117 118 119 120 121 122
            if len(args) <= len(getargspec(fn)[0]) - 1:
                # No session specified as last argument or in kwargs
                private_transaction = True
                session = kwargs['session'] = DBConn().session()
            else:
                # Session is last argument in args
                session = args[-1]
123
                if session is None:
M
fixup  
Mark Hymers 已提交
124
                    args = list(args)
125 126
                    session = args[-1] = DBConn().session()
                    private_transaction = True
127 128 129 130 131

        if private_transaction:
            session.commit_or_flush = session.commit
        else:
            session.commit_or_flush = session.flush
132 133 134 135 136 137

        try:
            return fn(*args, **kwargs)
        finally:
            if private_transaction:
                # We created a session; close it.
138
                session.close()
139

140 141 142
    wrapped.__doc__ = fn.__doc__
    wrapped.func_name = fn.func_name

143 144
    return wrapped

F
Frank Lichtenheld 已提交
145 146
__all__.append('session_wrapper')

147 148
################################################################################

M
Mark Hymers 已提交
149
class Architecture(object):
T
Torsten Werner 已提交
150 151 152
    def __init__(self, arch_string = None, description = None):
        self.arch_string = arch_string
        self.description = description
M
Mark Hymers 已提交
153

154 155 156 157 158 159 160 161 162 163 164 165
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.arch_string== val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.arch_string != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
166 167 168
    def __repr__(self):
        return '<Architecture %s>' % self.arch_string

169 170
__all__.append('Architecture')

171
@session_wrapper
172 173 174 175 176 177 178 179 180 181 182 183 184 185
def get_architecture(architecture, session=None):
    """
    Returns database id for given C{architecture}.

    @type architecture: string
    @param architecture: The name of the architecture

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Architecture
    @return: Architecture object for the given arch (None if not present)
    """
186

187
    q = session.query(Architecture).filter_by(arch_string=architecture)
188

189 190 191 192
    try:
        return q.one()
    except NoResultFound:
        return None
193

194 195
__all__.append('get_architecture')

196
@session_wrapper
M
Mark Hymers 已提交
197 198 199 200
def get_architecture_suites(architecture, session=None):
    """
    Returns list of Suite objects for given C{architecture} name

J
Joerg Jaspert 已提交
201 202
    @type architecture: str
    @param architecture: Architecture name to search for
M
Mark Hymers 已提交
203 204 205 206 207 208 209 210 211 212 213 214

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: list of Suite objects for the given name (may be empty)
    """

    q = session.query(Suite)
    q = q.join(SuiteArchitecture)
    q = q.join(Architecture).filter_by(arch_string=architecture).order_by('suite_name')
215 216 217 218

    ret = q.all()

    return ret
M
Mark Hymers 已提交
219

220 221
__all__.append('get_architecture_suites')

M
Mark Hymers 已提交
222 223
################################################################################

M
Mark Hymers 已提交
224
class Archive(object):
M
Mark Hymers 已提交
225 226
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
227 228

    def __repr__(self):
C
Chris Lamb 已提交
229
        return '<Archive %s>' % self.archive_name
M
Mark Hymers 已提交
230

231 232
__all__.append('Archive')

233
@session_wrapper
234 235
def get_archive(archive, session=None):
    """
F
Frank Lichtenheld 已提交
236
    returns database id for given C{archive}.
237 238 239 240 241 242 243 244 245 246 247 248 249

    @type archive: string
    @param archive: the name of the arhive

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Archive
    @return: Archive object for the given name (None if not present)

    """
    archive = archive.lower()
250

251
    q = session.query(Archive).filter_by(archive_name=archive)
252

253 254 255 256
    try:
        return q.one()
    except NoResultFound:
        return None
257

258
__all__.append('get_archive')
259

M
Mark Hymers 已提交
260 261
################################################################################

M
Mark Hymers 已提交
262
class BinAssociation(object):
M
Mark Hymers 已提交
263 264
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
265 266

    def __repr__(self):
M
Mark Hymers 已提交
267
        return '<BinAssociation %s (%s, %s)>' % (self.ba_id, self.binary, self.suite)
M
Mark Hymers 已提交
268

269 270
__all__.append('BinAssociation')

M
Mark Hymers 已提交
271 272
################################################################################

M
Mike O'Connor 已提交
273 274 275 276 277 278 279 280 281 282 283
class BinContents(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<BinContents (%s, %s)>' % (self.binary, self.filename)

__all__.append('BinContents')

################################################################################

284
class DBBinary(object):
M
Mark Hymers 已提交
285 286
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
287 288

    def __repr__(self):
289
        return '<DBBinary %s (%s, %s)>' % (self.package, self.version, self.architecture)
M
Mark Hymers 已提交
290

291
__all__.append('DBBinary')
292

293
@session_wrapper
294 295 296 297
def get_suites_binary_in(package, session=None):
    """
    Returns list of Suite objects which given C{package} name is in

J
Joerg Jaspert 已提交
298 299
    @type package: str
    @param package: DBBinary package name to search for
300 301 302 303 304

    @rtype: list
    @return: list of Suite objects for the given package
    """

305
    return session.query(Suite).join(BinAssociation).join(DBBinary).filter_by(package=package).all()
306 307 308

__all__.append('get_suites_binary_in')

309
@session_wrapper
310
def get_binary_from_id(binary_id, session=None):
311
    """
312
    Returns DBBinary object for given C{id}
313

314 315
    @type binary_id: int
    @param binary_id: Id of the required binary
316 317 318 319 320

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

321 322
    @rtype: DBBinary
    @return: DBBinary object for the given binary (None if not present)
323
    """
324

325
    q = session.query(DBBinary).filter_by(binary_id=binary_id)
326

327 328 329 330
    try:
        return q.one()
    except NoResultFound:
        return None
M
Mark Hymers 已提交
331

332 333
__all__.append('get_binary_from_id')

334
@session_wrapper
335
def get_binaries_from_name(package, version=None, architecture=None, session=None):
M
Mark Hymers 已提交
336
    """
337
    Returns list of DBBinary objects for given C{package} name
M
Mark Hymers 已提交
338 339

    @type package: str
340
    @param package: DBBinary package name to search for
M
Mark Hymers 已提交
341

342 343 344
    @type version: str or None
    @param version: Version to search for (or None)

J
Joerg Jaspert 已提交
345 346
    @type architecture: str, list or None
    @param architecture: Architectures to limit to (or None if no limit)
347

M
Mark Hymers 已提交
348 349 350 351 352
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
353
    @return: list of DBBinary objects for the given name (may be empty)
M
Mark Hymers 已提交
354
    """
355 356 357 358 359 360 361 362 363 364 365

    q = session.query(DBBinary).filter_by(package=package)

    if version is not None:
        q = q.filter_by(version=version)

    if architecture is not None:
        if not isinstance(architecture, list):
            architecture = [architecture]
        q = q.join(Architecture).filter(Architecture.arch_string.in_(architecture))

366 367 368
    ret = q.all()

    return ret
M
Mark Hymers 已提交
369

370 371
__all__.append('get_binaries_from_name')

372
@session_wrapper
373 374 375 376 377 378 379 380 381 382 383 384 385 386
def get_binaries_from_source_id(source_id, session=None):
    """
    Returns list of DBBinary objects for given C{source_id}

    @type source_id: int
    @param source_id: source_id to search for

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: list of DBBinary objects for the given name (may be empty)
    """
387

388
    return session.query(DBBinary).filter_by(source_id=source_id).all()
389 390 391

__all__.append('get_binaries_from_source_id')

392
@session_wrapper
M
Mark Hymers 已提交
393 394 395 396 397 398
def get_binary_from_name_suite(package, suitename, session=None):
    ### For dak examine-package
    ### XXX: Doesn't use object API yet

    sql = """SELECT DISTINCT(b.package), b.version, c.name, su.suite_name
             FROM binaries b, files fi, location l, component c, bin_associations ba, suite su
399
             WHERE b.package='%(package)s'
M
Mark Hymers 已提交
400 401 402 403 404
               AND b.file = fi.id
               AND fi.location = l.id
               AND l.component = c.id
               AND ba.bin=b.id
               AND ba.suite = su.id
405
               AND su.suite_name %(suitename)s
M
Mark Hymers 已提交
406 407
          ORDER BY b.version DESC"""

408
    return session.execute(sql % {'package': package, 'suitename': suitename})
M
Mark Hymers 已提交
409 410 411

__all__.append('get_binary_from_name_suite')

412
@session_wrapper
413
def get_binary_components(package, suitename, arch, session=None):
414
    # Check for packages that have moved from one component to another
415 416 417 418 419 420 421 422 423 424
    query = """SELECT c.name FROM binaries b, bin_associations ba, suite s, location l, component c, architecture a, files f
    WHERE b.package=:package AND s.suite_name=:suitename
      AND (a.arch_string = :arch OR a.arch_string = 'all')
      AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
      AND f.location = l.id
      AND l.component = c.id
      AND b.file = f.id"""

    vals = {'package': package, 'suitename': suitename, 'arch': arch}

425
    return session.execute(query, vals)
426 427

__all__.append('get_binary_components')
428

M
Mark Hymers 已提交
429 430
################################################################################

431 432 433 434
class BinaryACL(object):
    def __init__(self, *args, **kwargs):
        pass

435 436 437
    def __repr__(self):
        return '<BinaryACL %s>' % self.binary_acl_id

438 439 440 441 442 443 444 445
__all__.append('BinaryACL')

################################################################################

class BinaryACLMap(object):
    def __init__(self, *args, **kwargs):
        pass

446 447 448
    def __repr__(self):
        return '<BinaryACLMap %s>' % self.binary_acl_map_id

449 450 451 452
__all__.append('BinaryACLMap')

################################################################################

M
Mark Hymers 已提交
453 454 455 456
MINIMAL_APT_CONF="""
Dir
{
   ArchiveDir "%(archivepath)s";
J
Joerg Jaspert 已提交
457 458
   OverrideDir "%(overridedir)s";
   CacheDir "%(cachedir)s";
M
Mark Hymers 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
};

Default
{
   Packages::Compress ". bzip2 gzip";
   Sources::Compress ". bzip2 gzip";
   DeLinkLimit 0;
   FileMode 0664;
}

bindirectory "incoming"
{
   Packages "Packages";
   Contents " ";

   BinOverride "override.sid.all3";
   BinCacheDB "packages-accepted.db";

   FileList "%(filelist)s";

   PathPrefix "";
   Packages::Extensions ".deb .udeb";
};

bindirectory "incoming/"
{
   Sources "Sources";
   BinOverride "override.sid.all3";
   SrcOverride "override.sid.all3.src";
   FileList "%(filelist)s";
};
"""

492 493 494 495 496
class BuildQueue(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
497
        return '<BuildQueue %s>' % self.queue_name
498

M
Mark Hymers 已提交
499
    def write_metadata(self, starttime, force=False):
M
Mark Hymers 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512
        # Do we write out metafiles?
        if not (force or self.generate_metadata):
            return

        session = DBConn().session().object_session(self)

        fl_fd = fl_name = ac_fd = ac_name = None
        tempdir = None
        arches = " ".join([ a.arch_string for a in session.query(Architecture).all() if a.arch_string != 'source' ])
        startdir = os.getcwd()

        try:
            # Grab files we want to include
M
Mark Hymers 已提交
513
            newer = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueueFile.lastused + timedelta(seconds=self.stay_of_execution) > starttime).all()
M
Mark Hymers 已提交
514 515 516 517 518 519
            # Write file list with newer files
            (fl_fd, fl_name) = mkstemp()
            for n in newer:
                os.write(fl_fd, '%s\n' % n.fullpath)
            os.close(fl_fd)

J
Joerg Jaspert 已提交
520 521
            cnf = Config()

M
Mark Hymers 已提交
522 523 524 525
            # Write minimal apt.conf
            # TODO: Remove hardcoding from template
            (ac_fd, ac_name) = mkstemp()
            os.write(ac_fd, MINIMAL_APT_CONF % {'archivepath': self.path,
J
Joerg Jaspert 已提交
526 527 528 529
                                                'filelist': fl_name,
                                                'cachedir': cnf["Dir::Cache"],
                                                'overridedir': cnf["Dir::Override"],
                                                })
M
Mark Hymers 已提交
530
            os.close(ac_fd)
M
Mark Hymers 已提交
531 532

            # Run apt-ftparchive generate
M
Mark Hymers 已提交
533 534
            os.chdir(os.path.dirname(ac_name))
            os.system('apt-ftparchive -qq -o APT::FTPArchive::Contents=off generate %s' % os.path.basename(ac_name))
M
Mark Hymers 已提交
535 536 537 538 539 540

            # Run apt-ftparchive release
            # TODO: Eww - fix this
            bname = os.path.basename(self.path)
            os.chdir(self.path)
            os.chdir('..')
541 542 543 544 545 546 547 548

            # We have to remove the Release file otherwise it'll be included in the
            # new one
            try:
                os.unlink(os.path.join(bname, 'Release'))
            except OSError:
                pass

M
argh  
Mark Hymers 已提交
549
            os.system("""apt-ftparchive -qq -o APT::FTPArchive::Release::Origin="%s" -o APT::FTPArchive::Release::Label="%s" -o APT::FTPArchive::Release::Description="%s" -o APT::FTPArchive::Release::Architectures="%s" release %s > Release""" % (self.origin, self.label, self.releasedescription, arches, bname))
M
Mark Hymers 已提交
550

J
Joerg Jaspert 已提交
551 552 553 554 555 556
            # Crude hack with open and append, but this whole section is and should be redone.
            if self.notautomatic:
                release=open("Release", "a")
                release.write("NotAutomatic: yes")
                release.close()

M
Mark Hymers 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
            # Sign if necessary
            if self.signingkey:
                keyring = "--secret-keyring \"%s\"" % cnf["Dinstall::SigningKeyring"]
                if cnf.has_key("Dinstall::SigningPubKeyring"):
                    keyring += " --keyring \"%s\"" % cnf["Dinstall::SigningPubKeyring"]

                os.system("gpg %s --no-options --batch --no-tty --armour --default-key %s --detach-sign -o Release.gpg Release""" % (keyring, self.signingkey))

            # Move the files if we got this far
            os.rename('Release', os.path.join(bname, 'Release'))
            if self.signingkey:
                os.rename('Release.gpg', os.path.join(bname, 'Release.gpg'))

        # Clean up any left behind files
        finally:
            os.chdir(startdir)
            if fl_fd:
                try:
                    os.close(fl_fd)
                except OSError:
                    pass

            if fl_name:
                try:
                    os.unlink(fl_name)
                except OSError:
                    pass

            if ac_fd:
                try:
                    os.close(ac_fd)
                except OSError:
                    pass

            if ac_name:
                try:
                    os.unlink(ac_name)
                except OSError:
                    pass

M
Mark Hymers 已提交
597
    def clean_and_update(self, starttime, Logger, dryrun=False):
M
Mark Hymers 已提交
598 599 600
        """WARNING: This routine commits for you"""
        session = DBConn().session().object_session(self)

M
Mark Hymers 已提交
601
        if self.generate_metadata and not dryrun:
M
Mark Hymers 已提交
602
            self.write_metadata(starttime)
M
Mark Hymers 已提交
603 604

        # Grab files older than our execution time
M
Mark Hymers 已提交
605
        older = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueueFile.lastused + timedelta(seconds=self.stay_of_execution) <= starttime).all()
M
Mark Hymers 已提交
606 607 608 609 610

        for o in older:
            killdb = False
            try:
                if dryrun:
M
Mark Hymers 已提交
611
                    Logger.log(["I: Would have removed %s from the queue" % o.fullpath])
M
Mark Hymers 已提交
612
                else:
M
Mark Hymers 已提交
613
                    Logger.log(["I: Removing %s from the queue" % o.fullpath])
M
Mark Hymers 已提交
614 615 616 617 618 619 620 621
                    os.unlink(o.fullpath)
                    killdb = True
            except OSError, e:
                # If it wasn't there, don't worry
                if e.errno == ENOENT:
                    killdb = True
                else:
                    # TODO: Replace with proper logging call
M
Mark Hymers 已提交
622
                    Logger.log(["E: Could not remove %s" % o.fullpath])
M
Mark Hymers 已提交
623 624 625 626 627 628

            if killdb:
                session.delete(o)

        session.commit()

M
Mark Hymers 已提交
629
        for f in os.listdir(self.path):
J
Joerg Jaspert 已提交
630
            if f.startswith('Packages') or f.startswith('Source') or f.startswith('Release') or f.startswith('advisory'):
M
Mark Hymers 已提交
631 632 633 634 635 636 637
                continue

            try:
                r = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter_by(filename = f).one()
            except NoResultFound:
                fp = os.path.join(self.path, f)
                if dryrun:
M
Mark Hymers 已提交
638
                    Logger.log(["I: Would remove unused link %s" % fp])
M
Mark Hymers 已提交
639
                else:
M
Mark Hymers 已提交
640
                    Logger.log(["I: Removing unused link %s" % fp])
M
Mark Hymers 已提交
641 642 643
                    try:
                        os.unlink(fp)
                    except OSError:
M
Mark Hymers 已提交
644
                        Logger.log(["E: Failed to unlink unreferenced file %s" % r.fullpath])
M
Mark Hymers 已提交
645

646 647 648 649 650 651 652 653 654 655 656
    def add_file_from_pool(self, poolfile):
        """Copies a file into the pool.  Assumes that the PoolFile object is
        attached to the same SQLAlchemy session as the Queue object is.

        The caller is responsible for committing after calling this function."""
        poolfile_basename = poolfile.filename[poolfile.filename.rindex(os.sep)+1:]

        # Check if we have a file of this name or this ID already
        for f in self.queuefiles:
            if f.fileid is not None and f.fileid == poolfile.file_id or \
               f.poolfile.filename == poolfile_basename:
M
Mark Hymers 已提交
657
                   # In this case, update the BuildQueueFile entry so we
658 659
                   # don't remove it too early
                   f.lastused = datetime.now()
660
                   DBConn().session().object_session(poolfile).add(f)
661 662
                   return f

M
Mark Hymers 已提交
663 664
        # Prepare BuildQueueFile object
        qf = BuildQueueFile()
M
hmm...  
Mark Hymers 已提交
665
        qf.build_queue_id = self.queue_id
666
        qf.lastused = datetime.now()
667
        qf.filename = poolfile_basename
668

M
Mark Hymers 已提交
669
        targetpath = poolfile.fullpath
670 671 672
        queuepath = os.path.join(self.path, poolfile_basename)

        try:
M
Mark Hymers 已提交
673
            if self.copy_files:
674 675
                # We need to copy instead of symlink
                import utils
M
Mark Hymers 已提交
676
                utils.copy(targetpath, queuepath)
677 678 679
                # NULL in the fileid field implies a copy
                qf.fileid = None
            else:
M
Mark Hymers 已提交
680
                os.symlink(targetpath, queuepath)
681 682 683 684 685 686 687 688 689 690 691 692 693
                qf.fileid = poolfile.file_id
        except OSError:
            return None

        # Get the same session as the PoolFile is using and add the qf to it
        DBConn().session().object_session(poolfile).add(qf)

        return qf


__all__.append('BuildQueue')

@session_wrapper
694
def get_build_queue(queuename, session=None):
695
    """
696
    Returns BuildQueue object for given C{queue name}, creating it if it does not
697 698 699 700 701 702 703 704 705
    exist.

    @type queuename: string
    @param queuename: The name of the queue

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

706 707
    @rtype: BuildQueue
    @return: BuildQueue object for the given queue
708 709
    """

710
    q = session.query(BuildQueue).filter_by(queue_name=queuename)
711 712 713 714 715 716

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

717
__all__.append('get_build_queue')
718 719 720 721 722 723 724 725

################################################################################

class BuildQueueFile(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
M
Mark Hymers 已提交
726
        return '<BuildQueueFile %s (%s)>' % (self.filename, self.build_queue_id)
727

M
Mark Hymers 已提交
728 729 730 731
    @property
    def fullpath(self):
        return os.path.join(self.buildqueue.path, self.filename)

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

__all__.append('BuildQueueFile')

################################################################################

class ChangePendingBinary(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ChangePendingBinary %s>' % self.change_pending_binary_id

__all__.append('ChangePendingBinary')

################################################################################

class ChangePendingFile(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ChangePendingFile %s>' % self.change_pending_file_id

__all__.append('ChangePendingFile')

################################################################################

class ChangePendingSource(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ChangePendingSource %s>' % self.change_pending_source_id

__all__.append('ChangePendingSource')

################################################################################

M
Mark Hymers 已提交
770
class Component(object):
M
Mark Hymers 已提交
771 772
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
773

774 775 776 777 778 779 780 781 782 783 784 785
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.component_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.component_name != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
786 787 788
    def __repr__(self):
        return '<Component %s>' % self.component_name

789 790 791

__all__.append('Component')

792
@session_wrapper
793 794 795 796 797 798 799 800 801 802 803 804
def get_component(component, session=None):
    """
    Returns database id for given C{component}.

    @type component: string
    @param component: The name of the override type

    @rtype: int
    @return: the database id for the given component

    """
    component = component.lower()
805

806
    q = session.query(Component).filter_by(component_name=component)
807

808 809 810 811
    try:
        return q.one()
    except NoResultFound:
        return None
812

813 814
__all__.append('get_component')

M
Mark Hymers 已提交
815 816
################################################################################

M
Mark Hymers 已提交
817
class DBConfig(object):
M
Mark Hymers 已提交
818 819
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
820 821 822 823

    def __repr__(self):
        return '<DBConfig %s>' % self.name

824 825
__all__.append('DBConfig')

M
Mark Hymers 已提交
826 827
################################################################################

828
@session_wrapper
829 830 831 832 833 834 835 836 837 838
def get_or_set_contents_file_id(filename, session=None):
    """
    Returns database id for given filename.

    If no matching file is found, a row is inserted.

    @type filename: string
    @param filename: The filename
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
839 840
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
841 842 843 844 845

    @rtype: int
    @return: the database id for the given component
    """

846
    q = session.query(ContentFilename).filter_by(filename=filename)
847 848 849 850

    try:
        ret = q.one().cafilename_id
    except NoResultFound:
851 852 853
        cf = ContentFilename()
        cf.filename = filename
        session.add(cf)
854
        session.commit_or_flush()
855
        ret = cf.cafilename_id
856

857
    return ret
858 859 860

__all__.append('get_or_set_contents_file_id')

861
@session_wrapper
M
Mark Hymers 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
def get_contents(suite, overridetype, section=None, session=None):
    """
    Returns contents for a suite / overridetype combination, limiting
    to a section if not None.

    @type suite: Suite
    @param suite: Suite object

    @type overridetype: OverrideType
    @param overridetype: OverrideType object

    @type section: Section
    @param section: Optional section object to limit results to

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: ResultsProxy
    @return: ResultsProxy object set up to return tuples of (filename, section,
    package, arch_id)
    """

    # find me all of the contents for a given suite
    contents_q = """SELECT (p.path||'/'||n.file) AS fn,
                            s.section,
                            b.package,
                            b.architecture
                   FROM content_associations c join content_file_paths p ON (c.filepath=p.id)
                   JOIN content_file_names n ON (c.filename=n.id)
                   JOIN binaries b ON (b.id=c.binary_pkg)
                   JOIN override o ON (o.package=b.package)
                   JOIN section s ON (s.id=o.section)
                   WHERE o.suite = :suiteid AND o.type = :overridetypeid
                   AND b.type=:overridetypename"""

    vals = {'suiteid': suite.suite_id,
            'overridetypeid': overridetype.overridetype_id,
            'overridetypename': overridetype.overridetype}

    if section is not None:
        contents_q += " AND s.id = :sectionid"
        vals['sectionid'] = section.section_id

    contents_q += " ORDER BY fn"

908
    return session.execute(contents_q, vals)
M
Mark Hymers 已提交
909 910 911

__all__.append('get_contents')

M
Mark Hymers 已提交
912 913
################################################################################

M
Mark Hymers 已提交
914
class ContentFilepath(object):
M
Mark Hymers 已提交
915 916
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
917 918 919 920

    def __repr__(self):
        return '<ContentFilepath %s>' % self.filepath

921 922
__all__.append('ContentFilepath')

923
@session_wrapper
M
Mark Hymers 已提交
924
def get_or_set_contents_path_id(filepath, session=None):
925 926 927 928 929
    """
    Returns database id for given path.

    If no matching file is found, a row is inserted.

J
Joerg Jaspert 已提交
930 931 932
    @type filepath: string
    @param filepath: The filepath

933 934
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
935 936
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
937 938 939 940 941

    @rtype: int
    @return: the database id for the given path
    """

942
    q = session.query(ContentFilepath).filter_by(filepath=filepath)
943 944 945 946

    try:
        ret = q.one().cafilepath_id
    except NoResultFound:
947 948 949
        cf = ContentFilepath()
        cf.filepath = filepath
        session.add(cf)
950
        session.commit_or_flush()
951
        ret = cf.cafilepath_id
952

953
    return ret
954 955 956

__all__.append('get_or_set_contents_path_id')

M
Mark Hymers 已提交
957 958
################################################################################

959
class ContentAssociation(object):
M
Mark Hymers 已提交
960 961
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
962 963 964 965

    def __repr__(self):
        return '<ContentAssociation %s>' % self.ca_id

966 967
__all__.append('ContentAssociation')

968 969 970 971 972 973 974 975 976 977 978 979
def insert_content_paths(binary_id, fullpaths, session=None):
    """
    Make sure given path is associated with given binary id

    @type binary_id: int
    @param binary_id: the id of the binary
    @type fullpaths: list
    @param fullpaths: the list of paths of the file being associated with the binary
    @type session: SQLAlchemy session
    @param session: Optional SQLAlchemy session.  If this is passed, the caller
    is responsible for ensuring a transaction has begun and committing the
    results or rolling back based on the result code.  If not passed, a commit
M
Mark Hymers 已提交
980 981
    will be performed at the end of the function, otherwise the caller is
    responsible for commiting.
982 983 984 985 986 987 988 989 990 991

    @return: True upon success
    """

    privatetrans = False
    if session is None:
        session = DBConn().session()
        privatetrans = True

    try:
M
Mark Hymers 已提交
992
        # Insert paths
993 994 995 996 997
        def generate_path_dicts():
            for fullpath in fullpaths:
                if fullpath.startswith( './' ):
                    fullpath = fullpath[2:]

998
                yield {'filename':fullpath, 'id': binary_id }
999

1000 1001 1002
        for d in generate_path_dicts():
            session.execute( "INSERT INTO bin_contents ( file, binary_id ) VALUES ( :filename, :id )",
                         d )
1003

M
Mike O'Connor 已提交
1004
        session.commit()
1005
        if privatetrans:
M
Mark Hymers 已提交
1006
            session.close()
1007
        return True
M
Mark Hymers 已提交
1008

1009 1010 1011 1012 1013 1014
    except:
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
M
Mark Hymers 已提交
1015
            session.close()
1016 1017 1018 1019 1020

        return False

__all__.append('insert_content_paths')

M
Mark Hymers 已提交
1021 1022
################################################################################

M
Mark Hymers 已提交
1023
class DSCFile(object):
M
Mark Hymers 已提交
1024 1025
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1026 1027 1028 1029

    def __repr__(self):
        return '<DSCFile %s>' % self.dscfile_id

1030 1031
__all__.append('DSCFile')

1032
@session_wrapper
M
Mark Hymers 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
def get_dscfiles(dscfile_id=None, source_id=None, poolfile_id=None, session=None):
    """
    Returns a list of DSCFiles which may be empty

    @type dscfile_id: int (optional)
    @param dscfile_id: the dscfile_id of the DSCFiles to find

    @type source_id: int (optional)
    @param source_id: the source id related to the DSCFiles to find

    @type poolfile_id: int (optional)
    @param poolfile_id: the poolfile id related to the DSCFiles to find

    @rtype: list
    @return: Possibly empty list of DSCFiles
    """

    q = session.query(DSCFile)

    if dscfile_id is not None:
        q = q.filter_by(dscfile_id=dscfile_id)

    if source_id is not None:
        q = q.filter_by(source_id=source_id)

    if poolfile_id is not None:
        q = q.filter_by(poolfile_id=poolfile_id)

1061
    return q.all()
M
Mark Hymers 已提交
1062 1063 1064

__all__.append('get_dscfiles')

M
Mark Hymers 已提交
1065 1066
################################################################################

M
Mark Hymers 已提交
1067
class PoolFile(object):
M
Mark Hymers 已提交
1068 1069
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1070 1071 1072 1073

    def __repr__(self):
        return '<PoolFile %s>' % self.filename

M
Mark Hymers 已提交
1074 1075 1076 1077
    @property
    def fullpath(self):
        return os.path.join(self.location.path, self.filename)

1078 1079
__all__.append('PoolFile')

1080
@session_wrapper
1081 1082 1083
def check_poolfile(filename, filesize, md5sum, location_id, session=None):
    """
    Returns a tuple:
J
Joerg Jaspert 已提交
1084
    (ValidFileFound [boolean or None], PoolFile object or None)
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099

    @type filename: string
    @param filename: the filename of the file to check against the DB

    @type filesize: int
    @param filesize: the size of the file to check against the DB

    @type md5sum: string
    @param md5sum: the md5sum of the file to check against the DB

    @type location_id: int
    @param location_id: the id of the location to look in

    @rtype: tuple
    @return: Tuple of length 2.
J
Joerg Jaspert 已提交
1100 1101 1102 1103 1104
                 - If more than one file found with that name: (C{None},  C{None})
                 - If valid pool file found: (C{True}, C{PoolFile object})
                 - If valid pool file not found:
                     - (C{False}, C{None}) if no file found
                     - (C{False}, C{PoolFile object}) if file found with size/md5sum mismatch
1105 1106 1107 1108 1109
    """

    q = session.query(PoolFile).filter_by(filename=filename)
    q = q.join(Location).filter_by(location_id=location_id)

1110 1111
    ret = None

1112
    if q.count() > 1:
1113 1114 1115 1116 1117
        ret = (None, None)
    elif q.count() < 1:
        ret = (False, None)
    else:
        obj = q.one()
M
Mark Hymers 已提交
1118
        if obj.md5sum != md5sum or obj.filesize != int(filesize):
1119
            ret = (False, obj)
1120

1121 1122
    if ret is None:
        ret = (True, obj)
1123

1124
    return ret
1125 1126 1127

__all__.append('check_poolfile')

1128
@session_wrapper
M
Mark Hymers 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
def get_poolfile_by_id(file_id, session=None):
    """
    Returns a PoolFile objects or None for the given id

    @type file_id: int
    @param file_id: the id of the file to look for

    @rtype: PoolFile or None
    @return: either the PoolFile object or None
    """

    q = session.query(PoolFile).filter_by(file_id=file_id)

1142 1143 1144 1145
    try:
        return q.one()
    except NoResultFound:
        return None
M
Mark Hymers 已提交
1146 1147 1148

__all__.append('get_poolfile_by_id')

1149

1150
@session_wrapper
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
def get_poolfile_by_name(filename, location_id=None, session=None):
    """
    Returns an array of PoolFile objects for the given filename and
    (optionally) location_id

    @type filename: string
    @param filename: the filename of the file to check against the DB

    @type location_id: int
    @param location_id: the id of the location to look in (optional)

    @rtype: array
    @return: array of PoolFile objects
    """

    q = session.query(PoolFile).filter_by(filename=filename)

    if location_id is not None:
        q = q.join(Location).filter_by(location_id=location_id)

1171
    return q.all()
1172 1173 1174

__all__.append('get_poolfile_by_name')

1175
@session_wrapper
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
def get_poolfile_like_name(filename, session=None):
    """
    Returns an array of PoolFile objects which are like the given name

    @type filename: string
    @param filename: the filename of the file to check against the DB

    @rtype: array
    @return: array of PoolFile objects
    """

    # TODO: There must be a way of properly using bind parameters with %FOO%
M
Mark Hymers 已提交
1188
    q = session.query(PoolFile).filter(PoolFile.filename.like('%%/%s' % filename))
1189

1190
    return q.all()
1191 1192 1193

__all__.append('get_poolfile_like_name')

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
@session_wrapper
def add_poolfile(filename, datadict, location_id, session=None):
    """
    Add a new file to the pool

    @type filename: string
    @param filename: filename

    @type datadict: dict
    @param datadict: dict with needed data

    @type location_id: int
    @param location_id: database id of the location

    @rtype: PoolFile
    @return: the PoolFile object created
    """
    poolfile = PoolFile()
    poolfile.filename = filename
    poolfile.filesize = datadict["size"]
    poolfile.md5sum = datadict["md5sum"]
    poolfile.sha1sum = datadict["sha1sum"]
    poolfile.sha256sum = datadict["sha256sum"]
    poolfile.location_id = location_id

    session.add(poolfile)
    # Flush to get a file id (NB: This is not a commit)
    session.flush()

    return poolfile

__all__.append('add_poolfile')

M
Mark Hymers 已提交
1227 1228
################################################################################

M
Mark Hymers 已提交
1229
class Fingerprint(object):
T
Torsten Werner 已提交
1230 1231
    def __init__(self, fingerprint = None):
        self.fingerprint = fingerprint
M
Mark Hymers 已提交
1232 1233 1234 1235

    def __repr__(self):
        return '<Fingerprint %s>' % self.fingerprint

1236 1237
__all__.append('Fingerprint')

M
Mark Hymers 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
@session_wrapper
def get_fingerprint(fpr, session=None):
    """
    Returns Fingerprint object for given fpr.

    @type fpr: string
    @param fpr: The fpr to find / add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).

    @rtype: Fingerprint
    @return: the Fingerprint object for the given fpr or None
    """

    q = session.query(Fingerprint).filter_by(fingerprint=fpr)

    try:
        ret = q.one()
    except NoResultFound:
        ret = None

    return ret

__all__.append('get_fingerprint')

1265
@session_wrapper
M
Mark Hymers 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
def get_or_set_fingerprint(fpr, session=None):
    """
    Returns Fingerprint object for given fpr.

    If no matching fpr is found, a row is inserted.

    @type fpr: string
    @param fpr: The fpr to find / add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
    A flush will be performed either way.

    @rtype: Fingerprint
    @return: the Fingerprint object for the given fpr
    """

1285
    q = session.query(Fingerprint).filter_by(fingerprint=fpr)
1286 1287 1288 1289

    try:
        ret = q.one()
    except NoResultFound:
1290 1291 1292
        fingerprint = Fingerprint()
        fingerprint.fingerprint = fpr
        session.add(fingerprint)
1293
        session.commit_or_flush()
1294
        ret = fingerprint
M
Mark Hymers 已提交
1295

1296
    return ret
M
Mark Hymers 已提交
1297 1298 1299

__all__.append('get_or_set_fingerprint')

M
Mark Hymers 已提交
1300 1301
################################################################################

M
Mark Hymers 已提交
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
# Helper routine for Keyring class
def get_ldap_name(entry):
    name = []
    for k in ["cn", "mn", "sn"]:
        ret = entry.get(k)
        if ret and ret[0] != "" and ret[0] != "-":
            name.append(ret[0])
    return " ".join(name)

################################################################################

M
Mark Hymers 已提交
1313
class Keyring(object):
M
Mark Hymers 已提交
1314 1315 1316 1317 1318 1319
    gpg_invocation = "gpg --no-default-keyring --keyring %s" +\
                     " --with-colons --fingerprint --fingerprint"

    keys = {}
    fpr_lookup = {}

M
Mark Hymers 已提交
1320 1321
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1322 1323 1324 1325

    def __repr__(self):
        return '<Keyring %s>' % self.keyring_name

1326 1327
    def de_escape_gpg_str(self, txt):
        esclist = re.split(r'(\\x..)', txt)
M
Mark Hymers 已提交
1328 1329 1330 1331
        for x in range(1,len(esclist),2):
            esclist[x] = "%c" % (int(esclist[x][2:],16))
        return "".join(esclist)

T
Torsten Werner 已提交
1332 1333
    def parse_address(self, uid):
        """parses uid and returns a tuple of real name and email address"""
M
Mark Hymers 已提交
1334
        import email.Utils
T
Torsten Werner 已提交
1335 1336 1337 1338 1339 1340
        (name, address) = email.Utils.parseaddr(uid)
        name = re.sub(r"\s*[(].*[)]", "", name)
        name = self.de_escape_gpg_str(name)
        if name == "":
            name = uid
        return (name, address)
M
Mark Hymers 已提交
1341

T
Torsten Werner 已提交
1342
    def load_keys(self, keyring):
M
Mark Hymers 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
        if not self.keyring_id:
            raise Exception('Must be initialized with database information')

        k = os.popen(self.gpg_invocation % keyring, "r")
        key = None
        signingkey = False

        for line in k.xreadlines():
            field = line.split(":")
            if field[0] == "pub":
                key = field[4]
T
Torsten Werner 已提交
1354 1355 1356 1357
                self.keys[key] = {}
                (name, addr) = self.parse_address(field[9])
                if "@" in addr:
                    self.keys[key]["email"] = addr
M
Mark Hymers 已提交
1358 1359 1360 1361 1362 1363
                    self.keys[key]["name"] = name
                self.keys[key]["fingerprints"] = []
                signingkey = True
            elif key and field[0] == "sub" and len(field) >= 12:
                signingkey = ("s" in field[11])
            elif key and field[0] == "uid":
T
Torsten Werner 已提交
1364 1365 1366 1367
                (name, addr) = self.parse_address(field[9])
                if "email" not in self.keys[key] and "@" in addr:
                    self.keys[key]["email"] = addr
                    self.keys[key]["name"] = name
M
Mark Hymers 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
            elif signingkey and field[0] == "fpr":
                self.keys[key]["fingerprints"].append(field[9])
                self.fpr_lookup[field[9]] = key

    def import_users_from_ldap(self, session):
        import ldap
        cnf = Config()

        LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
        LDAPServer = cnf["Import-LDAP-Fingerprints::LDAPServer"]

        l = ldap.open(LDAPServer)
        l.simple_bind_s("","")
        Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
               "(&(keyfingerprint=*)(gidnumber=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
               ["uid", "keyfingerprint", "cn", "mn", "sn"])

        ldap_fin_uid_id = {}

        byuid = {}
        byname = {}

        for i in Attrs:
            entry = i[1]
            uid = entry["uid"][0]
            name = get_ldap_name(entry)
            fingerprints = entry["keyFingerPrint"]
            keyid = None
            for f in fingerprints:
                key = self.fpr_lookup.get(f, None)
                if key not in self.keys:
                    continue
                self.keys[key]["uid"] = uid

                if keyid != None:
                    continue
                keyid = get_or_set_uid(uid, session).uid_id
                byuid[keyid] = (uid, name)
                byname[uid] = (keyid, name)

        return (byname, byuid)

    def generate_users_from_keyring(self, format, session):
        byuid = {}
        byname = {}
        any_invalid = False
        for x in self.keys.keys():
T
Torsten Werner 已提交
1415
            if "email" not in self.keys[x]:
M
Mark Hymers 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
                any_invalid = True
                self.keys[x]["uid"] = format % "invalid-uid"
            else:
                uid = format % self.keys[x]["email"]
                keyid = get_or_set_uid(uid, session).uid_id
                byuid[keyid] = (uid, self.keys[x]["name"])
                byname[uid] = (keyid, self.keys[x]["name"])
                self.keys[x]["uid"] = uid

        if any_invalid:
            uid = format % "invalid-uid"
            keyid = get_or_set_uid(uid, session).uid_id
            byuid[keyid] = (uid, "ungeneratable user id")
            byname[uid] = (keyid, "ungeneratable user id")

        return (byname, byuid)

1433 1434
__all__.append('Keyring')

1435
@session_wrapper
M
Mark Hymers 已提交
1436
def get_keyring(keyring, session=None):
1437
    """
M
Mark Hymers 已提交
1438
    If C{keyring} does not have an entry in the C{keyrings} table yet, return None
1439 1440 1441 1442 1443 1444 1445 1446 1447
    If C{keyring} already has an entry, simply return the existing Keyring

    @type keyring: string
    @param keyring: the keyring name

    @rtype: Keyring
    @return: the Keyring object for this keyring
    """

1448
    q = session.query(Keyring).filter_by(keyring_name=keyring)
1449

1450 1451 1452
    try:
        return q.one()
    except NoResultFound:
M
Mark Hymers 已提交
1453
        return None
1454

M
Mark Hymers 已提交
1455
__all__.append('get_keyring')
1456

M
Mark Hymers 已提交
1457
################################################################################
1458

M
Mark Hymers 已提交
1459 1460 1461 1462 1463 1464 1465 1466
class KeyringACLMap(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<KeyringACLMap %s>' % self.keyring_acl_map_id

__all__.append('KeyringACLMap')
1467

M
Mark Hymers 已提交
1468 1469
################################################################################

M
Mark Hymers 已提交
1470
class DBChange(object):
J
Joerg Jaspert 已提交
1471 1472 1473 1474
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
M
Mark Hymers 已提交
1475
        return '<DBChange %s>' % self.changesname
J
Joerg Jaspert 已提交
1476

1477 1478 1479 1480
    def clean_from_queue(self):
        session = DBConn().session().object_session(self)

        # Remove changes_pool_files entries
M
Mark Hymers 已提交
1481
        self.poolfiles = []
1482

M
Mark Hymers 已提交
1483 1484
        # Remove changes_pending_files references
        self.files = []
1485 1486 1487 1488 1489

        # Clear out of queue
        self.in_queue = None
        self.approved_for_id = None

M
Mark Hymers 已提交
1490
__all__.append('DBChange')
J
Joerg Jaspert 已提交
1491 1492

@session_wrapper
M
Mark Hymers 已提交
1493
def get_dbchange(filename, session=None):
J
Joerg Jaspert 已提交
1494
    """
M
Mark Hymers 已提交
1495
    returns DBChange object for given C{filename}.
J
Joerg Jaspert 已提交
1496

J
Joerg Jaspert 已提交
1497 1498
    @type filename: string
    @param filename: the name of the file
J
Joerg Jaspert 已提交
1499 1500 1501 1502 1503

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

J
Joerg Jaspert 已提交
1504 1505
    @rtype: DBChange
    @return:  DBChange object for the given filename (C{None} if not present)
1506

J
Joerg Jaspert 已提交
1507
    """
M
Mark Hymers 已提交
1508
    q = session.query(DBChange).filter_by(changesname=filename)
J
Joerg Jaspert 已提交
1509 1510 1511 1512 1513 1514

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

M
Mark Hymers 已提交
1515
__all__.append('get_dbchange')
1516

M
Mark Hymers 已提交
1517 1518
################################################################################

M
Mark Hymers 已提交
1519
class Location(object):
M
Mark Hymers 已提交
1520 1521
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1522 1523 1524 1525

    def __repr__(self):
        return '<Location %s (%s)>' % (self.path, self.location_id)

1526 1527
__all__.append('Location')

1528
@session_wrapper
1529 1530 1531 1532 1533 1534
def get_location(location, component=None, archive=None, session=None):
    """
    Returns Location object for the given combination of location, component
    and archive

    @type location: string
J
Joerg Jaspert 已提交
1535
    @param location: the path of the location, e.g. I{/srv/ftp-master.debian.org/ftp/pool/}
1536 1537 1538 1539 1540

    @type component: string
    @param component: the component name (if None, no restriction applied)

    @type archive: string
J
Joerg Jaspert 已提交
1541
    @param archive: the archive name (if None, no restriction applied)
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554

    @rtype: Location / None
    @return: Either a Location object or None if one can't be found
    """

    q = session.query(Location).filter_by(path=location)

    if archive is not None:
        q = q.join(Archive).filter_by(archive_name=archive)

    if component is not None:
        q = q.join(Component).filter_by(component_name=component)

1555 1556 1557 1558
    try:
        return q.one()
    except NoResultFound:
        return None
1559 1560 1561

__all__.append('get_location')

M
Mark Hymers 已提交
1562 1563
################################################################################

M
Mark Hymers 已提交
1564
class Maintainer(object):
M
Mark Hymers 已提交
1565 1566
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1567 1568 1569 1570

    def __repr__(self):
        return '''<Maintainer '%s' (%s)>''' % (self.name, self.maintainer_id)

M
Mark Hymers 已提交
1571 1572 1573 1574 1575 1576
    def get_split_maintainer(self):
        if not hasattr(self, 'name') or self.name is None:
            return ('', '', '', '')

        return fix_maintainer(self.name.strip())

1577 1578
__all__.append('Maintainer')

1579
@session_wrapper
M
Mark Hymers 已提交
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
def get_or_set_maintainer(name, session=None):
    """
    Returns Maintainer object for given maintainer name.

    If no matching maintainer name is found, a row is inserted.

    @type name: string
    @param name: The maintainer name to add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
    A flush will be performed either way.

    @rtype: Maintainer
    @return: the Maintainer object for the given maintainer
    """

1599
    q = session.query(Maintainer).filter_by(name=name)
1600 1601 1602
    try:
        ret = q.one()
    except NoResultFound:
1603 1604 1605
        maintainer = Maintainer()
        maintainer.name = name
        session.add(maintainer)
1606
        session.commit_or_flush()
1607
        ret = maintainer
M
Mark Hymers 已提交
1608

1609
    return ret
M
Mark Hymers 已提交
1610 1611 1612

__all__.append('get_or_set_maintainer')

1613
@session_wrapper
C
Chris Lamb 已提交
1614
def get_maintainer(maintainer_id, session=None):
C
Chris Lamb 已提交
1615
    """
1616 1617
    Return the name of the maintainer behind C{maintainer_id} or None if that
    maintainer_id is invalid.
C
Chris Lamb 已提交
1618 1619 1620 1621

    @type maintainer_id: int
    @param maintainer_id: the id of the maintainer

1622 1623
    @rtype: Maintainer
    @return: the Maintainer with this C{maintainer_id}
C
Chris Lamb 已提交
1624 1625
    """

1626
    return session.query(Maintainer).get(maintainer_id)
C
Chris Lamb 已提交
1627 1628 1629

__all__.append('get_maintainer')

M
Mark Hymers 已提交
1630 1631
################################################################################

M
Mark Hymers 已提交
1632 1633 1634 1635 1636 1637 1638 1639 1640
class NewComment(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '''<NewComment for '%s %s' (%s)>''' % (self.package, self.version, self.comment_id)

__all__.append('NewComment')

1641
@session_wrapper
M
Mark Hymers 已提交
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
def has_new_comment(package, version, session=None):
    """
    Returns true if the given combination of C{package}, C{version} has a comment.

    @type package: string
    @param package: name of the package

    @type version: string
    @param version: package version

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: boolean
    @return: true/false
    """

    q = session.query(NewComment)
    q = q.filter_by(package=package)
    q = q.filter_by(version=version)
1663

1664
    return bool(q.count() > 0)
M
Mark Hymers 已提交
1665 1666 1667

__all__.append('has_new_comment')

1668
@session_wrapper
M
Mark Hymers 已提交
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
def get_new_comments(package=None, version=None, comment_id=None, session=None):
    """
    Returns (possibly empty) list of NewComment objects for the given
    parameters

    @type package: string (optional)
    @param package: name of the package

    @type version: string (optional)
    @param version: package version

    @type comment_id: int (optional)
    @param comment_id: An id of a comment

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: A (possibly empty) list of NewComment objects will be returned
    """

    q = session.query(NewComment)
    if package is not None: q = q.filter_by(package=package)
    if version is not None: q = q.filter_by(version=version)
    if comment_id is not None: q = q.filter_by(comment_id=comment_id)

1696
    return q.all()
M
Mark Hymers 已提交
1697 1698 1699 1700 1701

__all__.append('get_new_comments')

################################################################################

M
Mark Hymers 已提交
1702
class Override(object):
M
Mark Hymers 已提交
1703 1704
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1705 1706 1707 1708

    def __repr__(self):
        return '<Override %s (%s)>' % (self.package, self.suite_id)

1709 1710
__all__.append('Override')

1711
@session_wrapper
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
def get_override(package, suite=None, component=None, overridetype=None, session=None):
    """
    Returns Override object for the given parameters

    @type package: string
    @param package: The name of the package

    @type suite: string, list or None
    @param suite: The name of the suite (or suites if a list) to limit to.  If
                  None, don't limit.  Defaults to None.

    @type component: string, list or None
    @param component: The name of the component (or components if a list) to
                      limit to.  If None, don't limit.  Defaults to None.

    @type overridetype: string, list or None
    @param overridetype: The name of the overridetype (or overridetypes if a list) to
                         limit to.  If None, don't limit.  Defaults to None.

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: A (possibly empty) list of Override objects will be returned
    """

    q = session.query(Override)
    q = q.filter_by(package=package)

    if suite is not None:
        if not isinstance(suite, list): suite = [suite]
        q = q.join(Suite).filter(Suite.suite_name.in_(suite))

    if component is not None:
        if not isinstance(component, list): component = [component]
        q = q.join(Component).filter(Component.component_name.in_(component))

    if overridetype is not None:
        if not isinstance(overridetype, list): overridetype = [overridetype]
        q = q.join(OverrideType).filter(OverrideType.overridetype.in_(overridetype))

1754
    return q.all()
1755 1756 1757 1758

__all__.append('get_override')


M
Mark Hymers 已提交
1759 1760
################################################################################

M
Mark Hymers 已提交
1761
class OverrideType(object):
M
Mark Hymers 已提交
1762 1763
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1764 1765 1766 1767

    def __repr__(self):
        return '<OverrideType %s>' % self.overridetype

1768 1769
__all__.append('OverrideType')

1770
@session_wrapper
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
def get_override_type(override_type, session=None):
    """
    Returns OverrideType object for given C{override type}.

    @type override_type: string
    @param override_type: The name of the override type

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: int
    @return: the database id for the given override type
    """
1785

M
Mark Hymers 已提交
1786
    q = session.query(OverrideType).filter_by(overridetype=override_type)
1787

1788 1789 1790 1791
    try:
        return q.one()
    except NoResultFound:
        return None
1792

1793 1794
__all__.append('get_override_type')

M
Mark Hymers 已提交
1795 1796
################################################################################

M
Mike O'Connor 已提交
1797
class DebContents(object):
M
Mark Hymers 已提交
1798 1799
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1800 1801

    def __repr__(self):
M
Mike O'Connor 已提交
1802 1803 1804 1805 1806 1807 1808 1809
        return '<DebConetnts %s: %s>' % (self.package.package,self.file)

__all__.append('DebContents')


class UdebContents(object):
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1810

M
Mike O'Connor 已提交
1811 1812 1813 1814 1815 1816 1817 1818
    def __repr__(self):
        return '<UdebConetnts %s: %s>' % (self.package.package,self.file)

__all__.append('UdebContents')

class PendingBinContents(object):
    def __init__(self, *args, **kwargs):
        pass
1819

M
Mike O'Connor 已提交
1820 1821 1822 1823 1824 1825 1826 1827 1828
    def __repr__(self):
        return '<PendingBinContents %s>' % self.contents_id

__all__.append('PendingBinContents')

def insert_pending_content_paths(package,
                                 is_udeb,
                                 fullpaths,
                                 session=None):
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    """
    Make sure given paths are temporarily associated with given
    package

    @type package: dict
    @param package: the package to associate with should have been read in from the binary control file
    @type fullpaths: list
    @param fullpaths: the list of paths of the file being associated with the binary
    @type session: SQLAlchemy session
    @param session: Optional SQLAlchemy session.  If this is passed, the caller
    is responsible for ensuring a transaction has begun and committing the
    results or rolling back based on the result code.  If not passed, a commit
    will be performed at the end of the function

    @return: True upon success, False if there is a problem
    """

    privatetrans = False

    if session is None:
        session = DBConn().session()
        privatetrans = True

    try:
        arch = get_architecture(package['Architecture'], session)
        arch_id = arch.arch_id

        # Remove any already existing recorded files for this package
M
Mike O'Connor 已提交
1857
        q = session.query(PendingBinContents)
1858 1859 1860 1861 1862 1863 1864
        q = q.filter_by(package=package['Package'])
        q = q.filter_by(version=package['Version'])
        q = q.filter_by(architecture=arch_id)
        q.delete()

        for fullpath in fullpaths:

M
Mike O'Connor 已提交
1865 1866
            if fullpath.startswith( "./" ):
                fullpath = fullpath[2:]
M
Mark Hymers 已提交
1867

M
Mike O'Connor 已提交
1868
            pca = PendingBinContents()
1869 1870
            pca.package = package['Package']
            pca.version = package['Version']
M
Mike O'Connor 已提交
1871
            pca.file = fullpath
1872
            pca.architecture = arch_id
M
Mike O'Connor 已提交
1873

1874
            if isudeb:
M
Mike O'Connor 已提交
1875 1876 1877
                pca.type = 8 # gross
            else:
                pca.type = 7 # also gross
1878 1879 1880 1881 1882
            session.add(pca)

        # Only commit if we set up the session ourself
        if privatetrans:
            session.commit()
1883
            session.close()
M
Mark Hymers 已提交
1884 1885
        else:
            session.flush()
1886 1887

        return True
1888
    except Exception, e:
1889 1890 1891 1892 1893
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
1894
            session.close()
1895 1896 1897 1898 1899

        return False

__all__.append('insert_pending_content_paths')

M
Mark Hymers 已提交
1900 1901
################################################################################

1902 1903 1904 1905 1906 1907 1908 1909 1910
class PolicyQueue(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<PolicyQueue %s>' % self.queue_name

__all__.append('PolicyQueue')

1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
@session_wrapper
def get_policy_queue(queuename, session=None):
    """
    Returns PolicyQueue object for given C{queue name}

    @type queuename: string
    @param queuename: The name of the queue

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: PolicyQueue
    @return: PolicyQueue object for the given queue
    """

    q = session.query(PolicyQueue).filter_by(queue_name=queuename)

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

__all__.append('get_policy_queue')

M
Mark Hymers 已提交
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
@session_wrapper
def get_policy_queue_from_path(pathname, session=None):
    """
    Returns PolicyQueue object for given C{path name}

    @type queuename: string
    @param queuename: The path

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: PolicyQueue
    @return: PolicyQueue object for the given queue
    """

    q = session.query(PolicyQueue).filter_by(path=pathname)

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

__all__.append('get_policy_queue_from_path')

1961 1962
################################################################################

M
Mark Hymers 已提交
1963
class Priority(object):
M
Mark Hymers 已提交
1964 1965
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1966

1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.priority == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.priority != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
1979 1980 1981
    def __repr__(self):
        return '<Priority %s (%s)>' % (self.priority, self.priority_id)

1982 1983
__all__.append('Priority')

1984
@session_wrapper
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
def get_priority(priority, session=None):
    """
    Returns Priority object for given C{priority name}.

    @type priority: string
    @param priority: The name of the priority

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Priority
    @return: Priority object for the given priority
    """
1999

2000
    q = session.query(Priority).filter_by(priority=priority)
2001

2002 2003 2004 2005
    try:
        return q.one()
    except NoResultFound:
        return None
2006

2007 2008
__all__.append('get_priority')

2009
@session_wrapper
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
def get_priorities(session=None):
    """
    Returns dictionary of priority names -> id mappings

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: dictionary
    @return: dictionary of priority names -> id mappings
    """

    ret = {}
    q = session.query(Priority)
    for x in q.all():
        ret[x.priority] = x.priority_id

    return ret

__all__.append('get_priorities')

M
Mark Hymers 已提交
2031 2032
################################################################################

M
Mark Hymers 已提交
2033
class Section(object):
M
Mark Hymers 已提交
2034 2035
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2036

2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.section == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.section != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
2049 2050 2051
    def __repr__(self):
        return '<Section %s>' % self.section

2052 2053
__all__.append('Section')

2054
@session_wrapper
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
def get_section(section, session=None):
    """
    Returns Section object for given C{section name}.

    @type section: string
    @param section: The name of the section

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Section
    @return: Section object for the given section name
    """
2069

2070
    q = session.query(Section).filter_by(section=section)
2071

2072 2073 2074 2075
    try:
        return q.one()
    except NoResultFound:
        return None
2076

2077 2078
__all__.append('get_section')

2079
@session_wrapper
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
def get_sections(session=None):
    """
    Returns dictionary of section names -> id mappings

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: dictionary
    @return: dictionary of section names -> id mappings
    """

    ret = {}
    q = session.query(Section)
    for x in q.all():
        ret[x.section] = x.section_id

    return ret

__all__.append('get_sections')

M
Mark Hymers 已提交
2101 2102
################################################################################

2103
class DBSource(object):
M
Mark Hymers 已提交
2104 2105
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2106 2107

    def __repr__(self):
2108
        return '<DBSource %s (%s)>' % (self.source, self.version)
M
Mark Hymers 已提交
2109

2110
__all__.append('DBSource')
2111

2112
@session_wrapper
2113 2114 2115 2116 2117 2118 2119
def source_exists(source, source_version, suites = ["any"], session=None):
    """
    Ensure that source exists somewhere in the archive for the binary
    upload being processed.
      1. exact match     => 1.0-3
      2. bin-only NMU    => 1.0-3+b1 , 1.0-3.1+b1

J
Joerg Jaspert 已提交
2120 2121
    @type source: string
    @param source: source name
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138

    @type source_version: string
    @param source_version: expected source version

    @type suites: list
    @param suites: list of suites to check in, default I{any}

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: int
    @return: returns 1 if a source with expected version is found, otherwise 0

    """

    cnf = Config()
2139
    ret = 1
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173

    for suite in suites:
        q = session.query(DBSource).filter_by(source=source)
        if suite != "any":
            # source must exist in suite X, or in some other suite that's
            # mapped to X, recursively... silent-maps are counted too,
            # unreleased-maps aren't.
            maps = cnf.ValueList("SuiteMappings")[:]
            maps.reverse()
            maps = [ m.split() for m in maps ]
            maps = [ (x[1], x[2]) for x in maps
                            if x[0] == "map" or x[0] == "silent-map" ]
            s = [suite]
            for x in maps:
                if x[1] in s and x[0] not in s:
                    s.append(x[0])

            q = q.join(SrcAssociation).join(Suite)
            q = q.filter(Suite.suite_name.in_(s))

        # Reduce the query results to a list of version numbers
        ql = [ j.version for j in q.all() ]

        # Try (1)
        if source_version in ql:
            continue

        # Try (2)
        from daklib.regexes import re_bin_only_nmu
        orig_source_version = re_bin_only_nmu.sub('', source_version)
        if orig_source_version in ql:
            continue

        # No source found so return not ok
2174 2175 2176
        ret = 0

    return ret
2177 2178 2179

__all__.append('source_exists')

2180
@session_wrapper
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
def get_suites_source_in(source, session=None):
    """
    Returns list of Suite objects which given C{source} name is in

    @type source: str
    @param source: DBSource package name to search for

    @rtype: list
    @return: list of Suite objects for the given source
    """

2192
    return session.query(Suite).join(SrcAssociation).join(DBSource).filter_by(source=source).all()
2193 2194 2195

__all__.append('get_suites_source_in')

2196
@session_wrapper
2197
def get_sources_from_name(source, version=None, dm_upload_allowed=None, session=None):
M
Mark Hymers 已提交
2198
    """
2199
    Returns list of DBSource objects for given C{source} name and other parameters
M
Mark Hymers 已提交
2200 2201

    @type source: str
2202
    @param source: DBSource package name to search for
M
Mark Hymers 已提交
2203

J
Joerg Jaspert 已提交
2204 2205
    @type version: str or None
    @param version: DBSource version name to search for or None if not applicable
2206

2207 2208 2209 2210
    @type dm_upload_allowed: bool
    @param dm_upload_allowed: If None, no effect.  If True or False, only
    return packages with that dm_upload_allowed setting

M
Mark Hymers 已提交
2211 2212 2213 2214 2215
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
2216
    @return: list of DBSource objects for the given name (may be empty)
M
Mark Hymers 已提交
2217
    """
2218 2219

    q = session.query(DBSource).filter_by(source=source)
2220 2221 2222 2223

    if version is not None:
        q = q.filter_by(version=version)

2224 2225 2226
    if dm_upload_allowed is not None:
        q = q.filter_by(dm_upload_allowed=dm_upload_allowed)

2227
    return q.all()
M
Mark Hymers 已提交
2228

2229 2230
__all__.append('get_sources_from_name')

2231
@session_wrapper
2232 2233
def get_source_in_suite(source, suite, session=None):
    """
2234
    Returns list of DBSource objects for a combination of C{source} and C{suite}.
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248

      - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
      - B{suite} - a suite name, eg. I{unstable}

    @type source: string
    @param source: source package name

    @type suite: string
    @param suite: the suite name

    @rtype: string
    @return: the version for I{source} in I{suite}

    """
2249

M
updates  
Mark Hymers 已提交
2250 2251 2252
    q = session.query(SrcAssociation)
    q = q.join('source').filter_by(source=source)
    q = q.join('suite').filter_by(suite_name=suite)
2253

2254 2255 2256 2257
    try:
        return q.one().source
    except NoResultFound:
        return None
2258

2259 2260
__all__.append('get_source_in_suite')

M
Mark Hymers 已提交
2261 2262
################################################################################

2263 2264 2265 2266
@session_wrapper
def add_dsc_to_db(u, filename, session=None):
    entry = u.pkg.files[filename]
    source = DBSource()
2267
    pfs = []
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284

    source.source = u.pkg.dsc["source"]
    source.version = u.pkg.dsc["version"] # NB: not files[file]["version"], that has no epoch
    source.maintainer_id = get_or_set_maintainer(u.pkg.dsc["maintainer"], session).maintainer_id
    source.changedby_id = get_or_set_maintainer(u.pkg.changes["changed-by"], session).maintainer_id
    source.fingerprint_id = get_or_set_fingerprint(u.pkg.changes["fingerprint"], session).fingerprint_id
    source.install_date = datetime.now().date()

    dsc_component = entry["component"]
    dsc_location_id = entry["location id"]

    source.dm_upload_allowed = (u.pkg.dsc.get("dm-upload-allowed", '') == "yes")

    # Set up a new poolfile if necessary
    if not entry.has_key("files id") or not entry["files id"]:
        filename = entry["pool name"] + filename
        poolfile = add_poolfile(filename, entry, dsc_location_id, session)
F
Frank Lichtenheld 已提交
2285
        session.flush()
2286
        pfs.append(poolfile)
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
        entry["files id"] = poolfile.file_id

    source.poolfile_id = entry["files id"]
    session.add(source)
    session.flush()

    for suite_name in u.pkg.changes["distribution"].keys():
        sa = SrcAssociation()
        sa.source_id = source.source_id
        sa.suite_id = get_suite(suite_name).suite_id
        session.add(sa)

    session.flush()

    # Add the source files to the DB (files and dsc_files)
    dscfile = DSCFile()
    dscfile.source_id = source.source_id
    dscfile.poolfile_id = entry["files id"]
    session.add(dscfile)

    for dsc_file, dentry in u.pkg.dsc_files.items():
        df = DSCFile()
        df.source_id = source.source_id

        # If the .orig tarball is already in the pool, it's
        # files id is stored in dsc_files by check_dsc().
        files_id = dentry.get("files id", None)

        # Find the entry in the files hash
        # TODO: Bail out here properly
        dfentry = None
        for f, e in u.pkg.files.items():
            if f == dsc_file:
                dfentry = e
                break

        if files_id is None:
            filename = dfentry["pool name"] + dsc_file

            (found, obj) = check_poolfile(filename, dentry["size"], dentry["md5sum"], dsc_location_id)
            # FIXME: needs to check for -1/-2 and or handle exception
            if found and obj is not None:
                files_id = obj.file_id
2330
                pfs.append(obj)
2331 2332 2333 2334 2335 2336 2337

            # If still not found, add it
            if files_id is None:
                # HACK: Force sha1sum etc into dentry
                dentry["sha1sum"] = dfentry["sha1sum"]
                dentry["sha256sum"] = dfentry["sha256sum"]
                poolfile = add_poolfile(filename, dentry, dsc_location_id, session)
2338
                pfs.append(poolfile)
2339
                files_id = poolfile.file_id
2340 2341 2342 2343 2344
        else:
            poolfile = get_poolfile_by_id(files_id, session)
            if poolfile is None:
                utils.fubar("INTERNAL ERROR. Found no poolfile with id %d" % files_id)
            pfs.append(poolfile)
2345 2346 2347 2348 2349 2350 2351 2352 2353

        df.poolfile_id = files_id
        session.add(df)

    session.flush()

    # Add the src_uploaders to the DB
    uploader_ids = [source.maintainer_id]
    if u.pkg.dsc.has_key("uploaders"):
2354
        for up in u.pkg.dsc["uploaders"].replace(">, ", ">\t").split("\t"):
2355 2356 2357 2358
            up = up.strip()
            uploader_ids.append(get_or_set_maintainer(up, session).maintainer_id)

    added_ids = {}
T
Torsten Werner 已提交
2359 2360 2361 2362
    for up_id in uploader_ids:
        if added_ids.has_key(up_id):
            import utils
            utils.warn("Already saw uploader %s for source %s" % (up_id, source.source))
2363 2364
            continue

T
Torsten Werner 已提交
2365
        added_ids[up_id]=1
2366 2367

        su = SrcUploader()
T
Torsten Werner 已提交
2368
        su.maintainer_id = up_id
2369 2370 2371 2372 2373
        su.source_id = source.source_id
        session.add(su)

    session.flush()

M
Mark Hymers 已提交
2374
    return source, dsc_component, dsc_location_id, pfs
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399

__all__.append('add_dsc_to_db')

@session_wrapper
def add_deb_to_db(u, filename, session=None):
    """
    Contrary to what you might expect, this routine deals with both
    debs and udebs.  That info is in 'dbtype', whilst 'type' is
    'deb' for both of them
    """
    cnf = Config()
    entry = u.pkg.files[filename]

    bin = DBBinary()
    bin.package = entry["package"]
    bin.version = entry["version"]
    bin.maintainer_id = get_or_set_maintainer(entry["maintainer"], session).maintainer_id
    bin.fingerprint_id = get_or_set_fingerprint(u.pkg.changes["fingerprint"], session).fingerprint_id
    bin.arch_id = get_architecture(entry["architecture"], session).arch_id
    bin.binarytype = entry["dbtype"]

    # Find poolfile id
    filename = entry["pool name"] + filename
    fullpath = os.path.join(cnf["Dir::Pool"], filename)
    if not entry.get("location id", None):
2400
        entry["location id"] = get_location(cnf["Dir::Pool"], entry["component"], session=session).location_id
2401

2402 2403 2404 2405
    if entry.get("files id", None):
        poolfile = get_poolfile_by_id(bin.poolfile_id)
        bin.poolfile_id = entry["files id"]
    else:
2406
        poolfile = add_poolfile(filename, entry, entry["location id"], session)
2407
        bin.poolfile_id = entry["files id"] = poolfile.file_id
2408 2409 2410 2411 2412

    # Find source id
    bin_sources = get_sources_from_name(entry["source package"], entry["source version"], session=session)
    if len(bin_sources) != 1:
        raise NoSourceFieldError, "Unable to find a unique source id for %s (%s), %s, file %s, type %s, signed by %s" % \
2413
                                  (bin.package, bin.version, entry["architecture"],
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
                                   filename, bin.binarytype, u.pkg.changes["fingerprint"])

    bin.source_id = bin_sources[0].source_id

    # Add and flush object so it has an ID
    session.add(bin)
    session.flush()

    # Add BinAssociations
    for suite_name in u.pkg.changes["distribution"].keys():
        ba = BinAssociation()
        ba.binary_id = bin.binary_id
        ba.suite_id = get_suite(suite_name).suite_id
        session.add(ba)

    session.flush()

    # Deal with contents - disabled for now
    #contents = copy_temporary_contents(bin.package, bin.version, bin.architecture.arch_string, os.path.basename(filename), None, session)
    #if not contents:
    #    print "REJECT\nCould not determine contents of package %s" % bin.package
    #    session.rollback()
    #    raise MissingContents, "No contents stored for package %s, and couldn't determine contents of %s" % (bin.package, filename)

2438 2439
    return poolfile

2440 2441 2442 2443
__all__.append('add_deb_to_db')

################################################################################

2444 2445 2446 2447
class SourceACL(object):
    def __init__(self, *args, **kwargs):
        pass

2448 2449 2450
    def __repr__(self):
        return '<SourceACL %s>' % self.source_acl_id

2451 2452 2453 2454
__all__.append('SourceACL')

################################################################################

M
Mark Hymers 已提交
2455
class SrcAssociation(object):
M
Mark Hymers 已提交
2456 2457
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2458 2459

    def __repr__(self):
M
Mark Hymers 已提交
2460
        return '<SrcAssociation %s (%s, %s)>' % (self.sa_id, self.source, self.suite)
M
Mark Hymers 已提交
2461

2462 2463
__all__.append('SrcAssociation')

M
Mark Hymers 已提交
2464 2465
################################################################################

2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
class SrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<SrcFormat %s>' % (self.format_name)

__all__.append('SrcFormat')

################################################################################

M
Mark Hymers 已提交
2477
class SrcUploader(object):
M
Mark Hymers 已提交
2478 2479
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2480 2481 2482 2483

    def __repr__(self):
        return '<SrcUploader %s>' % self.uploader_id

2484 2485
__all__.append('SrcUploader')

M
Mark Hymers 已提交
2486 2487
################################################################################

M
Mark Hymers 已提交
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
SUITE_FIELDS = [ ('SuiteName', 'suite_name'),
                 ('SuiteID', 'suite_id'),
                 ('Version', 'version'),
                 ('Origin', 'origin'),
                 ('Label', 'label'),
                 ('Description', 'description'),
                 ('Untouchable', 'untouchable'),
                 ('Announce', 'announce'),
                 ('Codename', 'codename'),
                 ('OverrideCodename', 'overridecodename'),
                 ('ValidTime', 'validtime'),
                 ('Priority', 'priority'),
                 ('NotAutomatic', 'notautomatic'),
                 ('CopyChanges', 'copychanges'),
J
Joerg Jaspert 已提交
2502
                 ('OverrideSuite', 'overridesuite')]
M
Mark Hymers 已提交
2503

M
Mark Hymers 已提交
2504
class Suite(object):
2505 2506 2507
    def __init__(self, suite_name = None, version = None):
        self.suite_name = suite_name
        self.version = version
M
Mark Hymers 已提交
2508 2509 2510 2511

    def __repr__(self):
        return '<Suite %s>' % self.suite_name

2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.suite_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.suite_name != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
2524 2525 2526 2527 2528 2529 2530 2531 2532
    def details(self):
        ret = []
        for disp, field in SUITE_FIELDS:
            val = getattr(self, field, None)
            if val is not None:
                ret.append("%s: %s" % (disp, val))

        return "\n".join(ret)

2533 2534
__all__.append('Suite')

2535
@session_wrapper
M
Mark Hymers 已提交
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
def get_suite_architecture(suite, architecture, session=None):
    """
    Returns a SuiteArchitecture object given C{suite} and ${arch} or None if it
    doesn't exist

    @type suite: str
    @param suite: Suite name to search for

    @type architecture: str
    @param architecture: Architecture name to search for

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: SuiteArchitecture
    @return: the SuiteArchitecture object or None
    """

    q = session.query(SuiteArchitecture)
    q = q.join(Architecture).filter_by(arch_string=architecture)
    q = q.join(Suite).filter_by(suite_name=suite)
2558

2559 2560 2561 2562
    try:
        return q.one()
    except NoResultFound:
        return None
M
Mark Hymers 已提交
2563

2564
__all__.append('get_suite_architecture')
M
Mark Hymers 已提交
2565

2566
@session_wrapper
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
def get_suite(suite, session=None):
    """
    Returns Suite object for given C{suite name}.

    @type suite: string
    @param suite: The name of the suite

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Suite
F
Frank Lichtenheld 已提交
2579
    @return: Suite object for the requested suite name (None if not present)
2580
    """
2581

2582
    q = session.query(Suite).filter_by(suite_name=suite)
2583

2584 2585 2586 2587
    try:
        return q.one()
    except NoResultFound:
        return None
2588

2589 2590
__all__.append('get_suite')

M
Mark Hymers 已提交
2591 2592
################################################################################

2593
# TODO: remove SuiteArchitecture class
M
Mark Hymers 已提交
2594
class SuiteArchitecture(object):
M
Mark Hymers 已提交
2595 2596
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2597 2598 2599 2600

    def __repr__(self):
        return '<SuiteArchitecture (%s, %s)>' % (self.suite_id, self.arch_id)

2601 2602
__all__.append('SuiteArchitecture')

2603
@session_wrapper
2604
def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
M
Mark Hymers 已提交
2605 2606 2607
    """
    Returns list of Architecture objects for given C{suite} name

J
Joerg Jaspert 已提交
2608 2609
    @type suite: str
    @param suite: Suite name to search for
M
Mark Hymers 已提交
2610

2611 2612 2613 2614 2615 2616 2617 2618
    @type skipsrc: boolean
    @param skipsrc: Whether to skip returning the 'source' architecture entry
    (Default False)

    @type skipall: boolean
    @param skipall: Whether to skip returning the 'all' architecture entry
    (Default False)

M
Mark Hymers 已提交
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: list of Architecture objects for the given name (may be empty)
    """

    q = session.query(Architecture)
    q = q.join(SuiteArchitecture)
2629
    q = q.join(Suite).filter_by(suite_name=suite)
2630

2631 2632
    if skipsrc:
        q = q.filter(Architecture.arch_string != 'source')
2633

2634 2635
    if skipall:
        q = q.filter(Architecture.arch_string != 'all')
2636

2637
    q = q.order_by('arch_string')
2638

2639
    return q.all()
M
Mark Hymers 已提交
2640

2641
__all__.append('get_suite_architectures')
M
Mark Hymers 已提交
2642

M
Mark Hymers 已提交
2643 2644
################################################################################

2645 2646 2647 2648 2649 2650 2651 2652 2653
class SuiteSrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<SuiteSrcFormat (%s, %s)>' % (self.suite_id, self.src_format_id)

__all__.append('SuiteSrcFormat')

2654
@session_wrapper
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
def get_suite_src_formats(suite, session=None):
    """
    Returns list of allowed SrcFormat for C{suite}.

    @type suite: str
    @param suite: Suite name to search for

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: the list of allowed source formats for I{suite}
    """

    q = session.query(SrcFormat)
    q = q.join(SuiteSrcFormat)
    q = q.join(Suite).filter_by(suite_name=suite)
    q = q.order_by('format_name')

2675
    return q.all()
2676 2677 2678 2679 2680

__all__.append('get_suite_src_formats')

################################################################################

M
Mark Hymers 已提交
2681
class Uid(object):
T
Torsten Werner 已提交
2682 2683 2684
    def __init__(self, uid = None, name = None):
        self.uid = uid
        self.name = name
M
Mark Hymers 已提交
2685

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.uid == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.uid != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
2698 2699 2700
    def __repr__(self):
        return '<Uid %s (%s)>' % (self.uid, self.name)

2701 2702
__all__.append('Uid')

2703
@session_wrapper
M
Mark Hymers 已提交
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
def get_or_set_uid(uidname, session=None):
    """
    Returns uid object for given uidname.

    If no matching uidname is found, a row is inserted.

    @type uidname: string
    @param uidname: The uid to add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.

    @rtype: Uid
    @return: the uid object for the given uidname
    """
2721 2722 2723

    q = session.query(Uid).filter_by(uid=uidname)

2724 2725 2726
    try:
        ret = q.one()
    except NoResultFound:
2727 2728 2729
        uid = Uid()
        uid.uid = uidname
        session.add(uid)
2730
        session.commit_or_flush()
2731
        ret = uid
M
Mark Hymers 已提交
2732

2733
    return ret
M
Mark Hymers 已提交
2734 2735 2736

__all__.append('get_or_set_uid')

2737
@session_wrapper
2738 2739 2740 2741
def get_uid_from_fingerprint(fpr, session=None):
    q = session.query(Uid)
    q = q.join(Fingerprint).filter_by(fingerprint=fpr)

2742 2743 2744 2745
    try:
        return q.one()
    except NoResultFound:
        return None
2746 2747 2748

__all__.append('get_uid_from_fingerprint')

M
Mark Hymers 已提交
2749 2750
################################################################################

2751 2752 2753 2754
class UploadBlock(object):
    def __init__(self, *args, **kwargs):
        pass

2755 2756 2757
    def __repr__(self):
        return '<UploadBlock %s (%s)>' % (self.source, self.upload_block_id)

2758 2759 2760 2761
__all__.append('UploadBlock')

################################################################################

2762
class DBConn(object):
M
Mark Hymers 已提交
2763
    """
2764
    database module init.
M
Mark Hymers 已提交
2765
    """
2766 2767
    __shared_state = {}

M
Mark Hymers 已提交
2768
    def __init__(self, *args, **kwargs):
2769
        self.__dict__ = self.__shared_state
M
Mark Hymers 已提交
2770

2771 2772 2773 2774
        if not getattr(self, 'initialised', False):
            self.initialised = True
            self.debug = kwargs.has_key('debug')
            self.__createconn()
M
Mark Hymers 已提交
2775

M
Mark Hymers 已提交
2776
    def __setuptables(self):
2777
        tables_with_primary = (
C
Chris Lamb 已提交
2778 2779 2780 2781 2782 2783 2784
            'architecture',
            'archive',
            'bin_associations',
            'binaries',
            'binary_acl',
            'binary_acl_map',
            'build_queue',
2785
            'changelogs_text',
C
Chris Lamb 已提交
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
            'component',
            'config',
            'changes_pending_binaries',
            'changes_pending_files',
            'changes_pending_source',
            'dsc_files',
            'files',
            'fingerprint',
            'keyrings',
            'keyring_acl_map',
            'location',
            'maintainer',
            'new_comments',
            'override_type',
M
Mike O'Connor 已提交
2800
            'pending_bin_contents',
C
Chris Lamb 已提交
2801 2802 2803 2804 2805 2806 2807 2808 2809
            'policy_queue',
            'priority',
            'section',
            'source',
            'source_acl',
            'src_associations',
            'src_format',
            'src_uploaders',
            'suite',
2810 2811
            'uid',
            'upload_blocks',
2812 2813 2814 2815 2816
            # The following tables have primary keys but sqlalchemy
            # version 0.5 fails to reflect them correctly with database
            # versions before upgrade #41.
            #'changes',
            #'build_queue_files',
2817 2818 2819 2820 2821 2822 2823 2824 2825
        )

        tables_no_primary = (
            'bin_contents',
            'changes_pending_files_map',
            'changes_pending_source_files',
            'changes_pool_files',
            'deb_contents',
            'override',
C
Chris Lamb 已提交
2826 2827 2828
            'suite_architectures',
            'suite_src_formats',
            'suite_build_queue_copy',
M
Mike O'Connor 已提交
2829
            'udeb_contents',
2830 2831 2832
            # see the comment above
            'changes',
            'build_queue_files',
C
Chris Lamb 已提交
2833 2834
        )

2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
        views = (
            'almost_obsolete_all_associations',
            'almost_obsolete_src_associations',
            'any_associations_source',
            'bin_assoc_by_arch',
            'bin_associations_binaries',
            'binaries_suite_arch',
            'binfiles_suite_component_arch',
            'changelogs',
            'file_arch_suite',
            'newest_all_associations',
            'newest_any_associations',
            'newest_source',
            'newest_src_association',
            'obsolete_all_associations',
            'obsolete_any_associations',
            'obsolete_any_by_all_associations',
            'obsolete_src_associations',
            'source_suite',
            'src_associations_bin',
            'src_associations_src',
            'suite_arch_by_name',
        )

2859 2860 2861
        # Sqlalchemy version 0.5 fails to reflect the SERIAL type
        # correctly and that is why we have to use a workaround. It can
        # be removed as soon as we switch to version 0.6.
2862 2863 2864 2865 2866 2867 2868
        for table_name in tables_with_primary:
            table = Table(table_name, self.db_meta, \
                Column('id', Integer, primary_key = True), \
                autoload=True, useexisting=True)
            setattr(self, 'tbl_%s' % table_name, table)

        for table_name in tables_no_primary:
M
Mark Hymers 已提交
2869 2870
            table = Table(table_name, self.db_meta, autoload=True)
            setattr(self, 'tbl_%s' % table_name, table)
M
Mark Hymers 已提交
2871

2872 2873 2874 2875
        for view_name in views:
            view = Table(view_name, self.db_meta, autoload=True)
            setattr(self, 'view_%s' % view_name, view)

M
Mark Hymers 已提交
2876
    def __setupmappers(self):
M
Mark Hymers 已提交
2877
        mapper(Architecture, self.tbl_architecture,
2878 2879
               properties = dict(arch_id = self.tbl_architecture.c.id,
                                 suites = relation(Suite, secondary=self.tbl_suite_architectures, backref='architectures')))
M
Mark Hymers 已提交
2880 2881 2882 2883 2884 2885 2886 2887

        mapper(Archive, self.tbl_archive,
               properties = dict(archive_id = self.tbl_archive.c.id,
                                 archive_name = self.tbl_archive.c.name))

        mapper(BinAssociation, self.tbl_bin_associations,
               properties = dict(ba_id = self.tbl_bin_associations.c.id,
                                 suite_id = self.tbl_bin_associations.c.suite,
M
Mark Hymers 已提交
2888 2889
                                 suite = relation(Suite),
                                 binary_id = self.tbl_bin_associations.c.bin,
2890
                                 binary = relation(DBBinary)))
M
Mark Hymers 已提交
2891

M
Mike O'Connor 已提交
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
        mapper(PendingBinContents, self.tbl_pending_bin_contents,
               properties = dict(contents_id =self.tbl_pending_bin_contents.c.id,
                                 filename = self.tbl_pending_bin_contents.c.filename,
                                 package = self.tbl_pending_bin_contents.c.package,
                                 version = self.tbl_pending_bin_contents.c.version,
                                 arch = self.tbl_pending_bin_contents.c.arch,
                                 otype = self.tbl_pending_bin_contents.c.type))

        mapper(DebContents, self.tbl_deb_contents,
               properties = dict(binary_id=self.tbl_deb_contents.c.binary_id,
                                 package=self.tbl_deb_contents.c.package,
2903
                                 suite=self.tbl_deb_contents.c.suite,
M
Mike O'Connor 已提交
2904 2905 2906 2907 2908 2909 2910
                                 arch=self.tbl_deb_contents.c.arch,
                                 section=self.tbl_deb_contents.c.section,
                                 filename=self.tbl_deb_contents.c.filename))

        mapper(UdebContents, self.tbl_udeb_contents,
               properties = dict(binary_id=self.tbl_udeb_contents.c.binary_id,
                                 package=self.tbl_udeb_contents.c.package,
2911
                                 suite=self.tbl_udeb_contents.c.suite,
M
Mike O'Connor 已提交
2912 2913 2914
                                 arch=self.tbl_udeb_contents.c.arch,
                                 section=self.tbl_udeb_contents.c.section,
                                 filename=self.tbl_udeb_contents.c.filename))
M
Mike O'Connor 已提交
2915

2916 2917 2918 2919 2920 2921 2922
        mapper(BuildQueue, self.tbl_build_queue,
               properties = dict(queue_id = self.tbl_build_queue.c.id))

        mapper(BuildQueueFile, self.tbl_build_queue_files,
               properties = dict(buildqueue = relation(BuildQueue, backref='queuefiles'),
                                 poolfile = relation(PoolFile, backref='buildqueueinstances')))

2923
        mapper(DBBinary, self.tbl_binaries,
M
Mark Hymers 已提交
2924
               properties = dict(binary_id = self.tbl_binaries.c.id,
M
Mark Hymers 已提交
2925 2926
                                 package = self.tbl_binaries.c.package,
                                 version = self.tbl_binaries.c.version,
M
Mark Hymers 已提交
2927
                                 maintainer_id = self.tbl_binaries.c.maintainer,
M
Mark Hymers 已提交
2928
                                 maintainer = relation(Maintainer),
M
Mark Hymers 已提交
2929
                                 source_id = self.tbl_binaries.c.source,
2930
                                 source = relation(DBSource),
M
Mark Hymers 已提交
2931
                                 arch_id = self.tbl_binaries.c.architecture,
M
Mark Hymers 已提交
2932 2933 2934 2935 2936 2937 2938 2939 2940
                                 architecture = relation(Architecture),
                                 poolfile_id = self.tbl_binaries.c.file,
                                 poolfile = relation(PoolFile),
                                 binarytype = self.tbl_binaries.c.type,
                                 fingerprint_id = self.tbl_binaries.c.sig_fpr,
                                 fingerprint = relation(Fingerprint),
                                 install_date = self.tbl_binaries.c.install_date,
                                 binassociations = relation(BinAssociation,
                                                            primaryjoin=(self.tbl_binaries.c.id==self.tbl_bin_associations.c.bin))))
M
Mark Hymers 已提交
2941

2942 2943 2944 2945
        mapper(BinaryACL, self.tbl_binary_acl,
               properties = dict(binary_acl_id = self.tbl_binary_acl.c.id))

        mapper(BinaryACLMap, self.tbl_binary_acl_map,
2946 2947 2948
               properties = dict(binary_acl_map_id = self.tbl_binary_acl_map.c.id,
                                 fingerprint = relation(Fingerprint, backref="binary_acl_map"),
                                 architecture = relation(Architecture)))
2949

M
Mark Hymers 已提交
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
        mapper(Component, self.tbl_component,
               properties = dict(component_id = self.tbl_component.c.id,
                                 component_name = self.tbl_component.c.name))

        mapper(DBConfig, self.tbl_config,
               properties = dict(config_id = self.tbl_config.c.id))

        mapper(DSCFile, self.tbl_dsc_files,
               properties = dict(dscfile_id = self.tbl_dsc_files.c.id,
                                 source_id = self.tbl_dsc_files.c.source,
2960
                                 source = relation(DBSource),
M
Mark Hymers 已提交
2961 2962
                                 poolfile_id = self.tbl_dsc_files.c.file,
                                 poolfile = relation(PoolFile)))
M
Mark Hymers 已提交
2963 2964 2965 2966

        mapper(PoolFile, self.tbl_files,
               properties = dict(file_id = self.tbl_files.c.id,
                                 filesize = self.tbl_files.c.size,
M
Mark Hymers 已提交
2967 2968
                                 location_id = self.tbl_files.c.location,
                                 location = relation(Location)))
M
Mark Hymers 已提交
2969 2970 2971 2972

        mapper(Fingerprint, self.tbl_fingerprint,
               properties = dict(fingerprint_id = self.tbl_fingerprint.c.id,
                                 uid_id = self.tbl_fingerprint.c.uid,
M
Mark Hymers 已提交
2973 2974
                                 uid = relation(Uid),
                                 keyring_id = self.tbl_fingerprint.c.keyring,
2975 2976 2977
                                 keyring = relation(Keyring),
                                 source_acl = relation(SourceACL),
                                 binary_acl = relation(BinaryACL)))
M
Mark Hymers 已提交
2978 2979 2980 2981 2982

        mapper(Keyring, self.tbl_keyrings,
               properties = dict(keyring_name = self.tbl_keyrings.c.name,
                                 keyring_id = self.tbl_keyrings.c.id))

M
Mark Hymers 已提交
2983 2984
        mapper(DBChange, self.tbl_changes,
               properties = dict(change_id = self.tbl_changes.c.id,
M
Mark Hymers 已提交
2985 2986 2987
                                 poolfiles = relation(PoolFile,
                                                      secondary=self.tbl_changes_pool_files,
                                                      backref="changeslinks"),
2988
                                 seen = self.tbl_changes.c.seen,
2989 2990 2991 2992 2993 2994 2995 2996
                                 source = self.tbl_changes.c.source,
                                 binaries = self.tbl_changes.c.binaries,
                                 architecture = self.tbl_changes.c.architecture,
                                 distribution = self.tbl_changes.c.distribution,
                                 urgency = self.tbl_changes.c.urgency,
                                 maintainer = self.tbl_changes.c.maintainer,
                                 changedby = self.tbl_changes.c.changedby,
                                 date = self.tbl_changes.c.date,
M
Mike O'Connor 已提交
2997
                                 version = self.tbl_changes.c.version,
2998 2999 3000 3001 3002 3003 3004
                                 files = relation(ChangePendingFile,
                                                  secondary=self.tbl_changes_pending_files_map,
                                                  backref="changesfile"),
                                 in_queue_id = self.tbl_changes.c.in_queue,
                                 in_queue = relation(PolicyQueue,
                                                     primaryjoin=(self.tbl_changes.c.in_queue==self.tbl_policy_queue.c.id)),
                                 approved_for_id = self.tbl_changes.c.approved_for))
3005

M
Mark Hymers 已提交
3006 3007
        mapper(ChangePendingBinary, self.tbl_changes_pending_binaries,
               properties = dict(change_pending_binary_id = self.tbl_changes_pending_binaries.c.id))
M
Mark Hymers 已提交
3008

3009
        mapper(ChangePendingFile, self.tbl_changes_pending_files,
3010 3011 3012 3013 3014 3015
               properties = dict(change_pending_file_id = self.tbl_changes_pending_files.c.id,
                                 filename = self.tbl_changes_pending_files.c.filename,
                                 size = self.tbl_changes_pending_files.c.size,
                                 md5sum = self.tbl_changes_pending_files.c.md5sum,
                                 sha1sum = self.tbl_changes_pending_files.c.sha1sum,
                                 sha256sum = self.tbl_changes_pending_files.c.sha256sum))
3016 3017 3018

        mapper(ChangePendingSource, self.tbl_changes_pending_source,
               properties = dict(change_pending_source_id = self.tbl_changes_pending_source.c.id,
M
Mark Hymers 已提交
3019
                                 change = relation(DBChange),
3020 3021 3022 3023 3024 3025 3026
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_changes_pending_source.c.maintainer_id==self.tbl_maintainer.c.id)),
                                 changedby = relation(Maintainer,
                                                      primaryjoin=(self.tbl_changes_pending_source.c.changedby_id==self.tbl_maintainer.c.id)),
                                 fingerprint = relation(Fingerprint),
                                 source_files = relation(ChangePendingFile,
                                                         secondary=self.tbl_changes_pending_source_files,
3027
                                                         backref="pending_sources")))
M
Mark Hymers 已提交
3028

J
Joerg Jaspert 已提交
3029

M
Mark Hymers 已提交
3030 3031 3032 3033 3034
        mapper(KeyringACLMap, self.tbl_keyring_acl_map,
               properties = dict(keyring_acl_map_id = self.tbl_keyring_acl_map.c.id,
                                 keyring = relation(Keyring, backref="keyring_acl_map"),
                                 architecture = relation(Architecture)))

M
Mark Hymers 已提交
3035 3036 3037
        mapper(Location, self.tbl_location,
               properties = dict(location_id = self.tbl_location.c.id,
                                 component_id = self.tbl_location.c.component,
M
Mark Hymers 已提交
3038
                                 component = relation(Component),
M
Mark Hymers 已提交
3039
                                 archive_id = self.tbl_location.c.archive,
M
Mark Hymers 已提交
3040
                                 archive = relation(Archive),
M
Mark Hymers 已提交
3041 3042 3043 3044 3045
                                 archive_type = self.tbl_location.c.type))

        mapper(Maintainer, self.tbl_maintainer,
               properties = dict(maintainer_id = self.tbl_maintainer.c.id))

M
Mark Hymers 已提交
3046 3047 3048
        mapper(NewComment, self.tbl_new_comments,
               properties = dict(comment_id = self.tbl_new_comments.c.id))

M
Mark Hymers 已提交
3049 3050
        mapper(Override, self.tbl_override,
               properties = dict(suite_id = self.tbl_override.c.suite,
M
Mark Hymers 已提交
3051
                                 suite = relation(Suite),
3052
                                 package = self.tbl_override.c.package,
M
Mark Hymers 已提交
3053
                                 component_id = self.tbl_override.c.component,
M
Mark Hymers 已提交
3054
                                 component = relation(Component),
M
Mark Hymers 已提交
3055
                                 priority_id = self.tbl_override.c.priority,
M
Mark Hymers 已提交
3056
                                 priority = relation(Priority),
M
Mark Hymers 已提交
3057
                                 section_id = self.tbl_override.c.section,
M
Mark Hymers 已提交
3058 3059 3060
                                 section = relation(Section),
                                 overridetype_id = self.tbl_override.c.type,
                                 overridetype = relation(OverrideType)))
M
Mark Hymers 已提交
3061 3062 3063 3064 3065

        mapper(OverrideType, self.tbl_override_type,
               properties = dict(overridetype = self.tbl_override_type.c.type,
                                 overridetype_id = self.tbl_override_type.c.id))

3066 3067 3068
        mapper(PolicyQueue, self.tbl_policy_queue,
               properties = dict(policy_queue_id = self.tbl_policy_queue.c.id))

M
Mark Hymers 已提交
3069 3070 3071 3072
        mapper(Priority, self.tbl_priority,
               properties = dict(priority_id = self.tbl_priority.c.id))

        mapper(Section, self.tbl_section,
M
Mike O'Connor 已提交
3073 3074
               properties = dict(section_id = self.tbl_section.c.id,
                                 section=self.tbl_section.c.section))
M
Mark Hymers 已提交
3075

3076
        mapper(DBSource, self.tbl_source,
M
Mark Hymers 已提交
3077
               properties = dict(source_id = self.tbl_source.c.id,
M
Mark Hymers 已提交
3078
                                 version = self.tbl_source.c.version,
M
Mark Hymers 已提交
3079
                                 maintainer_id = self.tbl_source.c.maintainer,
M
Mark Hymers 已提交
3080 3081 3082 3083
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_source.c.maintainer==self.tbl_maintainer.c.id)),
                                 poolfile_id = self.tbl_source.c.file,
                                 poolfile = relation(PoolFile),
M
Mark Hymers 已提交
3084
                                 fingerprint_id = self.tbl_source.c.sig_fpr,
M
Mark Hymers 已提交
3085 3086 3087 3088 3089 3090 3091
                                 fingerprint = relation(Fingerprint),
                                 changedby_id = self.tbl_source.c.changedby,
                                 changedby = relation(Maintainer,
                                                      primaryjoin=(self.tbl_source.c.changedby==self.tbl_maintainer.c.id)),
                                 srcfiles = relation(DSCFile,
                                                     primaryjoin=(self.tbl_source.c.id==self.tbl_dsc_files.c.source)),
                                 srcassociations = relation(SrcAssociation,
M
Mark Hymers 已提交
3092 3093
                                                            primaryjoin=(self.tbl_source.c.id==self.tbl_src_associations.c.source)),
                                 srcuploaders = relation(SrcUploader)))
M
Mark Hymers 已提交
3094

3095 3096
        mapper(SourceACL, self.tbl_source_acl,
               properties = dict(source_acl_id = self.tbl_source_acl.c.id))
M
Mark Hymers 已提交
3097 3098

        mapper(SrcAssociation, self.tbl_src_associations,
M
Mark Hymers 已提交
3099 3100 3101 3102
               properties = dict(sa_id = self.tbl_src_associations.c.id,
                                 suite_id = self.tbl_src_associations.c.suite,
                                 suite = relation(Suite),
                                 source_id = self.tbl_src_associations.c.source,
3103
                                 source = relation(DBSource)))
M
Mark Hymers 已提交
3104

3105 3106 3107 3108
        mapper(SrcFormat, self.tbl_src_format,
               properties = dict(src_format_id = self.tbl_src_format.c.id,
                                 format_name = self.tbl_src_format.c.format_name))

M
Mark Hymers 已提交
3109 3110 3111
        mapper(SrcUploader, self.tbl_src_uploaders,
               properties = dict(uploader_id = self.tbl_src_uploaders.c.id,
                                 source_id = self.tbl_src_uploaders.c.source,
3112
                                 source = relation(DBSource,
M
Mark Hymers 已提交
3113 3114 3115 3116
                                                   primaryjoin=(self.tbl_src_uploaders.c.source==self.tbl_source.c.id)),
                                 maintainer_id = self.tbl_src_uploaders.c.maintainer,
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_src_uploaders.c.maintainer==self.tbl_maintainer.c.id))))
M
Mark Hymers 已提交
3117 3118

        mapper(Suite, self.tbl_suite,
3119
               properties = dict(suite_id = self.tbl_suite.c.id,
3120 3121
                                 policy_queue = relation(PolicyQueue),
                                 copy_queues = relation(BuildQueue, secondary=self.tbl_suite_build_queue_copy)))
M
Mark Hymers 已提交
3122 3123 3124

        mapper(SuiteArchitecture, self.tbl_suite_architectures,
               properties = dict(suite_id = self.tbl_suite_architectures.c.suite,
3125
                                 suite = relation(Suite, backref='suitearchitectures'),
M
Mark Hymers 已提交
3126 3127
                                 arch_id = self.tbl_suite_architectures.c.architecture,
                                 architecture = relation(Architecture)))
M
Mark Hymers 已提交
3128

3129 3130 3131 3132 3133 3134
        mapper(SuiteSrcFormat, self.tbl_suite_src_formats,
               properties = dict(suite_id = self.tbl_suite_src_formats.c.suite,
                                 suite = relation(Suite, backref='suitesrcformats'),
                                 src_format_id = self.tbl_suite_src_formats.c.src_format,
                                 src_format = relation(SrcFormat)))

M
Mark Hymers 已提交
3135
        mapper(Uid, self.tbl_uid,
3136 3137
               properties = dict(uid_id = self.tbl_uid.c.id,
                                 fingerprint = relation(Fingerprint)))
M
Mark Hymers 已提交
3138

3139
        mapper(UploadBlock, self.tbl_upload_blocks,
3140 3141 3142
               properties = dict(upload_block_id = self.tbl_upload_blocks.c.id,
                                 fingerprint = relation(Fingerprint, backref="uploadblocks"),
                                 uid = relation(Uid, backref="uploadblocks")))
3143

M
Mark Hymers 已提交
3144 3145
    ## Connection functions
    def __createconn(self):
M
Mark Hymers 已提交
3146
        from config import Config
3147 3148
        cnf = Config()
        if cnf["DB::Host"]:
M
Mark Hymers 已提交
3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
            # TCP/IP
            connstr = "postgres://%s" % cnf["DB::Host"]
            if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
                connstr += ":%s" % cnf["DB::Port"]
            connstr += "/%s" % cnf["DB::Name"]
        else:
            # Unix Socket
            connstr = "postgres:///%s" % cnf["DB::Name"]
            if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
                connstr += "?port=%s" % cnf["DB::Port"]
3159

M
updates  
Mark Hymers 已提交
3160
        self.db_pg   = create_engine(connstr, echo=self.debug)
M
Mark Hymers 已提交
3161 3162 3163 3164
        self.db_meta = MetaData()
        self.db_meta.bind = self.db_pg
        self.db_smaker = sessionmaker(bind=self.db_pg,
                                      autoflush=True,
3165
                                      autocommit=False)
M
Mark Hymers 已提交
3166

M
Mark Hymers 已提交
3167
        self.__setuptables()
M
Mark Hymers 已提交
3168
        self.__setupmappers()
M
Mark Hymers 已提交
3169

M
Mark Hymers 已提交
3170 3171
    def session(self):
        return self.db_smaker()
M
Mark Hymers 已提交
3172

M
Mark Hymers 已提交
3173
__all__.append('DBConn')
M
Mike O'Connor 已提交
3174

3175