]> git.decadent.org.uk Git - dak.git/blob - dak/contents.py
Content generation seems to be working now
[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 header_prefix = "%s::Header" % options_prefix
87
88 log = logging.getLogger()
89
90 ################################################################################
91
92 latin1_q = """SET CLIENT_ENCODING TO 'LATIN1'"""
93
94 arches_q = """PREPARE arches_q as
95               SELECT s.architecture, a.arch_string
96               FROM suite_architectures s
97               JOIN architecture a ON (s.architecture=a.id)
98                   WHERE suite = $1"""
99
100 debs_q = """PREPARE debs_q as
101               SELECT b.id, f.filename FROM bin_assoc_by_arch baa
102               JOIN binaries b ON baa.bin=b.id
103               JOIN files f ON b.file=f.id
104               WHERE suite = $1
105                   AND arch = $2"""
106
107 olddeb_q = """PREPARE olddeb_q as
108               SELECT 1 FROM content_associations
109               WHERE binary_pkg = $1
110               LIMIT 1"""
111
112 contents_q = """PREPARE contents_q as
113               SELECT (p.path||'/'||n.file) AS fn,
114                       comma_separated_list(s.section||'/'||b.package)
115               FROM content_associations c
116               JOIN content_file_paths p ON (c.filepath=p.id)
117               JOIN content_file_names n ON (c.filename=n.id)
118               JOIN binaries b ON (b.id=c.binary_pkg)
119               JOIN bin_associations ba ON (b.id=ba.bin)
120               JOIN override o ON (o.package=b.package)
121               JOIN section s ON (s.id=o.section)
122               WHERE (b.architecture = $1 OR b.architecture = $2)
123                   AND ba.suite = $3
124                   AND o.suite = $4
125                   AND b.type = 'deb'
126                   AND o.type = '7'
127               GROUP BY fn
128               ORDER BY fn"""
129
130 udeb_contents_q = """PREPARE udeb_contents_q as
131               SELECT (p.path||'/'||n.file) as fn,
132                       comma_separated_list(s.section||'/'||b.package)
133               FROM content_associations c
134               JOIN content_file_paths p ON (c.filepath=p.id)
135               JOIN content_file_names n ON (c.filename=n.id)
136               JOIN binaries b ON (b.id=c.binary_pkg)
137               JOIN bin_associations ba ON (b.id=ba.bin)
138               JOIN override o ON (o.package=b.package)
139               JOIN section s ON (s.id=o.section)
140               WHERE s.id = $1
141                   AND ba.suite = $2
142                   AND o.suite = $3
143                   AND b.type = 'udeb'
144                   AND o.type = '8'
145               GROUP BY fn
146               ORDER BY fn"""
147
148 class Contents(object):
149     """
150     Class capable of generating Contents-$arch.gz files
151
152     Usage GenerateContents().generateContents( ["main","contrib","non-free"] )
153     """
154
155     def __init__(self):
156         self.header = None
157
158     def _getHeader(self):
159         # Internal method to return the header for Contents.gz files
160         if self.header == None:
161             if Config().has_key("Contents::Header"):
162                 try:
163                     h = open(os.path.join( Config()["Dir::Templates"],
164                                            Config()["Contents::Header"] ), "r")
165                     self.header = h.read()
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                 self.header = False
173
174         return self.header
175
176     # goal column for section column
177     _goal_column = 54
178
179     def _write_content_file(self, cursor, filename):
180         # Internal method for writing all the results to a given file
181         f = gzip.open(Config()["Dir::Root"] + filename, "w")
182         try:
183             header = self._getHeader()
184
185             if header:
186                 f.write(header)
187
188             while True:
189                 contents = cursor.fetchone()
190                 if not contents:
191                     return
192
193                 num_tabs = max(1,
194                                int( math.ceil( (self._goal_column - len(contents[0])) / 8) ) )
195                 f.write(contents[0] + ( '\t' * num_tabs ) + contents[-1] + "\n")
196
197         finally:
198             f.close()
199
200     def cruft(self):
201         """
202         remove files/paths from the DB which are no longer referenced by binaries
203         """
204         cursor = DBConn().cursor();
205         cursor.execute( "BEGIN WORK" )
206         cursor.execute( """DELETE FROM content_file_names
207                            WHERE id IN (SELECT cfn.id FROM content_file_names cfn
208                                         LEFT JOIN content_associations ca
209                                             ON ca.filename=cfn.id
210                                         WHERE ca.id IS NULL)""" );
211         cursor.execute( """DELETE FROM content_file_paths
212                            WHERE id IN (SELECT cfn.id FROM content_file_paths cfn
213                                         LEFT JOIN content_associations ca
214                                             ON ca.filepath=cfn.id
215                                         WHERE ca.id IS NULL)""" );
216         cursor.execute( "COMMIT" )
217
218     def bootstrap(self):
219         """
220         scan the existing debs in the pool to populate the contents database tables
221         """
222         pooldir = Config()[ 'Dir::Pool' ]
223
224         cursor = DBConn().cursor();
225         cursor.execute( latin1_q )
226         cursor.execute( debs_q )
227         cursor.execute( olddeb_q )
228         cursor.execute( arches_q )
229
230         suites = self._suites()
231         for suite in [i.lower() for i in suites]:
232             suite_id = DBConn().get_suite_id(suite)
233
234             arch_list = self._arches(cursor, suite_id)
235             arch_all_id = DBConn().get_architecture_id("all")
236             for arch_id in arch_list:
237                 cursor.execute( "EXECUTE debs_q(%d, %d)" % ( suite_id, arch_id[0] ) )
238
239                 debs = cursor.fetchall()
240                 count = 0
241                 for deb in debs:
242                     count += 1
243                     cursor.execute( "EXECUTE olddeb_q(%d)" % (deb[0] ) )
244                     old = cursor.fetchone()
245                     if old:
246                         log.debug( "already imported: %s" % deb[1] )
247                     else:
248                         debfile = os.path.join( pooldir, deb[1] )
249                         if os.path.exists( debfile ):
250                             contents = utils.generate_contents_information( debfile )
251                             DBConn().insert_content_paths(deb[0], contents)
252                             log.info( "imported (%d/%d): %s" % (count,len(debs),deb[1] ) )
253                         else:
254                             log.error( "missing .deb: %s" % deb[1] )
255
256     def generate(self):
257         """
258         Generate Contents-$arch.gz files for every aviailable arch in each given suite.
259         """
260         cursor = DBConn().cursor();
261
262         cursor.execute( arches_q )
263         cursor.execute( contents_q )
264         cursor.execute( udeb_contents_q )
265
266         suites = self._suites()
267
268         # Get our suites, and the architectures
269         for suite in [i.lower() for i in suites]:
270             suite_id = DBConn().get_suite_id(suite)
271
272             arch_list = self._arches(cursor, suite_id)
273
274             arch_all_id = DBConn().get_architecture_id("all")
275
276             for arch_id in arch_list:
277                 cursor.execute( "EXECUTE contents_q(%d,%d,%d,%d)" % (arch_id[0], arch_all_id, suite_id, suite_id))
278                 self._write_content_file(cursor, "dists/%s/Contents-%s.gz" % (suite, arch_id[1]))
279
280             # The MORE fun part. Ok, udebs need their own contents files, udeb, and udeb-nf (not-free)
281             # This is HORRIBLY debian specific :-/
282             # First off, udeb
283             section_id = DBConn().get_section_id('debian-installer') # all udebs should be here)
284             if section_id != -1:
285                 cursor.execute("EXECUTE udeb_contents_q(%d,%d,%d)" % (section_id, suite_id, suite_id))
286                 self._write_content_file(cursor, "dists/%s/Contents-udeb.gz" % suite)
287
288             # Once more, with non-free
289             section_id = DBConn().get_section_id('non-free/debian-installer') # all udebs should be here)
290
291             if section_id != -1:
292                 cursor.execute("EXECUTE udeb_contents_q(%d,%d,%d)" % (section_id, suite_id, suite_id))
293                 self._write_content_file(cursor, "dists/%s/Contents-udeb-nf.gz" % suite)
294
295
296 ################################################################################
297
298     def _suites(self):
299         # return a list of suites to operate on
300         if Config().has_key( "%s::%s" %(options_prefix,"Suite")):
301             suites = utils.split_args(Config()[ "%s::%s" %(options_prefix,"Suite")])
302         else:
303             suites = Config().SubTree("Suite").List()
304
305         return suites
306
307     def _arches(self, cursor, suite):
308         # return a list of archs to operate on
309         arch_list = [ ]
310         if Config().has_key( "%s::%s" %(options_prefix,"Arch")):
311             archs = utils.split_args(Config()[ "%s::%s" %(options_prefix,"Arch")])
312             for arch_name in archs:
313                 arch_list.append((DBConn().get_architecture_id(arch_name), arch_name))
314         else:
315             cursor.execute("EXECUTE arches_q(%d)" % (suite))
316             while True:
317                 r = cursor.fetchone()
318                 if not r:
319                     break
320
321                 if r[1] != "source" and r[1] != "all":
322                     arch_list.append((r[0], r[1]))
323
324         return arch_list
325
326 ################################################################################
327
328 def main():
329     cnf = Config()
330
331     arguments = [('h',"help", "%s::%s" % (options_prefix,"Help")),
332                  ('s',"suite", "%s::%s" % (options_prefix,"Suite"),"HasArg"),
333                  ('q',"quiet", "%s::%s" % (options_prefix,"Quiet")),
334                  ('v',"verbose", "%s::%s" % (options_prefix,"Verbose")),
335                  ('a',"arch", "%s::%s" % (options_prefix,"Arch"),"HasArg"),
336                 ]
337
338     commands = {'generate' : Contents.generate,
339                 'bootstrap' : Contents.bootstrap,
340                 'cruft' : Contents.cruft,
341                 }
342
343     level=logging.INFO
344     if cnf.has_key("%s::%s" % (options_prefix,"Quiet")):
345         level=logging.ERROR
346
347     elif cnf.has_key("%s::%s" % (options_prefix,"Verbose")):
348         level=logging.DEBUG
349
350
351     logging.basicConfig( level=logging.DEBUG,
352                          format='%(asctime)s %(levelname)s %(message)s',
353                          stream = sys.stderr )
354
355     args = apt_pkg.ParseCommandLine(cnf.Cnf, arguments,sys.argv)
356
357     if (len(args) < 1) or not commands.has_key(args[0]):
358         usage()
359
360     if cnf.has_key("%s::%s" % (options_prefix,"Help")):
361         usage()
362
363     commands[args[0]](Contents())
364
365 if __name__ == '__main__':
366     main()