2 # Copyright 2009-2010 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
5 from __future__ import print_function
8 # This block ensures that ^C interrupts are handled quietly.
12 def exithandler(signum,frame):
13 signal.signal(signal.SIGINT, signal.SIG_IGN)
14 signal.signal(signal.SIGTERM, signal.SIG_IGN)
17 signal.signal(signal.SIGINT, exithandler)
18 signal.signal(signal.SIGTERM, exithandler)
20 except KeyboardInterrupt:
29 from os import path as osp
30 sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
33 from portage import os
34 from _emerge.MetadataRegen import MetadataRegen
35 from portage.cache.cache_errors import CacheError, StatCollision
36 from portage.util import writemsg_level
37 from portage import cpv_getkey
38 from portage.dep import isjustname
41 import xml.etree.ElementTree
45 from repoman.utilities import parse_metadata_use
46 from xml.parsers.expat import ExpatError
48 if sys.hexversion >= 0x3000000:
52 usage = "egencache [options] <action> ... [atom] ..."
53 parser = optparse.OptionParser(usage=usage)
55 actions = optparse.OptionGroup(parser, 'Actions')
56 actions.add_option("--update",
58 help="update metadata/cache/ (generate as necessary)")
59 actions.add_option("--update-use-local-desc",
61 help="update the use.local.desc file from metadata.xml")
62 parser.add_option_group(actions)
64 common = optparse.OptionGroup(parser, 'Common options')
65 common.add_option("--repo",
67 help="name of repo to operate on (default repo is located at $PORTDIR)")
68 common.add_option("--config-root",
69 help="location of portage config files",
70 dest="portage_configroot")
71 common.add_option("--portdir",
72 help="override the portage tree location",
74 common.add_option("--tolerant",
76 help="exit successfully if only minor errors occurred")
77 common.add_option("--ignore-default-opts",
79 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
80 parser.add_option_group(common)
82 update = optparse.OptionGroup(parser, '--update options')
83 update.add_option("--cache-dir",
84 help="location of the metadata cache",
86 update.add_option("--jobs",
88 help="max ebuild processes to spawn")
89 update.add_option("--load-average",
91 help="max load allowed when spawning multiple jobs",
93 update.add_option("--rsync",
95 help="enable rsync stat collision workaround " + \
96 "for bug 139134 (use with --update)")
97 parser.add_option_group(update)
99 options, args = parser.parse_args(args)
104 jobs = int(options.jobs)
109 parser.error("Invalid: --jobs='%s'" % \
117 if options.load_average:
119 load_average = float(options.load_average)
123 if load_average <= 0.0:
124 parser.error("Invalid: --load-average='%s'" % \
125 (options.load_average,))
127 options.load_average = load_average
130 options.load_average = None
132 options.config_root = options.portage_configroot
133 if options.config_root is not None and \
134 not os.path.isdir(options.config_root):
135 parser.error("Not a directory: --config-root='%s'" % \
136 (options.config_root,))
138 if options.cache_dir is not None and not os.path.isdir(options.cache_dir):
139 parser.error("Not a directory: --cache-dir='%s'" % \
140 (options.cache_dir,))
144 atom = portage.dep.Atom(atom)
145 except portage.exception.InvalidAtom:
146 parser.error('Invalid atom: %s' % (atom,))
148 if not isjustname(atom):
149 parser.error('Atom is too specific: %s' % (atom,))
151 if options.update_use_local_desc:
153 xml.etree.ElementTree
155 parser.error('--update-use-local-desc requires python with USE=xml!')
157 return parser, options, args
159 class GenCache(object):
160 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
162 self._portdb = portdb
163 # We can globally cleanse stale cache only if we
164 # iterate over every single cp.
165 self._global_cleanse = cp_iter is None
166 if cp_iter is not None:
167 self._cp_set = set(cp_iter)
168 cp_iter = iter(self._cp_set)
169 self._cp_missing = self._cp_set.copy()
172 self._cp_missing = set()
173 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
174 consumer=self._metadata_callback,
175 max_jobs=max_jobs, max_load=max_load)
176 self.returncode = os.EX_OK
177 metadbmodule = portdb.settings.load_best_module("portdbapi.metadbmodule")
178 self._trg_cache = metadbmodule(portdb.porttrees[0],
179 "metadata/cache", portage.auxdbkeys[:])
181 self._trg_cache.raise_stat_collision = True
183 self._trg_cache.ec = \
184 portdb._repo_info[portdb.porttrees[0]].eclass_db
185 except AttributeError:
187 self._existing_nodes = set()
189 def _metadata_callback(self, cpv, ebuild_path, repo_path, metadata):
190 self._existing_nodes.add(cpv)
191 self._cp_missing.discard(cpv_getkey(cpv))
192 if metadata is not None:
193 if metadata.get('EAPI') == '0':
197 self._trg_cache[cpv] = metadata
198 except StatCollision as sc:
199 # If the content of a cache entry changes and neither the
200 # file mtime nor size changes, it will prevent rsync from
201 # detecting changes. Cache backends may raise this
202 # exception from _setitem() if they detect this type of stat
203 # collision. These exceptions are handled by bumping the
204 # mtime on the ebuild (and the corresponding cache entry).
207 for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
208 if max_mtime < ec_mtime:
210 if max_mtime == sc.mtime:
212 max_mtime = long(max_mtime)
214 os.utime(ebuild_path, (max_mtime, max_mtime))
218 "%s writing target: %s\n" % (cpv, e),
219 level=logging.ERROR, noiselevel=-1)
221 metadata['_mtime_'] = max_mtime
222 self._trg_cache[cpv] = metadata
223 self._portdb.auxdb[repo_path][cpv] = metadata
225 except CacheError as ce:
228 "%s writing target: %s\n" % (cpv, ce),
229 level=logging.ERROR, noiselevel=-1)
233 self.returncode |= self._regen.returncode
234 cp_missing = self._cp_missing
236 trg_cache = self._trg_cache
238 if self._global_cleanse:
240 for cpv in trg_cache:
245 "Unable to parse cp for '%s'\n" % (cpv,),
246 level=logging.ERROR, noiselevel=-1)
249 except CacheError as ce:
252 "Error listing cache entries for " + \
253 "'%s/metadata/cache': %s, continuing...\n" % \
254 (self._portdb.porttree_root, ce),
255 level=logging.ERROR, noiselevel=-1)
258 cp_set = self._cp_set
260 for cpv in trg_cache:
265 "Unable to parse cp for '%s'\n" % (cpv,),
266 level=logging.ERROR, noiselevel=-1)
268 cp_missing.discard(cp)
271 except CacheError as ce:
274 "Error listing cache entries for " + \
275 "'%s/metadata/cache': %s, continuing...\n" % \
276 (self._portdb.porttree_root, ce),
277 level=logging.ERROR, noiselevel=-1)
281 for cp in sorted(cp_missing):
283 "No ebuilds or cache entries found for '%s'\n" % (cp,),
284 level=logging.ERROR, noiselevel=-1)
287 dead_nodes.difference_update(self._existing_nodes)
293 except CacheError as ce:
296 "%s deleting stale cache: %s\n" % (k, ce),
297 level=logging.ERROR, noiselevel=-1)
299 if not trg_cache.autocommits:
302 except CacheError as ce:
305 "committing target: %s\n" % (ce,),
306 level=logging.ERROR, noiselevel=-1)
308 class GenUseLocalDesc(object):
309 def __init__(self, portdb):
310 self.returncode = os.EX_OK
311 self._portdb = portdb
314 repo_path = self._portdb.porttrees[0]
315 prof_path = os.path.join(repo_path, 'profiles')
316 desc_path = os.path.join(prof_path, 'use.local.desc')
323 output = open(desc_path, 'w')
326 "ERROR: failed to open output file: %s\n" % (e,),
327 level=logging.ERROR, noiselevel=-1)
332 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
333 # your descriptions to your package's metadata.xml ONLY.
334 # * generated automatically using egencache *
338 for cp in self._portdb.cp_all():
339 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
341 metadata = xml.etree.ElementTree.parse(metadata_path)
344 except (ExpatError, EnvironmentError) as e:
346 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
347 level=logging.ERROR, noiselevel=-1)
351 usedict = parse_metadata_use(metadata)
352 except portage.exception.ParseError as e:
354 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
355 level=logging.ERROR, noiselevel=-1)
358 for flag in sorted(usedict.keys()):
359 output.write('%s:%s - %s\n' % (cp, flag, usedict[flag]))
363 def egencache_main(args):
364 parser, options, atoms = parse_args(args)
366 config_root = options.config_root
367 if config_root is None:
370 # The calling environment is ignored, so the program is
371 # completely controlled by commandline arguments.
374 if options.repo is None:
375 env['PORTDIR_OVERLAY'] = ''
377 if options.cache_dir is not None:
378 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
380 if options.portdir is not None:
381 env['PORTDIR'] = options.portdir
383 settings = portage.config(config_root=config_root,
384 target_root='/', local_config=False, env=env)
387 if not options.ignore_default_opts:
388 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
391 parser, options, args = parse_args(default_opts + args)
393 if options.config_root is not None:
394 config_root = options.config_root
396 if options.cache_dir is not None:
397 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
399 settings = portage.config(config_root=config_root,
400 target_root='/', local_config=False, env=env)
402 if not options.update and not options.update_use_local_desc:
403 parser.error('No action specified (--update ' + \
404 'and/or --update-use-local-desc)')
407 if options.update and 'metadata-transfer' not in settings.features:
408 writemsg_level("ecachegen: warning: " + \
409 "automatically enabling FEATURES=metadata-transfer\n",
410 level=logging.WARNING, noiselevel=-1)
411 settings.features.add('metadata-transfer')
415 portdb = portage.portdbapi(mysettings=settings)
416 if options.repo is not None:
417 repo_path = portdb.getRepositoryPath(options.repo)
418 if repo_path is None:
419 parser.error("Unable to locate repository named '%s'" % \
423 # Limit ebuilds to the specified repo.
424 portdb.porttrees = [repo_path]
431 cp_iter = iter(atoms)
433 gen_cache = GenCache(portdb, cp_iter=cp_iter,
434 max_jobs=options.jobs,
435 max_load=options.load_average,
438 ret.append(gen_cache.returncode)
440 if options.update_use_local_desc:
441 gen_desc = GenUseLocalDesc(portdb)
443 ret.append(gen_desc.returncode)
449 if __name__ == "__main__":
450 portage._disable_legacy_globals()
451 portage.util.noiselimit = -1
452 sys.exit(egencache_main(sys.argv[1:]))