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