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