egencache: introduce the preliminary support for multiple actions.
[portage.git] / bin / egencache
1 #!/usr/bin/python
2 # Copyright 2009-2010 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
4
5 from __future__ import print_function
6
7 import sys
8 # This block ensures that ^C interrupts are handled quietly.
9 try:
10         import signal
11
12         def exithandler(signum,frame):
13                 signal.signal(signal.SIGINT, signal.SIG_IGN)
14                 signal.signal(signal.SIGTERM, signal.SIG_IGN)
15                 sys.exit(1)
16
17         signal.signal(signal.SIGINT, exithandler)
18         signal.signal(signal.SIGTERM, exithandler)
19
20 except KeyboardInterrupt:
21         sys.exit(1)
22
23 import logging
24 import optparse
25
26 try:
27         import portage
28 except ImportError:
29         from os import path as osp
30         sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
31         import portage
32
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
39
40 if sys.hexversion >= 0x3000000:
41         long = int
42
43 def parse_args(args):
44         usage = "egencache [options] <action> ... [atom] ..."
45         parser = optparse.OptionParser(usage=usage)
46
47         actions = optparse.OptionGroup(parser, 'Actions')
48         actions.add_option("--update",
49                 action="store_true",
50                 help="update metadata/cache/ (generate as necessary)")
51         parser.add_option_group(actions)
52
53         common = optparse.OptionGroup(parser, 'Common options')
54         common.add_option("--repo",
55                 action="store",
56                 help="name of repo to operate on (default repo is located at $PORTDIR)")
57         common.add_option("--config-root",
58                 help="location of portage config files",
59                 dest="portage_configroot")
60         common.add_option("--portdir",
61                 help="override the portage tree location",
62                 dest="portdir")
63         common.add_option("--tolerant",
64                 action="store_true",
65                 help="exit successfully if only minor errors occurred")
66         common.add_option("--ignore-default-opts",
67                 action="store_true",
68                 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
69         parser.add_option_group(common)
70
71         update = optparse.OptionGroup(parser, '--update options')
72         update.add_option("--cache-dir",
73                 help="location of the metadata cache",
74                 dest="cache_dir")
75         update.add_option("--jobs",
76                 action="store",
77                 help="max ebuild processes to spawn")
78         update.add_option("--load-average",
79                 action="store",
80                 help="max load allowed when spawning multiple jobs",
81                 dest="load_average")
82         update.add_option("--rsync",
83                 action="store_true",
84                 help="enable rsync stat collision workaround " + \
85                         "for bug 139134 (use with --update)")
86         parser.add_option_group(update)
87
88         options, args = parser.parse_args(args)
89
90         if options.jobs:
91                 jobs = None
92                 try:
93                         jobs = int(options.jobs)
94                 except ValueError:
95                         jobs = -1
96
97                 if jobs < 1:
98                         parser.error("Invalid: --jobs='%s'" % \
99                                 (options.jobs,))
100
101                 options.jobs = jobs
102
103         else:
104                 options.jobs = None
105
106         if options.load_average:
107                 try:
108                         load_average = float(options.load_average)
109                 except ValueError:
110                         load_average = 0.0
111
112                 if load_average <= 0.0:
113                         parser.error("Invalid: --load-average='%s'" % \
114                                 (options.load_average,))
115
116                 options.load_average = load_average
117
118         else:
119                 options.load_average = None
120
121         options.config_root = options.portage_configroot
122         if options.config_root is not None and \
123                 not os.path.isdir(options.config_root):
124                 parser.error("Not a directory: --config-root='%s'" % \
125                         (options.config_root,))
126
127         if options.cache_dir is not None and not os.path.isdir(options.cache_dir):
128                 parser.error("Not a directory: --cache-dir='%s'" % \
129                         (options.cache_dir,))
130
131         for atom in args:
132                 try:
133                         atom = portage.dep.Atom(atom)
134                 except portage.exception.InvalidAtom:
135                         parser.error('Invalid atom: %s' % (atom,))
136
137                 if not isjustname(atom):
138                         parser.error('Atom is too specific: %s' % (atom,))
139
140         return parser, options, args
141
142 class GenCache(object):
143         def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
144                 rsync=False):
145                 self._portdb = portdb
146                 # We can globally cleanse stale cache only if we
147                 # iterate over every single cp.
148                 self._global_cleanse = cp_iter is None
149                 if cp_iter is not None:
150                         self._cp_set = set(cp_iter)
151                         cp_iter = iter(self._cp_set)
152                         self._cp_missing = self._cp_set.copy()
153                 else:
154                         self._cp_set = None
155                         self._cp_missing = set()
156                 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
157                         consumer=self._metadata_callback,
158                         max_jobs=max_jobs, max_load=max_load)
159                 self.returncode = os.EX_OK
160                 metadbmodule = portdb.settings.load_best_module("portdbapi.metadbmodule")
161                 self._trg_cache = metadbmodule(portdb.porttrees[0],
162                         "metadata/cache", portage.auxdbkeys[:])
163                 if rsync:
164                         self._trg_cache.raise_stat_collision = True
165                 try:
166                         self._trg_cache.ec = \
167                                 portdb._repo_info[portdb.porttrees[0]].eclass_db
168                 except AttributeError:
169                         pass
170                 self._existing_nodes = set()
171
172         def _metadata_callback(self, cpv, ebuild_path, repo_path, metadata):
173                 self._existing_nodes.add(cpv)
174                 self._cp_missing.discard(cpv_getkey(cpv))
175                 if metadata is not None:
176                         if metadata.get('EAPI') == '0':
177                                 del metadata['EAPI']
178                         try:
179                                 try:
180                                         self._trg_cache[cpv] = metadata
181                                 except StatCollision as sc:
182                                         # If the content of a cache entry changes and neither the
183                                         # file mtime nor size changes, it will prevent rsync from
184                                         # detecting changes. Cache backends may raise this
185                                         # exception from _setitem() if they detect this type of stat
186                                         # collision. These exceptions are handled by bumping the
187                                         # mtime on the ebuild (and the corresponding cache entry).
188                                         # See bug #139134.
189                                         max_mtime = sc.mtime
190                                         for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
191                                                 if max_mtime < ec_mtime:
192                                                         max_mtime = ec_mtime
193                                         if max_mtime == sc.mtime:
194                                                 max_mtime += 1
195                                         max_mtime = long(max_mtime)
196                                         try:
197                                                 os.utime(ebuild_path, (max_mtime, max_mtime))
198                                         except OSError as e:
199                                                 self.returncode |= 1
200                                                 writemsg_level(
201                                                         "%s writing target: %s\n" % (cpv, e),
202                                                         level=logging.ERROR, noiselevel=-1)
203                                         else:
204                                                 metadata['_mtime_'] = max_mtime
205                                                 self._trg_cache[cpv] = metadata
206                                                 self._portdb.auxdb[repo_path][cpv] = metadata
207
208                         except CacheError as ce:
209                                 self.returncode |= 1
210                                 writemsg_level(
211                                         "%s writing target: %s\n" % (cpv, ce),
212                                         level=logging.ERROR, noiselevel=-1)
213
214         def run(self):
215                 self._regen.run()
216                 self.returncode |= self._regen.returncode
217                 cp_missing = self._cp_missing
218
219                 trg_cache = self._trg_cache
220                 dead_nodes = set()
221                 if self._global_cleanse:
222                         try:
223                                 for cpv in trg_cache:
224                                         cp = cpv_getkey(cpv)
225                                         if cp is None:
226                                                 self.returncode |= 1
227                                                 writemsg_level(
228                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
229                                                         level=logging.ERROR, noiselevel=-1)
230                                         else:
231                                                 dead_nodes.add(cpv)
232                         except CacheError as ce:
233                                 self.returncode |= 1
234                                 writemsg_level(
235                                         "Error listing cache entries for " + \
236                                         "'%s/metadata/cache': %s, continuing...\n" % \
237                                         (self._portdb.porttree_root, ce),
238                                         level=logging.ERROR, noiselevel=-1)
239
240                 else:
241                         cp_set = self._cp_set
242                         try:
243                                 for cpv in trg_cache:
244                                         cp = cpv_getkey(cpv)
245                                         if cp is None:
246                                                 self.returncode |= 1
247                                                 writemsg_level(
248                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
249                                                         level=logging.ERROR, noiselevel=-1)
250                                         else:
251                                                 cp_missing.discard(cp)
252                                                 if cp in cp_set:
253                                                         dead_nodes.add(cpv)
254                         except CacheError as ce:
255                                 self.returncode |= 1
256                                 writemsg_level(
257                                         "Error listing cache entries for " + \
258                                         "'%s/metadata/cache': %s, continuing...\n" % \
259                                         (self._portdb.porttree_root, ce),
260                                         level=logging.ERROR, noiselevel=-1)
261
262                 if cp_missing:
263                         self.returncode |= 1
264                         for cp in sorted(cp_missing):
265                                 writemsg_level(
266                                         "No ebuilds or cache entries found for '%s'\n"  % (cp,),
267                                         level=logging.ERROR, noiselevel=-1)
268
269                 if dead_nodes:
270                         dead_nodes.difference_update(self._existing_nodes)
271                         for k in dead_nodes:
272                                 try:
273                                         del trg_cache[k]
274                                 except KeyError:
275                                         pass
276                                 except CacheError as ce:
277                                         self.returncode |= 1
278                                         writemsg_level(
279                                                 "%s deleting stale cache: %s\n" % (k, ce),
280                                                 level=logging.ERROR, noiselevel=-1)
281
282                 if not trg_cache.autocommits:
283                         try:
284                                 trg_cache.commit()
285                         except CacheError as ce:
286                                 self.returncode |= 1
287                                 writemsg_level(
288                                         "committing target: %s\n" % (ce,),
289                                         level=logging.ERROR, noiselevel=-1)
290
291 def egencache_main(args):
292         parser, options, atoms = parse_args(args)
293
294         config_root = options.config_root
295         if config_root is None:
296                 config_root = '/'
297
298         # The calling environment is ignored, so the program is
299         # completely controlled by commandline arguments.
300         env = {}
301
302         if options.repo is None:
303                 env['PORTDIR_OVERLAY'] = ''
304
305         if options.cache_dir is not None:
306                 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
307
308         if options.portdir is not None:
309                 env['PORTDIR'] = options.portdir
310
311         settings = portage.config(config_root=config_root,
312                 target_root='/', local_config=False, env=env)
313
314         default_opts = None
315         if not options.ignore_default_opts:
316                 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
317
318         if default_opts:
319                 parser, options, args = parse_args(default_opts + args)
320
321                 if options.config_root is not None:
322                         config_root = options.config_root
323
324                 if options.cache_dir is not None:
325                         env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
326
327                 settings = portage.config(config_root=config_root,
328                         target_root='/', local_config=False, env=env)
329
330         if not options.update:
331                 parser.error('No action specified (--update ' + \
332                         'is the only available action)')
333                 return 1
334
335         if 'metadata-transfer' not in settings.features:
336                 writemsg_level("ecachegen: warning: " + \
337                         "automatically enabling FEATURES=metadata-transfer\n",
338                         level=logging.WARNING, noiselevel=-1)
339                 settings.features.add('metadata-transfer')
340
341         settings.lock()
342
343         portdb = portage.portdbapi(mysettings=settings)
344         if options.repo is not None:
345                 repo_path = portdb.getRepositoryPath(options.repo)
346                 if repo_path is None:
347                         parser.error("Unable to locate repository named '%s'" % \
348                                 (options.repo,))
349                         return 1
350
351                 # Limit ebuilds to the specified repo.
352                 portdb.porttrees = [repo_path]
353
354         ret = [os.EX_OK]
355
356         if options.update:
357                 cp_iter = None
358                 if atoms:
359                         cp_iter = iter(atoms)
360
361                 gen_cache = GenCache(portdb, cp_iter=cp_iter,
362                         max_jobs=options.jobs,
363                         max_load=options.load_average,
364                         rsync=options.rsync)
365                 gen_cache.run()
366                 ret.append(gen_cache.returncode)
367
368         if options.tolerant:
369                 return ret[0]
370         return max(ret)
371
372 if __name__ == "__main__":
373         portage._disable_legacy_globals()
374         portage.util.noiselimit = -1
375         sys.exit(egencache_main(sys.argv[1:]))