]> git.decadent.org.uk Git - dak.git/blob - dak/generate_packages_sources2.py
Enhance process pool implementation
[dak.git] / dak / generate_packages_sources2.py
1 #!/usr/bin/python
2
3 """
4 Generate Packages/Sources files
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2011  Ansgar Burchardt <ansgar@debian.org>
8 @copyright: Based on daklib/lists.py and dak/generate_filelist.py:
9             2009-2011  Torsten Werner <twerner@debian.org>
10 @copyright: Based on dak/generate_packages_sources.py:
11             2000, 2001, 2002, 2006  James Troup <james@nocrew.org>
12             2009  Mark Hymers <mhy@debian.org>
13             2010  Joerg Jaspert <joerg@debian.org>
14 @license: GNU General Public License version 2 or later
15 """
16
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26
27 # You should have received a copy of the GNU General Public License
28 # along with this program; if not, write to the Free Software
29 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
31 from daklib.dbconn import *
32 from daklib.config import Config
33 from daklib import utils, daklog
34 from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS, PROC_STATUS_SIGNALRAISED
35 from daklib.filewriter import PackagesFileWriter, SourcesFileWriter
36
37 import apt_pkg, os, stat, sys
38
39 EXIT_STATUS = 0
40
41 def usage():
42     print """Usage: dak generate-packages-sources2 [OPTIONS]
43 Generate the Packages/Sources files
44
45   -s, --suite=SUITE            process this suite
46                                Default: All suites not marked 'untouchable'
47   -f, --force                  Allow processing of untouchable suites
48                                CAREFUL: Only to be used at point release time!
49   -h, --help                   show this help and exit
50
51 SUITE can be a space seperated list, e.g.
52    --suite=unstable testing
53 """
54     sys.exit()
55
56 #############################################################################
57
58 # Here be dragons.
59 _sources_query = R"""
60 SELECT
61
62   (SELECT
63      STRING_AGG(
64        CASE
65          WHEN key = 'Source' THEN 'Package\: '
66          WHEN key = 'Files' THEN E'Files\:\n ' || f.md5sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
67          WHEN key = 'Checksums-Sha1' THEN E'Checksums-Sha1\:\n ' || f.sha1sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
68          WHEN key = 'Checksums-Sha256' THEN E'Checksums-Sha256\:\n ' || f.sha256sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
69          ELSE key || '\: '
70        END || value, E'\n' ORDER BY mk.ordering, mk.key)
71    FROM
72      source_metadata sm
73      JOIN metadata_keys mk ON mk.key_id = sm.key_id
74    WHERE s.id=sm.src_id
75   )
76   ||
77   E'\nDirectory\: pool/' || SUBSTRING(f.filename FROM E'\\A(.*)/[^/]*\\Z')
78   ||
79   E'\nPriority\: ' || pri.priority
80   ||
81   E'\nSection\: ' || sec.section
82
83 FROM
84
85 source s
86 JOIN src_associations sa ON s.id = sa.source
87 JOIN files f ON s.file=f.id
88 JOIN override o ON o.package = s.source
89 JOIN section sec ON o.section = sec.id
90 JOIN priority pri ON o.priority = pri.id
91
92 WHERE
93   sa.suite = :suite
94   AND o.suite = :overridesuite AND o.component = :component AND o.type = :dsc_type
95
96 ORDER BY
97 s.source, s.version
98 """
99
100 def generate_sources(suite_id, component_id):
101     global _sources_query
102
103     session = DBConn().session()
104     dsc_type = session.query(OverrideType).filter_by(overridetype='dsc').one().overridetype_id
105
106     suite = session.query(Suite).get(suite_id)
107     component = session.query(Component).get(component_id)
108
109     overridesuite_id = suite.get_overridesuite().suite_id
110
111     writer = SourcesFileWriter(suite=suite.suite_name, component=component.component_name)
112     output = writer.open()
113
114     # run query and write Sources
115     r = session.execute(_sources_query, {"suite": suite_id, "component": component_id, "dsc_type": dsc_type, "overridesuite": overridesuite_id})
116     for (stanza,) in r:
117         print >>output, stanza
118         print >>output, ""
119
120     writer.close()
121
122     message = ["generate sources", suite.suite_name, component.component_name]
123     session.rollback()
124     return message
125
126 #############################################################################
127
128 # Here be large dragons.
129 _packages_query = R"""
130 WITH
131
132   tmp AS (
133     SELECT
134       b.id AS binary_id,
135       b.package AS package,
136       b.version AS version,
137       b.architecture AS architecture,
138       b.source AS source_id,
139       s.source AS source,
140       f.filename AS filename,
141       f.size AS size,
142       f.md5sum AS md5sum,
143       f.sha1sum AS sha1sum,
144       f.sha256sum AS sha256sum
145     FROM
146       binaries b
147       JOIN bin_associations ba ON b.id = ba.bin
148       JOIN files f ON f.id = b.file
149       JOIN location l ON l.id = f.location
150       JOIN source s ON b.source = s.id
151     WHERE
152       (b.architecture = :arch_all OR b.architecture = :arch) AND b.type = :type_name
153       AND ba.suite = :suite
154       AND l.component = :component
155   )
156
157 SELECT
158   (SELECT
159      STRING_AGG(key || '\: ' || value, E'\n' ORDER BY mk.ordering, mk.key)
160    FROM
161      binaries_metadata bm
162      JOIN metadata_keys mk ON mk.key_id = bm.key_id
163    WHERE
164      bm.bin_id = tmp.binary_id
165      AND key != 'Section' AND key != 'Priority'
166   )
167   || COALESCE(E'\n' || (SELECT
168      STRING_AGG(key || '\: ' || value, E'\n' ORDER BY key)
169    FROM external_overrides eo
170    WHERE eo.package = tmp.package
171   ), '')
172   || E'\nSection\: ' || sec.section
173   || E'\nPriority\: ' || pri.priority
174   || E'\nFilename\: pool/' || tmp.filename
175   || E'\nSize\: ' || tmp.size
176   || E'\nMD5sum\: ' || tmp.md5sum
177   || E'\nSHA1\: ' || tmp.sha1sum
178   || E'\nSHA256\: ' || tmp.sha256sum
179
180 FROM
181   tmp
182   JOIN override o ON o.package = tmp.package
183   JOIN section sec ON sec.id = o.section
184   JOIN priority pri ON pri.id = o.priority
185
186 WHERE
187   (
188       architecture <> :arch_all
189     OR
190       (architecture = :arch_all AND source_id IN (SELECT source_id FROM tmp WHERE architecture <> :arch_all))
191     OR
192       (architecture = :arch_all AND source NOT IN (SELECT DISTINCT source FROM tmp WHERE architecture <> :arch_all))
193   )
194   AND
195     o.type = :type_id AND o.suite = :overridesuite AND o.component = :component
196
197 ORDER BY tmp.package, tmp.version
198 """
199
200 def generate_packages(suite_id, component_id, architecture_id, type_name):
201     global _packages_query
202
203     session = DBConn().session()
204     arch_all_id = session.query(Architecture).filter_by(arch_string='all').one().arch_id
205     type_id = session.query(OverrideType).filter_by(overridetype=type_name).one().overridetype_id
206
207     suite = session.query(Suite).get(suite_id)
208     component = session.query(Component).get(component_id)
209     architecture = session.query(Architecture).get(architecture_id)
210
211     overridesuite_id = suite.get_overridesuite().suite_id
212
213     writer = PackagesFileWriter(suite=suite.suite_name, component=component.component_name,
214             architecture=architecture.arch_string, debtype=type_name)
215     output = writer.open()
216
217     r = session.execute(_packages_query, {"suite": suite_id, "component": component_id,
218         "arch": architecture_id, "type_id": type_id, "type_name": type_name, "arch_all": arch_all_id,
219         "overridesuite": overridesuite_id})
220     for (stanza,) in r:
221         print >>output, stanza
222         print >>output, ""
223
224     writer.close()
225
226     message = ["generate-packages", suite.suite_name, component.component_name, architecture.arch_string]
227     session.rollback()
228     return message
229
230 #############################################################################
231
232 def main():
233     cnf = Config()
234
235     Arguments = [('h',"help","Generate-Packages-Sources::Options::Help"),
236                  ('s',"suite","Generate-Packages-Sources::Options::Suite"),
237                  ('f',"force","Generate-Packages-Sources::Options::Force")]
238
239     suite_names = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
240     try:
241         Options = cnf.SubTree("Generate-Packages-Sources::Options")
242     except KeyError:
243         Options = {}
244
245     if Options.has_key("Help"):
246         usage()
247
248     logger = daklog.Logger(cnf, 'generate-packages-sources2')
249
250     session = DBConn().session()
251
252     if Options.has_key("Suite"):
253         suites = []
254         for s in suite_names:
255             suite = get_suite(s.lower(), session)
256             if suite:
257                 suites.append(suite)
258             else:
259                 print "I: Cannot find suite %s" % s
260                 logger.log(['Cannot find suite %s' % s])
261     else:
262         suites = session.query(Suite).filter(Suite.untouchable == False).all()
263
264     force = Options.has_key("Force") and Options["Force"]
265
266     component_ids = [ c.component_id for c in session.query(Component).all() ]
267
268     def parse_results(message):
269         # Split out into (code, msg)
270         code, msg = message
271         if code == PROC_STATUS_SUCCESS:
272             Logger.log([msg])
273         elif code == PROC_STATUS_SIGNALRAISED:
274             Logger.log(['E: Subprocess recieved signal ', msg])
275         else:
276             Logger.log(['E: ', msg])
277
278     pool = DakProcessPool()
279     for s in suites:
280         if s.untouchable and not force:
281             utils.fubar("Refusing to touch %s (untouchable and not forced)" % s.suite_name)
282         for c in component_ids:
283             pool.apply_async(generate_sources, [s.suite_id, c], callback=parse_result)
284             for a in s.architectures:
285                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'deb'], callback=parse_result)
286                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'udeb'], callback=parse_result)
287
288     pool.close()
289     pool.join()
290
291     # this script doesn't change the database
292     session.close()
293
294     logger.close()
295
296     sys.exit(pool.output_status())
297
298 if __name__ == '__main__':
299     main()