]> git.decadent.org.uk Git - dak.git/blob - dak/contents.py
oops, forgot some changes to contents.py
[dak.git] / dak / contents.py
1 #!/usr/bin/env python
2 """
3 Create all the contents files
4
5 @contact: Debian FTPMaster <ftpmaster@debian.org>
6 @copyright: 2008, 2009 Michael Casadevall <mcasadevall@debian.org>
7 @copyright: 2009 Mike O'Connor <stew@debian.org>
8 @license: GNU General Public License version 2 or later
9 """
10
11 ################################################################################
12
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
17
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
22
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
27 ################################################################################
28
29 # <Ganneff> there is the idea to slowly replace contents files
30 # <Ganneff> with a new generation of such files.
31 # <Ganneff> having more info.
32
33 # <Ganneff> of course that wont help for now where we need to generate them :)
34
35 ################################################################################
36
37 import sys
38 import os
39 import tempfile
40 import logging
41 import math
42 import gzip
43 import apt_pkg
44 from daklib import utils
45 from daklib.config import Config
46 from daklib.dbconn import DBConn
47 ################################################################################
48
49 def usage (exit_code=0):
50     print """Usage: dak contents [options] command [arguments]
51
52 COMMANDS
53     generate
54         generate Contents-$arch.gz files
55
56     bootstrap
57         scan the debs in the existing pool and load contents in the the database
58
59     cruft
60         remove files/paths which are no longer referenced by a binary
61
62 OPTIONS
63      -h, --help
64         show this help and exit
65
66      -v, --verbose
67         show verbose information messages
68
69      -q, --quiet
70         supress all output but errors
71
72      -s, --suite={stable,testing,unstable,...}
73         only operate on a signle suite
74
75      -a, --arch={i386,amd64}
76         only operate on a signle architecture
77 """
78     sys.exit(exit_code)
79
80 ################################################################################
81
82 # where in dak.conf all of our configuration will be stowed
83
84 options_prefix = "Contents"
85 options_prefix = "%s::Opitons" % options_prefix
86
87 log = logging.getLogger()
88
89 ################################################################################
90
91 latin1_q = """SET CLIENT_ENCODING TO 'LATIN1'"""
92
93 arches_q = """PREPARE arches_q as
94               SELECT s.architecture, a.arch_string
95               FROM suite_architectures s
96               JOIN architecture a ON (s.architecture=a.id)
97                   WHERE suite = $1"""
98
99 debs_q = """PREPARE debs_q as
100               SELECT b.id, f.filename FROM bin_assoc_by_arch baa
101               JOIN binaries b ON baa.bin=b.id
102               JOIN files f ON b.file=f.id
103               WHERE suite = $1
104                   AND arch = $2"""
105
106 olddeb_q = """PREPARE olddeb_q as
107               SELECT 1 FROM content_associations
108               WHERE binary_pkg = $1
109               LIMIT 1"""
110
111 contents_q = """PREPARE contents_q as
112               SELECT (p.path||'/'||n.file) AS fn,
113                       comma_separated_list(s.section||'/'||b.package)
114               FROM content_associations c
115               JOIN content_file_paths p ON (c.filepath=p.id)
116               JOIN content_file_names n ON (c.filename=n.id)
117               JOIN binaries b ON (b.id=c.binary_pkg)
118               JOIN bin_associations ba ON (b.id=ba.bin)
119               JOIN override o ON (o.package=b.package)
120               JOIN section s ON (s.id=o.section)
121               WHERE (b.architecture = $1 OR b.architecture = $2)
122                   AND ba.suite = $3
123                   AND o.suite = $4
124                   AND b.type = 'deb'
125                   AND o.type = '7'
126               GROUP BY fn
127               ORDER BY fn"""
128
129 udeb_contents_q = """PREPARE udeb_contents_q as
130               SELECT (p.path||'/'||n.file) as fn,
131                       comma_separated_list(s.section||'/'||b.package)
132               FROM content_associations c
133               JOIN content_file_paths p ON (c.filepath=p.id)
134               JOIN content_file_names n ON (c.filename=n.id)
135               JOIN binaries b ON (b.id=c.binary_pkg)
136               JOIN bin_associations ba ON (b.id=ba.bin)
137               JOIN override o ON (o.package=b.package)
138               JOIN section s ON (s.id=o.section)
139               WHERE s.id = $1
140                   AND ba.suite = $2
141                   AND o.suite = $3
142                   AND b.type = 'udeb'
143                   AND o.type = '8'
144               GROUP BY fn
145               ORDER BY fn"""
146
147 class Contents(object):
148     """
149     Class capable of generating Contents-$arch.gz files
150
151     Usage GenerateContents().generateContents( ["main","contrib","non-free"] )
152     """
153
154     def __init__(self):
155         self.header = None
156
157     def _getHeader(self):
158         # Internal method to return the header for Contents.gz files
159         if self.header == None:
160             if Config().has_key("Contents::Header"):
161                 try:
162                     h = open(os.path.join( Config()["Dir::Templates"],
163                                            Config()["Contents::Header"] ), "r")
164                     self.header = h.read()
165                     print( "header: %s" % self.header )
166                     h.close()
167                 except:
168                     log.error( "error openeing header file: %d\n%s" % (Config()["Contents::Header"],
169                                                                        traceback.format_exc() ))
170                     self.header = False
171             else:
172                 print( "no header" )
173                 self.header = False
174
175         return self.header
176
177     # goal column for section column
178     _goal_column = 54
179
180     def _write_content_file(self, cursor, filename):
181         # Internal method for writing all the results to a given file
182         f = gzip.open(Config()["Dir::Root"] + filename, "w")
183         try:
184             header = self._getHeader()
185
186             if header:
187                 f.write(header)
188
189             while True:
190                 contents = cursor.fetchone()
191                 if not contents:
192                     return
193
194                 num_tabs = max(1,
195                                int( math.ceil( (self._goal_column - len(contents[0])) / 8) ) )
196                 f.write(contents[0] + ( '\t' * num_tabs ) + contents[-1] + "\n")
197
198         finally:
199             f.close()
200
201     def cruft(self):
202         """
203         remove files/paths from the DB which are no longer referenced by binaries
204         """
205         cursor = DBConn().cursor();
206         cursor.execute( "BEGIN WORK" )
207         cursor.execute( """DELETE FROM content_file_names
208                            WHERE id IN (SELECT cfn.id FROM content_file_names cfn
209                                         LEFT JOIN content_associations ca
210                                             ON ca.filename=cfn.id
211                                         WHERE ca.id IS NULL)""" );
212         cursor.execute( """DELETE FROM content_file_paths
213                            WHERE id IN (SELECT cfn.id FROM content_file_paths cfn
214                                         LEFT JOIN content_associations ca
215                                             ON ca.filepath=cfn.id
216                                         WHERE ca.id IS NULL)""" );
217         cursor.execute( "COMMIT" )
218
219
220     def bootstrap(self):
221         """
222         scan the existing debs in the pool to populate the contents database tables
223         """
224         pooldir = Config()[ 'Dir::Pool' ]
225
226         cursor = DBConn().cursor();
227         cursor.execute( latin1_q )
228         cursor.execute( debs_q )
229         cursor.execute( olddeb_q )
230         cursor.execute( arches_q )
231
232         suites = self._suites()
233         for suite in [i.lower() for i in suites]:
234             suite_id = DBConn().get_suite_id(suite)
235
236             arch_list = self._arches(cursor, suite_id)
237             arch_all_id = DBConn().get_architecture_id("all")
238             for arch_id in arch_list:
239                 cursor.execute( "EXECUTE debs_q(%d, %d)" % ( suite_id, arch_id[0] ) )
240
241                 debs = cursor.fetchall()
242                 count = 0
243                 for deb in debs:
244                     count += 1
245                     cursor.execute( "EXECUTE olddeb_q(%d)" % (deb[0] ) )
246                     old = cursor.fetchone()
247                     if old:
248                         log.debug( "already imported: %s" % deb[1] )
249                     else:
250                         debfile = os.path.join( pooldir, deb[1] )
251                         if os.path.exists( debfile ):
252                             contents = utils.generate_contents_information( debfile )
253                             DBConn().insert_content_paths(deb[0], contents)
254                             log.info( "imported (%d/%d): %s" % (count,len(debs),deb[1] ) )
255                         else:
256                             log.error( "missing .deb: %s" % deb[1] )
257
258     def generate(self):
259         """
260         Generate Contents-$arch.gz files for every aviailable arch in each given suite.
261         """
262         cursor = DBConn().cursor();
263
264         cursor.execute( arches_q )
265         cursor.execute( contents_q )
266         cursor.execute( udeb_contents_q )
267
268         suites = self._suites()
269
270         # Get our suites, and the architectures
271         for suite in [i.lower() for i in suites]:
272             suite_id = DBConn().get_suite_id(suite)
273             arch_list = self._arches(cursor, suite_id)
274
275             arch_all_id = DBConn().get_architecture_id("all")
276
277             for arch_id in arch_list:
278                 cursor.execute( "EXECUTE contents_q(%d,%d,%d,%d)" % (arch_id[0], arch_all_id, suite_id, suite_id))
279                 self._write_content_file(cursor, "dists/%s/Contents-%s.gz" % (suite, arch_id[1]))
280
281             # The MORE fun part. Ok, udebs need their own contents files, udeb, and udeb-nf (not-free)
282             # This is HORRIBLY debian specific :-/
283             # First off, udeb
284             section_id = DBConn().get_section_id('debian-installer') # all udebs should be here)
285             if section_id != -1:
286                 cursor.execute("EXECUTE udeb_contents_q(%d,%d,%d)" % (section_id, suite_id, suite_id))
287                 self._write_content_file(cursor, "dists/%s/Contents-udeb.gz" % suite)
288
289             # Once more, with non-free
290             section_id = DBConn().get_section_id('non-free/debian-installer') # all udebs should be here)
291
292             if section_id != -1:
293                 cursor.execute("EXECUTE udeb_contents_q(%d,%d,%d)" % (section_id, suite_id, suite_id))
294                 self._write_content_file(cursor, "dists/%s/Contents-udeb-nf.gz" % suite)
295
296
297 ################################################################################
298
299     def _suites(self):
300         # return a list of suites to operate on
301         if Config().has_key( "%s::%s" %(options_prefix,"Suite")):
302             suites = utils.split_args(Config()[ "%s::%s" %(options_prefix,"Suite")])
303         else:
304             suites = Config().SubTree("Suite").List()
305
306         return suites
307
308     def _arches(self, cursor, suite):
309         # return a list of archs to operate on
310         arch_list = [ ]
311         if Config().has_key( "%s::%s" %(options_prefix,"Arch")):
312             archs = utils.split_args(Config()[ "%s::%s" %(options_prefix,"Arch")])
313             for arch_name in archs:
314                 arch_list.append((DBConn().get_architecture_id(arch_name), arch_name))
315         else:
316             cursor.execute("EXECUTE arches_q(%d)" % (suite))
317             while True:
318                 r = cursor.fetchone()
319                 if not r:
320                     break
321
322                 if r[1] != "source" and r[1] != "all":
323                     arch_list.append((r[0], r[1]))
324
325         return arch_list
326
327 ################################################################################
328
329 def main():
330     cnf = Config()
331
332     arguments = [('h',"help", "%s::%s" % (options_prefix,"Help")),
333                  ('s',"suite", "%s::%s" % (options_prefix,"Suite"),"HasArg"),
334                  ('q',"quiet", "%s::%s" % (options_prefix,"Quiet")),
335                  ('v',"verbose", "%s::%s" % (options_prefix,"Verbose")),
336                  ('a',"arch", "%s::%s" % (options_prefix,"Arch"),"HasArg"),
337                 ]
338
339     commands = {'generate' : Contents.generate,
340                 'bootstrap' : Contents.bootstrap,
341                 'cruft' : Contents.cruft,
342                 }
343
344     level=logging.INFO
345     if cnf.has_key("%s::%s" % (options_prefix,"Quiet")):
346         level=logging.ERROR
347
348     elif cnf.has_key("%s::%s" % (options_prefix,"Verbose")):
349         level=logging.DEBUG
350
351
352     logging.basicConfig( level=logging.DEBUG,
353                          format='%(asctime)s %(levelname)s %(message)s',
354                          stream = sys.stderr )
355
356     args = apt_pkg.ParseCommandLine(cnf.Cnf, arguments,sys.argv)
357
358     if (len(args) < 1) or not commands.has_key(args[0]):
359         usage()
360
361     if cnf.has_key("%s::%s" % (options_prefix,"Help")):
362         usage()
363
364     commands[args[0]](Contents())
365
366 if __name__ == '__main__':
367     main()