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 cmp_sort_key, writemsg_level
37 from portage import cpv_getkey
38 from portage.dep import Atom, isjustname
39 from portage.versions import pkgcmp, pkgsplit
42 import xml.etree.ElementTree
46 from repoman.utilities import parse_metadata_use
47 from xml.parsers.expat import ExpatError
49 if sys.hexversion >= 0x3000000:
53 usage = "egencache [options] <action> ... [atom] ..."
54 parser = optparse.OptionParser(usage=usage)
56 actions = optparse.OptionGroup(parser, 'Actions')
57 actions.add_option("--update",
59 help="update metadata/cache/ (generate as necessary)")
60 actions.add_option("--update-use-local-desc",
62 help="update the use.local.desc file from metadata.xml")
63 parser.add_option_group(actions)
65 common = optparse.OptionGroup(parser, 'Common options')
66 common.add_option("--repo",
68 help="name of repo to operate on (default repo is located at $PORTDIR)")
69 common.add_option("--config-root",
70 help="location of portage config files",
71 dest="portage_configroot")
72 common.add_option("--portdir",
73 help="override the portage tree location",
75 common.add_option("--tolerant",
77 help="exit successfully if only minor errors occurred")
78 common.add_option("--ignore-default-opts",
80 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
81 parser.add_option_group(common)
83 update = optparse.OptionGroup(parser, '--update options')
84 update.add_option("--cache-dir",
85 help="location of the metadata cache",
87 update.add_option("--jobs",
89 help="max ebuild processes to spawn")
90 update.add_option("--load-average",
92 help="max load allowed when spawning multiple jobs",
94 update.add_option("--rsync",
96 help="enable rsync stat collision workaround " + \
97 "for bug 139134 (use with --update)")
98 parser.add_option_group(update)
100 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
101 uld.add_option("--use-local-desc-output",
102 help="output file for use.local.desc data (or '-' for stdout)",
104 parser.add_option_group(uld)
106 options, args = parser.parse_args(args)
111 jobs = int(options.jobs)
116 parser.error("Invalid: --jobs='%s'" % \
124 if options.load_average:
126 load_average = float(options.load_average)
130 if load_average <= 0.0:
131 parser.error("Invalid: --load-average='%s'" % \
132 (options.load_average,))
134 options.load_average = load_average
137 options.load_average = None
139 options.config_root = options.portage_configroot
140 if options.config_root is not None and \
141 not os.path.isdir(options.config_root):
142 parser.error("Not a directory: --config-root='%s'" % \
143 (options.config_root,))
145 if options.cache_dir is not None and not os.path.isdir(options.cache_dir):
146 parser.error("Not a directory: --cache-dir='%s'" % \
147 (options.cache_dir,))
151 atom = portage.dep.Atom(atom)
152 except portage.exception.InvalidAtom:
153 parser.error('Invalid atom: %s' % (atom,))
155 if not isjustname(atom):
156 parser.error('Atom is too specific: %s' % (atom,))
158 if options.update_use_local_desc:
160 xml.etree.ElementTree
162 parser.error('--update-use-local-desc requires python with USE=xml!')
164 return parser, options, args
166 class GenCache(object):
167 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
169 self._portdb = portdb
170 # We can globally cleanse stale cache only if we
171 # iterate over every single cp.
172 self._global_cleanse = cp_iter is None
173 if cp_iter is not None:
174 self._cp_set = set(cp_iter)
175 cp_iter = iter(self._cp_set)
176 self._cp_missing = self._cp_set.copy()
179 self._cp_missing = set()
180 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
181 consumer=self._metadata_callback,
182 max_jobs=max_jobs, max_load=max_load)
183 self.returncode = os.EX_OK
184 metadbmodule = portdb.settings.load_best_module("portdbapi.metadbmodule")
185 self._trg_cache = metadbmodule(portdb.porttrees[0],
186 "metadata/cache", portage.auxdbkeys[:])
188 self._trg_cache.raise_stat_collision = True
190 self._trg_cache.ec = \
191 portdb._repo_info[portdb.porttrees[0]].eclass_db
192 except AttributeError:
194 self._existing_nodes = set()
196 def _metadata_callback(self, cpv, ebuild_path, repo_path, metadata):
197 self._existing_nodes.add(cpv)
198 self._cp_missing.discard(cpv_getkey(cpv))
199 if metadata is not None:
200 if metadata.get('EAPI') == '0':
204 self._trg_cache[cpv] = metadata
205 except StatCollision as sc:
206 # If the content of a cache entry changes and neither the
207 # file mtime nor size changes, it will prevent rsync from
208 # detecting changes. Cache backends may raise this
209 # exception from _setitem() if they detect this type of stat
210 # collision. These exceptions are handled by bumping the
211 # mtime on the ebuild (and the corresponding cache entry).
214 for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
215 if max_mtime < ec_mtime:
217 if max_mtime == sc.mtime:
219 max_mtime = long(max_mtime)
221 os.utime(ebuild_path, (max_mtime, max_mtime))
225 "%s writing target: %s\n" % (cpv, e),
226 level=logging.ERROR, noiselevel=-1)
228 metadata['_mtime_'] = max_mtime
229 self._trg_cache[cpv] = metadata
230 self._portdb.auxdb[repo_path][cpv] = metadata
232 except CacheError as ce:
235 "%s writing target: %s\n" % (cpv, ce),
236 level=logging.ERROR, noiselevel=-1)
240 self.returncode |= self._regen.returncode
241 cp_missing = self._cp_missing
243 trg_cache = self._trg_cache
245 if self._global_cleanse:
247 for cpv in trg_cache:
252 "Unable to parse cp for '%s'\n" % (cpv,),
253 level=logging.ERROR, noiselevel=-1)
256 except CacheError as ce:
259 "Error listing cache entries for " + \
260 "'%s/metadata/cache': %s, continuing...\n" % \
261 (self._portdb.porttree_root, ce),
262 level=logging.ERROR, noiselevel=-1)
265 cp_set = self._cp_set
267 for cpv in trg_cache:
272 "Unable to parse cp for '%s'\n" % (cpv,),
273 level=logging.ERROR, noiselevel=-1)
275 cp_missing.discard(cp)
278 except CacheError as ce:
281 "Error listing cache entries for " + \
282 "'%s/metadata/cache': %s, continuing...\n" % \
283 (self._portdb.porttree_root, ce),
284 level=logging.ERROR, noiselevel=-1)
288 for cp in sorted(cp_missing):
290 "No ebuilds or cache entries found for '%s'\n" % (cp,),
291 level=logging.ERROR, noiselevel=-1)
294 dead_nodes.difference_update(self._existing_nodes)
300 except CacheError as ce:
303 "%s deleting stale cache: %s\n" % (k, ce),
304 level=logging.ERROR, noiselevel=-1)
306 if not trg_cache.autocommits:
309 except CacheError as ce:
312 "committing target: %s\n" % (ce,),
313 level=logging.ERROR, noiselevel=-1)
315 class GenUseLocalDesc(object):
316 def __init__(self, portdb, output=None):
317 self.returncode = os.EX_OK
318 self._portdb = portdb
319 self._output = output
322 repo_path = self._portdb.porttrees[0]
323 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
325 if self._output is None or self._output != '-':
326 if self._output is None:
327 prof_path = os.path.join(repo_path, 'profiles')
328 desc_path = os.path.join(prof_path, 'use.local.desc')
334 desc_path = self._output
337 output = open(desc_path, 'w')
340 "ERROR: failed to open output file: %s\n" % (e,),
341 level=logging.ERROR, noiselevel=-1)
348 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
349 # your descriptions to your package's metadata.xml ONLY.
350 # * generated automatically using egencache *
354 # The cmp function no longer exists in python3, so we'll
355 # implement our own here under a slightly different name
356 # since we don't want any confusion given that we never
357 # want to rely on the builtin cmp function.
359 return (a > b) - (a < b)
361 for cp in self._portdb.cp_all():
362 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
364 metadata = xml.etree.ElementTree.parse(metadata_path)
367 except (ExpatError, EnvironmentError) as e:
369 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
370 level=logging.ERROR, noiselevel=-1)
374 usedict = parse_metadata_use(metadata)
375 except portage.exception.ParseError as e:
377 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
378 level=logging.ERROR, noiselevel=-1)
381 for flag in sorted(usedict):
382 def atomcmp(atoma, atomb):
383 # None is better than an atom, that's why we reverse the args
384 if atoma is None or atomb is None:
385 return cmp_func(atomb, atoma)
386 # Same for plain PNs (.operator is None then)
387 elif atoma.operator is None or atomb.operator is None:
388 return cmp_func(atomb.operator, atoma.operator)
390 elif atoma.cpv != atomb.cpv:
391 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
392 # Versions match, let's fallback to operator matching
394 return cmp_func(ops.get(atoma.operator, -1),
395 ops.get(atomb.operator, -1))
402 resdict = usedict[flag]
403 if len(resdict) == 1:
404 resdesc = next(iter(resdict.items()))[1]
407 reskeys = dict((_Atom(k), k) for k in resdict)
408 except portage.exception.InvalidAtom as e:
410 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
411 level=logging.ERROR, noiselevel=-1)
413 resdesc = next(iter(resdict.items()))[1]
415 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
416 resdesc = resdict[reskeys[resatoms[-1]]]
418 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
422 def egencache_main(args):
423 parser, options, atoms = parse_args(args)
425 config_root = options.config_root
426 if config_root is None:
429 # The calling environment is ignored, so the program is
430 # completely controlled by commandline arguments.
433 if options.repo is None:
434 env['PORTDIR_OVERLAY'] = ''
436 if options.cache_dir is not None:
437 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
439 if options.portdir is not None:
440 env['PORTDIR'] = options.portdir
442 settings = portage.config(config_root=config_root,
443 target_root='/', local_config=False, env=env)
446 if not options.ignore_default_opts:
447 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
450 parser, options, args = parse_args(default_opts + args)
452 if options.config_root is not None:
453 config_root = options.config_root
455 if options.cache_dir is not None:
456 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
458 settings = portage.config(config_root=config_root,
459 target_root='/', local_config=False, env=env)
461 if not options.update and not options.update_use_local_desc:
462 parser.error('No action specified (--update ' + \
463 'and/or --update-use-local-desc)')
466 if options.update and 'metadata-transfer' not in settings.features:
467 writemsg_level("ecachegen: warning: " + \
468 "automatically enabling FEATURES=metadata-transfer\n",
469 level=logging.WARNING, noiselevel=-1)
470 settings.features.add('metadata-transfer')
474 portdb = portage.portdbapi(mysettings=settings)
475 if options.repo is not None:
476 repo_path = portdb.getRepositoryPath(options.repo)
477 if repo_path is None:
478 parser.error("Unable to locate repository named '%s'" % \
482 # Limit ebuilds to the specified repo.
483 portdb.porttrees = [repo_path]
490 cp_iter = iter(atoms)
492 gen_cache = GenCache(portdb, cp_iter=cp_iter,
493 max_jobs=options.jobs,
494 max_load=options.load_average,
497 ret.append(gen_cache.returncode)
499 if options.update_use_local_desc:
500 gen_desc = GenUseLocalDesc(portdb,
501 output=options.uld_output)
503 ret.append(gen_desc.returncode)
509 if __name__ == "__main__":
510 portage._disable_legacy_globals()
511 portage.util.noiselimit = -1
512 sys.exit(egencache_main(sys.argv[1:]))