contents.py 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#!/usr/bin/env python
"""
Helper code for contents generation.

@contact: Debian FTPMaster <ftpmaster@debian.org>
@copyright: 2011 Torsten Werner <twerner@debian.org>
@license: GNU General Public License version 2 or later
"""

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

# 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

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

from daklib.dbconn import *
from daklib.config import Config
T
Torsten Werner 已提交
30
from daklib.threadpool import ThreadPool
31
from multiprocessing import Pool
32 33

from sqlalchemy import desc, or_
34
from sqlalchemy.exc import IntegrityError
35
from subprocess import Popen, PIPE
36

T
Torsten Werner 已提交
37
import os.path
T
Torsten Werner 已提交
38

39 40 41 42 43 44 45 46 47 48
class ContentsWriter(object):
    '''
    ContentsWriter writes the Contents-$arch.gz files.
    '''
    def __init__(self, suite, architecture, overridetype, component = None):
        '''
        The constructor clones its arguments into a new session object to make
        sure that the new ContentsWriter object can be executed in a different
        thread.
        '''
49 50 51 52 53
        self.suite = suite
        self.architecture = architecture
        self.overridetype = overridetype
        self.component = component
        self.session = suite.session()
54 55 56 57 58

    def query(self):
        '''
        Returns a query object that is doing most of the work.
        '''
59 60
        overridesuite = self.suite
        if self.suite.overridesuite is not None:
T
Torsten Werner 已提交
61
            overridesuite = get_suite(self.suite.overridesuite, self.session)
62
        params = {
63
            'suite':         self.suite.suite_id,
T
Torsten Werner 已提交
64
            'overridesuite': overridesuite.suite_id,
65 66 67 68
            'arch_all':      get_architecture('all', self.session).arch_id,
            'arch':          self.architecture.arch_id,
            'type_id':       self.overridetype.overridetype_id,
            'type':          self.overridetype.overridetype,
69 70 71
        }

        if self.component is not None:
T
Torsten Werner 已提交
72
            params['component'] = self.component.component_id
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            sql = '''
create temp table newest_binaries (
    id integer primary key,
    package text);

create index newest_binaries_by_package on newest_binaries (package);

insert into newest_binaries (id, package)
    select distinct on (package) id, package from binaries
        where type = :type and
            (architecture = :arch_all or architecture = :arch) and
            id in (select bin from bin_associations where suite = :suite)
        order by package, version desc;

with

unique_override as
    (select o.package, s.section
        from override o, section s
92
        where o.suite = :overridesuite and o.type = :type_id and o.section = s.id and
93 94
        o.component = :component)

95
select bc.file, string_agg(o.section || '/' || b.package, ',' order by b.package) as pkglist
96 97
    from newest_binaries b, bin_contents bc, unique_override o
    where b.id = bc.binary_id and o.package = b.package
98
    group by bc.file'''
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

        else:
            sql = '''
create temp table newest_binaries (
    id integer primary key,
    package text);

create index newest_binaries_by_package on newest_binaries (package);

insert into newest_binaries (id, package)
    select distinct on (package) id, package from binaries
        where type = :type and
            (architecture = :arch_all or architecture = :arch) and
            id in (select bin from bin_associations where suite = :suite)
        order by package, version desc;

with

unique_override as
    (select distinct on (o.package, s.section) o.package, s.section
        from override o, section s
120
        where o.suite = :overridesuite and o.type = :type_id and o.section = s.id
121 122
        order by o.package, s.section, o.modified desc)

123
select bc.file, string_agg(o.section || '/' || b.package, ',' order by b.package) as pkglist
124 125
    from newest_binaries b, bin_contents bc, unique_override o
    where b.id = bc.binary_id and o.package = b.package
126
    group by bc.file'''
127

128
        return self.session.query("file", "pkglist").from_statement(sql). \
129 130 131 132 133 134
            params(params)

    def formatline(self, filename, package_list):
        '''
        Returns a formatted string for the filename argument.
        '''
T
Torsten Werner 已提交
135
        return "%-55s %s\n" % (filename, package_list)
136 137 138 139 140

    def fetch(self):
        '''
        Yields a new line of the Contents-$arch.gz file in filename order.
        '''
141 142
        for filename, package_list in self.query().yield_per(100):
            yield self.formatline(filename, package_list)
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        # end transaction to return connection to pool
        self.session.rollback()

    def get_list(self):
        '''
        Returns a list of lines for the Contents-$arch.gz file.
        '''
        return [item for item in self.fetch()]

    def output_filename(self):
        '''
        Returns the name of the output file.
        '''
        values = {
            'root': Config()['Dir::Root'],
            'suite': self.suite.suite_name,
            'architecture': self.architecture.arch_string
        }
        if self.component is None:
162
            return "%(root)s/dists/%(suite)s/Contents-%(architecture)s.gz" % values
163
        values['component'] = self.component.component_name
164
        return "%(root)s/dists/%(suite)s/%(component)s/Contents-%(architecture)s.gz" % values
165

T
Torsten Werner 已提交
166 167 168 169
    def get_header(self):
        '''
        Returns the header for the Contents files as a string.
        '''
T
Torsten Werner 已提交
170
        header_file = None
T
Torsten Werner 已提交
171
        try:
T
Torsten Werner 已提交
172
            filename = os.path.join(Config()['Dir::Templates'], 'contents')
T
Torsten Werner 已提交
173 174 175 176 177 178
            header_file = open(filename)
            return header_file.read()
        finally:
            if header_file:
                header_file.close()

179
    def write_file(self):
180
        '''
181
        Write the output file.
182 183
        '''
        command = ['gzip', '--rsyncable']
184 185 186
        final_filename = self.output_filename()
        temp_filename = final_filename + '.new'
        output_file = open(temp_filename, 'w')
187 188
        gzip = Popen(command, stdin = PIPE, stdout = output_file)
        gzip.stdin.write(self.get_header())
189
        for item in self.fetch():
190 191
            gzip.stdin.write(item)
        gzip.stdin.close()
192
        output_file.close()
193
        gzip.wait()
194 195 196 197
        try:
            os.remove(final_filename)
        except:
            pass
198 199
        os.rename(temp_filename, final_filename)
        os.chmod(final_filename, 0664)
T
Torsten Werner 已提交
200

201 202 203 204 205 206 207 208
    @classmethod
    def write_all(class_, suite_names = [], force = False):
        '''
        Writes all Contents files for suites in list suite_names which defaults
        to all 'touchable' suites if not specified explicitely. Untouchable
        suites will be included if the force argument is set to True.
        '''
        session = DBConn().session()
T
Torsten Werner 已提交
209
        suite_query = session.query(Suite)
210
        if len(suite_names) > 0:
T
Torsten Werner 已提交
211
            suite_query = suite_query.filter(Suite.suite_name.in_(suite_names))
212 213
        if not force:
            suite_query = suite_query.filter_by(untouchable = False)
214 215 216 217
        deb_id = get_override_type('deb', session).overridetype_id
        udeb_id = get_override_type('udeb', session).overridetype_id
        main_id = get_component('main', session).component_id
        non_free_id = get_component('non-free', session).component_id
218
        pool = Pool()
219
        for suite in suite_query:
220
            suite_id = suite.suite_id
T
Torsten Werner 已提交
221
            for architecture in suite.get_architectures(skipsrc = True, skipall = True):
222
                arch_id = architecture.arch_id
223
                # handle 'deb' packages
224
                pool.apply_async(generate_helper, (suite_id, arch_id, deb_id))
225
                # handle 'udeb' packages for 'main' and 'non-free'
226 227
                pool.apply_async(generate_helper, (suite_id, arch_id, udeb_id, main_id))
                pool.apply_async(generate_helper, (suite_id, arch_id, udeb_id, non_free_id))
228 229
        pool.close()
        pool.join()
230 231
        session.close()

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
def generate_helper(suite_id, arch_id, overridetype_id, component_id = None):
    '''
    This function is called in a new subprocess.
    '''
    DBConn().reset()
    session = DBConn().session()
    suite = Suite.get(suite_id, session)
    architecture = Architecture.get(arch_id, session)
    overridetype = OverrideType.get(overridetype_id, session)
    if component_id is None:
        component = None
    else:
        component = Component.get(component_id, session)
    contents_writer = ContentsWriter(suite, architecture, overridetype, component)
    contents_writer.write_file()

T
Torsten Werner 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

class ContentsScanner(object):
    '''
    ContentsScanner provides a threadsafe method scan() to scan the contents of
    a DBBinary object.
    '''
    def __init__(self, binary):
        '''
        The argument binary is the actual DBBinary object that should be
        scanned.
        '''
        self.binary_id = binary.binary_id

    def scan(self, dummy_arg = None):
        '''
        This method does the actual scan and fills in the associated BinContents
        property. It commits any changes to the database. The argument dummy_arg
        is ignored but needed by our threadpool implementation.
        '''
        session = DBConn().session()
        binary = session.query(DBBinary).get(self.binary_id)
269 270 271 272
        fileset = set(binary.scan_contents())
        if len(fileset) == 0:
            fileset.add('EMPTY_PACKAGE')
        for filename in fileset:
T
Torsten Werner 已提交
273
            binary.contents.append(BinContents(file = filename))
274
        session.commit()
T
Torsten Werner 已提交
275 276 277 278 279 280 281
        session.close()

    @classmethod
    def scan_all(class_, limit = None):
        '''
        The class method scan_all() scans all binaries using multiple threads.
        The number of binaries to be scanned can be limited with the limit
282 283
        argument. Returns the number of processed and remaining packages as a
        dict.
T
Torsten Werner 已提交
284 285
        '''
        session = DBConn().session()
286
        query = session.query(DBBinary).filter(DBBinary.contents == None)
287
        remaining = query.count
T
Torsten Werner 已提交
288 289
        if limit is not None:
            query = query.limit(limit)
290
        processed = query.count()
T
Torsten Werner 已提交
291 292 293 294
        threadpool = ThreadPool()
        for binary in query.yield_per(100):
            threadpool.queueTask(ContentsScanner(binary).scan)
        threadpool.joinAll()
295
        remaining = remaining()
T
Torsten Werner 已提交
296
        session.close()
297
        return { 'processed': processed, 'remaining': remaining }