]> git.decadent.org.uk Git - dak.git/blob - dak/generate_packages_sources2.py
Debug suites might also miss the source package
[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 import apt_pkg, sys
32
33 def usage():
34     print """Usage: dak generate-packages-sources2 [OPTIONS]
35 Generate the Packages/Sources files
36
37   -a, --archive=ARCHIVE        process suites in ARCHIVE
38   -s, --suite=SUITE            process this suite
39                                Default: All suites not marked 'untouchable'
40   -f, --force                  Allow processing of untouchable suites
41                                CAREFUL: Only to be used at point release time!
42   -h, --help                   show this help and exit
43
44 SUITE can be a space seperated list, e.g.
45    --suite=unstable testing
46 """
47     sys.exit()
48
49 #############################################################################
50
51 # Here be dragons.
52 _sources_query = R"""
53 SELECT
54
55   (SELECT
56      STRING_AGG(
57        CASE
58          WHEN key = 'Source' THEN E'Package\: '
59          WHEN key = 'Files' THEN E'Files\:\n ' || f.md5sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
60          WHEN key = 'Checksums-Sha1' THEN E'Checksums-Sha1\:\n ' || f.sha1sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
61          WHEN key = 'Checksums-Sha256' THEN E'Checksums-Sha256\:\n ' || f.sha256sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
62          ELSE key || E'\: '
63        END || value, E'\n' ORDER BY mk.ordering, mk.key)
64    FROM
65      source_metadata sm
66      JOIN metadata_keys mk ON mk.key_id = sm.key_id
67    WHERE s.id=sm.src_id
68   )
69   ||
70   CASE
71     WHEN src_associations_full.extra_source THEN E'\nExtra-Source-Only\: yes'
72     ELSE ''
73   END
74   ||
75   E'\nDirectory\: pool/' || :component_name || '/' || SUBSTRING(f.filename FROM E'\\A(.*)/[^/]*\\Z')
76   ||
77   E'\nPriority\: ' || COALESCE(pri.priority, 'extra')
78   ||
79   E'\nSection\: ' || COALESCE(sec.section, 'misc')
80
81 FROM
82
83 source s
84 JOIN src_associations_full ON src_associations_full.suite = :suite AND s.id = src_associations_full.source
85 JOIN files f ON s.file=f.id
86 JOIN files_archive_map fam
87   ON fam.file_id = f.id
88      AND fam.archive_id = (SELECT archive_id FROM suite WHERE id = :suite)
89      AND fam.component_id = :component
90 LEFT JOIN override o ON o.package = s.source
91                      AND o.suite = :overridesuite
92                      AND o.component = :component
93                      AND o.type = :dsc_type
94 LEFT JOIN section sec ON o.section = sec.id
95 LEFT JOIN priority pri ON o.priority = pri.id
96
97 ORDER BY
98 s.source, s.version
99 """
100
101 def generate_sources(suite_id, component_id):
102     global _sources_query
103     from daklib.filewriter import SourcesFileWriter
104     from daklib.dbconn import Component, DBConn, OverrideType, Suite
105     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
106
107     session = DBConn().session()
108     dsc_type = session.query(OverrideType).filter_by(overridetype='dsc').one().overridetype_id
109
110     suite = session.query(Suite).get(suite_id)
111     component = session.query(Component).get(component_id)
112
113     overridesuite_id = suite.get_overridesuite().suite_id
114
115     writer_args = {
116             'archive': suite.archive.path,
117             'suite': suite.suite_name,
118             'component': component.component_name
119     }
120     if suite.indices_compression is not None:
121         writer_args['compression'] = suite.indices_compression
122     writer = SourcesFileWriter(**writer_args)
123     output = writer.open()
124
125     # run query and write Sources
126     r = session.execute(_sources_query, {"suite": suite_id, "component": component_id, "component_name": component.component_name, "dsc_type": dsc_type, "overridesuite": overridesuite_id})
127     for (stanza,) in r:
128         print >>output, stanza
129         print >>output, ""
130
131     writer.close()
132
133     message = ["generate sources", suite.suite_name, component.component_name]
134     session.rollback()
135     return (PROC_STATUS_SUCCESS, message)
136
137 #############################################################################
138
139 # Here be large dragons.
140 _packages_query = R"""
141 WITH
142
143   tmp AS (
144     SELECT
145       b.id AS binary_id,
146       b.package AS package,
147       b.version AS version,
148       b.architecture AS architecture,
149       b.source AS source_id,
150       s.source AS source,
151       f.filename AS filename,
152       f.size AS size,
153       f.md5sum AS md5sum,
154       f.sha1sum AS sha1sum,
155       f.sha256sum AS sha256sum,
156       (SELECT value FROM binaries_metadata
157         WHERE bin_id = b.id
158           AND key_id = (SELECT key_id FROM metadata_keys WHERE key = 'Priority'))
159        AS fallback_priority,
160       (SELECT value FROM binaries_metadata
161         WHERE bin_id = b.id
162           AND key_id = (SELECT key_id FROM metadata_keys WHERE key = 'Section'))
163        AS fallback_section
164     FROM
165       binaries b
166       JOIN bin_associations ba ON b.id = ba.bin
167       JOIN files f ON f.id = b.file
168       JOIN files_archive_map fam ON f.id = fam.file_id AND fam.archive_id = :archive_id
169       JOIN source s ON b.source = s.id
170     WHERE
171       (b.architecture = :arch_all OR b.architecture = :arch) AND b.type = :type_name
172       AND ba.suite = :suite
173       AND fam.component_id = :component
174   )
175
176 SELECT
177   (SELECT
178      STRING_AGG(key || E'\: ' || value, E'\n' ORDER BY ordering, key)
179    FROM
180      (SELECT key, ordering,
181         CASE WHEN :include_long_description = 'false' AND key = 'Description'
182           THEN SUBSTRING(value FROM E'\\A[^\n]*')
183           ELSE value
184         END AS value
185       FROM
186         binaries_metadata bm
187         JOIN metadata_keys mk ON mk.key_id = bm.key_id
188       WHERE
189         bm.bin_id = tmp.binary_id
190         AND key != ALL (:metadata_skip)
191      ) AS metadata
192   )
193   || COALESCE(E'\n' || (SELECT
194      STRING_AGG(key || E'\: ' || value, E'\n' ORDER BY key)
195    FROM external_overrides eo
196    WHERE
197      eo.package = tmp.package
198      AND eo.suite = :overridesuite AND eo.component = :component
199   ), '')
200   || E'\nSection\: ' || COALESCE(sec.section, tmp.fallback_section)
201   || E'\nPriority\: ' || COALESCE(pri.priority, tmp.fallback_priority)
202   || E'\nFilename\: pool/' || :component_name || '/' || tmp.filename
203   || E'\nSize\: ' || tmp.size
204   || E'\nMD5sum\: ' || tmp.md5sum
205   || E'\nSHA1\: ' || tmp.sha1sum
206   || E'\nSHA256\: ' || tmp.sha256sum
207
208 FROM
209   tmp
210   LEFT JOIN override o ON o.package = tmp.package
211                       AND o.type = :type_id
212                       AND o.suite = :overridesuite
213                       AND o.component = :component
214   LEFT JOIN section sec ON sec.id = o.section
215   LEFT JOIN priority pri ON pri.id = o.priority
216
217 WHERE
218   (
219       architecture <> :arch_all
220     OR
221       (architecture = :arch_all AND source_id IN (SELECT source_id FROM tmp WHERE architecture <> :arch_all))
222     OR
223       (architecture = :arch_all AND source NOT IN (SELECT DISTINCT source FROM tmp WHERE architecture <> :arch_all))
224   )
225
226 ORDER BY tmp.source, tmp.package, tmp.version
227 """
228
229 def generate_packages(suite_id, component_id, architecture_id, type_name):
230     global _packages_query
231     from daklib.filewriter import PackagesFileWriter
232     from daklib.dbconn import Architecture, Component, DBConn, OverrideType, Suite
233     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
234
235     session = DBConn().session()
236     arch_all_id = session.query(Architecture).filter_by(arch_string='all').one().arch_id
237     type_id = session.query(OverrideType).filter_by(overridetype=type_name).one().overridetype_id
238
239     suite = session.query(Suite).get(suite_id)
240     component = session.query(Component).get(component_id)
241     architecture = session.query(Architecture).get(architecture_id)
242
243     overridesuite_id = suite.get_overridesuite().suite_id
244     include_long_description = suite.include_long_description
245
246     # We currently filter out the "Tag" line. They are set by external
247     # overrides and NOT by the maintainer. And actually having it set by
248     # maintainer means we output it twice at the moment -> which breaks
249     # dselect.
250     metadata_skip = ["Section", "Priority", "Tag"]
251     if include_long_description:
252         metadata_skip.append("Description-md5")
253
254     writer_args = {
255             'archive': suite.archive.path,
256             'suite': suite.suite_name,
257             'component': component.component_name,
258             'architecture': architecture.arch_string,
259             'debtype': type_name
260     }
261     if suite.indices_compression is not None:
262         writer_args['compression'] = suite.indices_compression
263     writer = PackagesFileWriter(**writer_args)
264     output = writer.open()
265
266     r = session.execute(_packages_query, {"archive_id": suite.archive.archive_id,
267         "suite": suite_id, "component": component_id, 'component_name': component.component_name,
268         "arch": architecture_id, "type_id": type_id, "type_name": type_name, "arch_all": arch_all_id,
269         "overridesuite": overridesuite_id, "metadata_skip": metadata_skip,
270         "include_long_description": 'true' if include_long_description else 'false'})
271     for (stanza,) in r:
272         print >>output, stanza
273         print >>output, ""
274
275     writer.close()
276
277     message = ["generate-packages", suite.suite_name, component.component_name, architecture.arch_string]
278     session.rollback()
279     return (PROC_STATUS_SUCCESS, message)
280
281 #############################################################################
282
283 _translations_query = """
284 WITH
285   override_suite AS
286     (SELECT
287       s.id AS id,
288       COALESCE(os.id, s.id) AS overridesuite_id
289       FROM suite AS s LEFT JOIN suite AS os ON s.overridesuite = os.suite_name)
290
291 SELECT
292      E'Package\: ' || b.package
293   || E'\nDescription-md5\: ' || bm_description_md5.value
294   || E'\nDescription-en\: ' || bm_description.value
295   || E'\n'
296 FROM binaries b
297   -- join tables for suite and component
298   JOIN bin_associations ba ON b.id = ba.bin
299   JOIN override_suite os ON os.id = ba.suite
300   JOIN override o ON b.package = o.package AND o.suite = os.overridesuite_id AND o.type = (SELECT id FROM override_type WHERE type = 'deb')
301
302   -- join tables for Description and Description-md5
303   JOIN binaries_metadata bm_description ON b.id = bm_description.bin_id AND bm_description.key_id = (SELECT key_id FROM metadata_keys WHERE key = 'Description')
304   JOIN binaries_metadata bm_description_md5 ON b.id = bm_description_md5.bin_id AND bm_description_md5.key_id = (SELECT key_id FROM metadata_keys WHERE key = 'Description-md5')
305
306   -- we want to sort by source name
307   JOIN source s ON b.source = s.id
308
309 WHERE ba.suite = :suite AND o.component = :component
310 GROUP BY b.package, bm_description_md5.value, bm_description.value
311 ORDER BY MIN(s.source), b.package, bm_description_md5.value
312 """
313
314 def generate_translations(suite_id, component_id):
315     global _translations_query
316     from daklib.filewriter import TranslationFileWriter
317     from daklib.dbconn import DBConn, Suite, Component
318     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
319
320     session = DBConn().session()
321     suite = session.query(Suite).get(suite_id)
322     component = session.query(Component).get(component_id)
323
324     writer_args = {
325             'archive': suite.archive.path,
326             'suite': suite.suite_name,
327             'component': component.component_name,
328             'language': 'en',
329     }
330     if suite.i18n_compression is not None:
331         writer_args['compression'] = suite.i18n_compression
332     writer = TranslationFileWriter(**writer_args)
333     output = writer.open()
334
335     r = session.execute(_translations_query, {"suite": suite_id, "component": component_id})
336     for (stanza,) in r:
337         print >>output, stanza
338
339     writer.close()
340
341     message = ["generate-translations", suite.suite_name, component.component_name]
342     session.rollback()
343     return (PROC_STATUS_SUCCESS, message)
344
345 #############################################################################
346
347 def main():
348     from daklib.config import Config
349     from daklib import daklog
350
351     cnf = Config()
352
353     Arguments = [('h',"help","Generate-Packages-Sources::Options::Help"),
354                  ('a','archive','Generate-Packages-Sources::Options::Archive','HasArg'),
355                  ('s',"suite","Generate-Packages-Sources::Options::Suite"),
356                  ('f',"force","Generate-Packages-Sources::Options::Force"),
357                  ('o','option','','ArbItem')]
358
359     suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
360     try:
361         Options = cnf.subtree("Generate-Packages-Sources::Options")
362     except KeyError:
363         Options = {}
364
365     if Options.has_key("Help"):
366         usage()
367
368     from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS, PROC_STATUS_SIGNALRAISED
369     pool = DakProcessPool()
370
371     logger = daklog.Logger('generate-packages-sources2')
372
373     from daklib.dbconn import Component, DBConn, get_suite, Suite, Archive
374     session = DBConn().session()
375     session.execute("SELECT add_missing_description_md5()")
376     session.commit()
377
378     if Options.has_key("Suite"):
379         suites = []
380         for s in suite_names:
381             suite = get_suite(s.lower(), session)
382             if suite:
383                 suites.append(suite)
384             else:
385                 print "I: Cannot find suite %s" % s
386                 logger.log(['Cannot find suite %s' % s])
387     else:
388         query = session.query(Suite).filter(Suite.untouchable == False)
389         if 'Archive' in Options:
390             query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
391         suites = query.all()
392
393     force = Options.has_key("Force") and Options["Force"]
394
395
396     def parse_results(message):
397         # Split out into (code, msg)
398         code, msg = message
399         if code == PROC_STATUS_SUCCESS:
400             logger.log([msg])
401         elif code == PROC_STATUS_SIGNALRAISED:
402             logger.log(['E: Subprocess recieved signal ', msg])
403         else:
404             logger.log(['E: ', msg])
405
406     # Lock tables so that nobody can change things underneath us
407     session.execute("LOCK TABLE src_associations IN SHARE MODE")
408     session.execute("LOCK TABLE bin_associations IN SHARE MODE")
409
410     for s in suites:
411         component_ids = [ c.component_id for c in s.components ]
412         if s.untouchable and not force:
413             import daklib.utils
414             daklib.utils.fubar("Refusing to touch %s (untouchable and not forced)" % s.suite_name)
415         for c in component_ids:
416             pool.apply_async(generate_sources, [s.suite_id, c], callback=parse_results)
417             if not s.include_long_description:
418                 pool.apply_async(generate_translations, [s.suite_id, c], callback=parse_results)
419             for a in s.architectures:
420                 if a == 'source':
421                     continue
422                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'deb'], callback=parse_results)
423                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'udeb'], callback=parse_results)
424
425     pool.close()
426     pool.join()
427
428     # this script doesn't change the database
429     session.close()
430
431     logger.close()
432
433     sys.exit(pool.overall_status())
434
435 if __name__ == '__main__':
436     main()