3 Create all the contents files
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
11 ################################################################################
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.
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.
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
27 ################################################################################
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.
33 # <Ganneff> of course that wont help for now where we need to generate them :)
35 ################################################################################
47 from daklib import utils
48 from daklib.binary import Binary
49 from daklib.config import Config
50 from daklib.dbconn import *
51 from daklib.contents import ContentsScanner
52 from daklib import daklog
56 ################################################################################
58 def usage (exit_code=0):
59 print """Usage: dak contents [options] command [arguments]
63 generate Contents-$arch.gz files
66 scan the debs in the existing pool and load contents into the bin_contents table
69 copy data from the bin_contents table into the deb_contents / udeb_contents tables
72 remove files/paths which are no longer referenced by a binary
76 show this help and exit
79 show verbose information messages
82 supress all output but errors
84 -s, --suite={stable,testing,unstable,...}
85 only operate on a single suite
88 optional package limit for bootstrap_bin
92 ################################################################################
94 # where in dak.conf all of our configuration will be stowed
96 options_prefix = "Contents"
97 options_prefix = "%s::Options" % options_prefix
99 log = logging.getLogger()
101 ################################################################################
103 class EndOfContents(object):
105 A sentry object for the end of the filename stream
109 class OneAtATime(object):
111 a one space queue which sits between multiple possible producers
112 and multiple possible consumers
115 self.next_in_line = None
116 self.read_lock = threading.Condition()
117 self.write_lock = threading.Condition()
120 def enqueue(self, next):
121 self.write_lock.acquire()
122 while self.next_in_line:
125 self.write_lock.wait()
127 assert( not self.next_in_line )
128 self.next_in_line = next
129 self.write_lock.release()
130 self.read_lock.acquire()
131 self.read_lock.notify()
132 self.read_lock.release()
135 self.read_lock.acquire()
136 while not self.next_in_line:
139 self.read_lock.wait()
141 result = self.next_in_line
143 self.next_in_line = None
144 self.read_lock.release()
145 self.write_lock.acquire()
146 self.write_lock.notify()
147 self.write_lock.release()
152 class ContentsWorkThread(threading.Thread):
155 def __init__(self, upstream, downstream):
156 threading.Thread.__init__(self)
157 self.upstream = upstream
158 self.downstream = downstream
163 contents_file = self.upstream.dequeue()
164 if isinstance(contents_file,EndOfContents):
166 self.downstream.enqueue(contents_file)
169 s = datetime.datetime.now()
170 print("%s start: %s" % (self,contents_file) )
171 self._run(contents_file)
172 print("%s finished: %s in %d seconds" % (self, contents_file, (datetime.datetime.now()-s).seconds ))
174 self.downstream.enqueue(contents_file)
176 traceback.print_exc()
178 class QueryThread(ContentsWorkThread):
179 def __init__(self, upstream, downstream):
180 ContentsWorkThread.__init__(self, upstream, downstream)
186 def _run(self, contents_file):
187 contents_file.query()
189 class IngestThread(ContentsWorkThread):
190 def __init__(self, upstream, downstream):
191 ContentsWorkThread.__init__(self, upstream, downstream)
194 return "IngestThread"
197 def _run(self, contents_file):
198 contents_file.ingest()
200 class SortThread(ContentsWorkThread):
201 def __init__(self, upstream, downstream):
202 ContentsWorkThread.__init__(self, upstream, downstream)
208 def _run(self, contents_file):
209 contents_file.sorted_keys = sorted(contents_file.filenames.keys())
211 class OutputThread(ContentsWorkThread):
212 def __init__(self, upstream, downstream):
213 ContentsWorkThread.__init__(self, upstream, downstream)
216 return "OutputThread"
219 def _run(self, contents_file):
220 contents_file.open_file()
221 for fname in contents_file.sorted_keys:
222 contents_file.filehandle.write("%s\t%s\n" % (fname,contents_file.filenames[fname]))
223 contents_file.sorted_keys = None
224 contents_file.filenames.clear()
226 class GzipThread(ContentsWorkThread):
227 def __init__(self, upstream, downstream):
228 ContentsWorkThread.__init__(self, upstream, downstream)
234 def _run(self, contents_file):
235 os.system("gzip -f %s" % contents_file.filename)
237 class ContentFile(object):
243 self.filename = filename
245 self.sorted_keys = None
246 self.suite_str = suite_str
247 self.suite_id = suite_id
249 self.filehandle = None
258 self.filenames = None
259 self.sortedkeys = None
260 self.filehandle.close()
265 r = self.results.fetchone()
268 filename, package = r
269 self.filenames[filename]=package
275 opens a gzip stream to the contents file
277 filepath = Config()["Contents::Root"] + self.filename
278 filedir = os.path.dirname(self.filename)
279 if not os.path.isdir(filedir):
281 self.filehandle = open(self.filename, "w")
284 def _write_header(self):
286 self.filehandle.write(ContentFile.header)
291 def _get_header(self):
293 Internal method to return the header for Contents.gz files
295 This is boilerplate which explains the contents of the file and how
298 if not ContentFile.header:
299 if Config().has_key("Contents::Header"):
301 h = open(os.path.join( Config()["Dir::Templates"],
302 Config()["Contents::Header"] ), "r")
303 ContentFile.header = h.read()
306 log.error( "error opening header file: %d\n%s" % (Config()["Contents::Header"],
307 traceback.format_exc() ))
308 ContentFile.header = None
310 ContentFile.header = None
312 return ContentFile.header
315 class DebContentFile(ContentFile):
322 ContentFile.__init__(self,
326 self.arch_str = arch_str
327 self.arch_id = arch_id
330 self.session = DBConn().session();
332 self.results = self.session.execute("""SELECT filename, comma_separated_list(section || '/' || package)
334 WHERE ( arch=2 or arch = :arch) AND suite = :suite
335 """, { 'arch':self.arch_id, 'suite':self.suite_id } )
337 class UdebContentFile(ContentFile):
344 ContentFile.__init__(self,
350 self.session = DBConn().session();
352 self.results = self.session.execute("""SELECT filename, comma_separated_list(section || '/' || package)
356 """ , { 'suite': self.suite_id } )
358 class Contents(object):
360 Class capable of generating Contents-$arch.gz files
365 def reject(self, message):
366 log.error("E: %s" % message)
370 remove files/paths from the DB which are no longer referenced
371 by binaries and clean the temporary table
373 s = DBConn().session()
375 # clear out all of the temporarily stored content associations
376 # this should be run only after p-a has run. after a p-a
377 # run we should have either accepted or rejected every package
378 # so there should no longer be anything in the queue
379 s.query(PendingContentAssociation).delete()
381 # delete any filenames we are storing which have no binary associated
383 cafq = s.query(ContentAssociation.filename_id).distinct()
384 cfq = s.query(ContentFilename)
385 cfq = cfq.filter(~ContentFilename.cafilename_id.in_(cafq))
388 # delete any paths we are storing which have no binary associated with
390 capq = s.query(ContentAssociation.filepath_id).distinct()
391 cpq = s.query(ContentFilepath)
392 cpq = cpq.filter(~ContentFilepath.cafilepath_id.in_(capq))
398 def bootstrap_bin(self):
400 scan the existing debs in the pool to populate the bin_contents table
402 pooldir = Config()[ 'Dir::Pool' ]
404 s = DBConn().session()
406 for binary in s.query(DBBinary).yield_per(100):
407 print( "binary: %s" % binary.package )
408 filename = binary.poolfile.filename
409 # Check for existing contents
410 existingq = s.execute( "select 1 from bin_contents where binary_id=:id", {'id':binary.binary_id} );
411 if existingq.fetchone():
412 log.debug( "already imported: %s" % (filename))
414 # We don't have existing contents so import them
415 log.debug( "scanning: %s" % (filename) )
417 debfile = os.path.join(pooldir, filename)
418 if os.path.exists(debfile):
419 Binary(debfile, self.reject).scan_package(binary.binary_id, True)
421 log.error("missing .deb: %s" % filename)
427 scan the existing debs in the pool to populate the contents database tables
429 s = DBConn().session()
432 # get a mapping of all the override types we care about (right now .deb an .udeb)
433 override_type_map = {};
434 for override_type in s.query(OverrideType).all():
435 if override_type.overridetype.endswith('deb' ):
436 override_type_map[override_type.overridetype_id] = override_type.overridetype;
438 for override in s.query(Override).yield_per(100):
439 if not override_type_map.has_key(override.overridetype_id):
440 #this isn't an override we care about
443 binaries = s.execute("""SELECT b.id, b.architecture
445 JOIN bin_associations ba ON ba.bin=b.id
446 WHERE ba.suite=:suite
447 AND b.package=:package""", {'suite':override.suite_id, 'package':override.package})
449 binary = binaries.fetchone()
453 exists = s.execute("SELECT 1 FROM %s_contents WHERE binary_id=:id limit 1" % override_type_map[override.overridetype_id], {'id':binary.id})
456 if exists.fetchone():
462 s.execute( """INSERT INTO %s_contents (filename,section,package,binary_id,arch,suite)
463 SELECT file, :section, :package, :binary_id, :arch, :suite
465 WHERE binary_id=:binary_id;""" % override_type_map[override.overridetype_id],
466 { 'section' : override.section_id,
467 'package' : override.package,
468 'binary_id' : binary.id,
469 'arch' : binary.architecture,
470 'suite' : override.suite_id } )
475 Generate contents files for both deb and udeb
480 def deb_generate(self):
482 Generate Contents-$arch.gz files for every available arch in each given suite.
484 session = DBConn().session()
485 debtype_id = get_override_type("deb", session)
486 suites = self._suites()
488 inputtoquery = OneAtATime()
489 querytoingest = OneAtATime()
490 ingesttosort = OneAtATime()
491 sorttooutput = OneAtATime()
492 outputtogzip = OneAtATime()
494 qt = QueryThread(inputtoquery,querytoingest)
495 it = IngestThread(querytoingest,ingesttosort)
496 st = SortThread(ingesttosort,sorttooutput)
497 ot = OutputThread(sorttooutput,outputtogzip)
498 gt = GzipThread(outputtogzip, None)
506 # Get our suites, and the architectures
507 for suite in [i.lower() for i in suites]:
508 suite_id = get_suite(suite, session).suite_id
509 print( "got suite_id: %s for suite: %s" % (suite_id, suite ) )
510 arch_list = self._arches(suite_id, session)
512 for (arch_id,arch_str) in arch_list:
513 print( "suite: %s, arch: %s time: %s" %(suite_id, arch_id, datetime.datetime.now().isoformat()) )
515 filename = "dists/%s/Contents-%s" % (suite, arch_str)
516 cf = DebContentFile(filename, suite, suite_id, arch_str, arch_id)
517 inputtoquery.enqueue( cf )
519 inputtoquery.enqueue( EndOfContents() )
522 def udeb_generate(self):
524 Generate Contents-$arch.gz files for every available arch in each given suite.
526 session = DBConn().session()
527 udebtype_id=DBConn().get_override_type_id("udeb")
528 suites = self._suites()
530 inputtoquery = OneAtATime()
531 querytoingest = OneAtATime()
532 ingesttosort = OneAtATime()
533 sorttooutput = OneAtATime()
534 outputtogzip = OneAtATime()
536 qt = QueryThread(inputtoquery,querytoingest)
537 it = IngestThread(querytoingest,ingesttosort)
538 st = SortThread(ingesttosort,sorttooutput)
539 ot = OutputThread(sorttooutput,outputtogzip)
540 gt = GzipThread(outputtogzip, None)
551 Generate Contents-$arch.gz files for every available arch in each given suite.
553 session = DBConn().session()
555 arch_all_id = get_architecture("all", session).arch_id
557 # The MORE fun part. Ok, udebs need their own contents files, udeb, and udeb-nf (not-free)
558 # This is HORRIBLY debian specific :-/
559 for dtype, section, fn_pattern in \
560 [('deb', None, "dists/%s/Contents-%s.gz"),
561 ('udeb', "debian-installer", "dists/%s/Contents-udeb-%s.gz"),
562 ('udeb', "non-free/debian-installer", "dists/%s/Contents-udeb-nf-%s.gz")]:
564 overridetype = get_override_type(dtype, session)
566 # For udebs, we only look in certain sections (see the for loop above)
567 if section is not None:
568 section = get_section(section, session)
571 for suite in which_suites(session):
572 # Which architectures do we need to work on
573 arch_list = get_suite_architectures(suite.suite_name, skipsrc=True, skipall=True, session=session)
575 # Set up our file writer dictionary
578 # One file writer per arch
579 for arch in arch_list:
580 file_writers[arch.arch_id] = GzippedContentWriter(fn_pattern % (suite, arch.arch_string))
582 for r in get_suite_contents(suite, overridetype, section, session=session).fetchall():
583 filename, section, package, arch_id = r
585 if arch_id == arch_all_id:
586 # It's arch all, so all contents files get it
587 for writer in file_writers.values():
588 writer.write(filename, section, package)
590 if file_writers.has_key(arch_id):
591 file_writers[arch_id].write(filename, section, package)
594 # close all the files
595 for writer in file_writers.values():
599 return a list of suites to operate on
601 if Config().has_key( "%s::%s" %(options_prefix,"Suite")):
602 suites = utils.split_args(Config()[ "%s::%s" %(options_prefix,"Suite")])
604 suites = Config().SubTree("Suite").List()
608 def _arches(self, suite, session):
610 return a list of archs to operate on
613 arches = session.execute(
614 """SELECT s.architecture, a.arch_string
615 FROM suite_architectures s
616 JOIN architecture a ON (s.architecture=a.id)
617 WHERE suite = :suite_id""",
618 {'suite_id':suite } )
621 r = arches.fetchone()
625 if r[1] != "source" and r[1] != "all":
626 arch_list.append((r[0], r[1]))
632 result = ContentsScanner.scan_all(limit)
633 processed = '%(processed)d packages processed' % result
634 remaining = '%(remaining)d packages remaining' % result
635 Logger.log([processed, remaining])
637 ################################################################################
642 arguments = [('h',"help", "%s::%s" % (options_prefix,"Help")),
643 ('s',"suite", "%s::%s" % (options_prefix,"Suite"),"HasArg"),
644 ('l',"limit", "%s::%s" % (options_prefix,"Limit"),"HasArg"),
645 ('q',"quiet", "%s::%s" % (options_prefix,"Quiet")),
646 ('v',"verbose", "%s::%s" % (options_prefix,"Verbose")),
649 commands = {'generate' : Contents.generate,
650 'bootstrap_bin' : Contents.bootstrap_bin,
651 'bootstrap' : Contents.bootstrap,
652 'cruft' : Contents.cruft,
655 args = apt_pkg.ParseCommandLine(cnf.Cnf, arguments,sys.argv)
657 if (len(args) < 1) or not commands.has_key(args[0]):
660 if cnf.has_key("%s::%s" % (options_prefix,"Help")):
664 if cnf.has_key("%s::%s" % (options_prefix,"Quiet")):
667 elif cnf.has_key("%s::%s" % (options_prefix,"Verbose")):
671 logging.basicConfig( level=level,
672 format='%(asctime)s %(levelname)s %(message)s',
673 stream = sys.stderr )
676 Logger = daklog.Logger(cnf.Cnf, 'contents')
679 if cnf.has_key("%s::%s" % (options_prefix,"Limit")):
680 limit = cnf["%s::%s" % (options_prefix,"Limit")]
682 if args[0] == 'bootstrap_bin':
685 commands[args[0]](Contents())
689 def which_suites(session):
691 return a list of suites to operate on
693 if Config().has_key( "%s::%s" %(options_prefix,"Suite")):
694 suites = utils.split_args(Config()[ "%s::%s" %(options_prefix,"Suite")])
696 suites = Config().SubTree("Suite").List()
698 return [get_suite(s.lower(), session) for s in suites]
701 if __name__ == '__main__':