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