blob: ecd1f25e63b64413f4dd413ed8b1284562d84d36 [file] [log] [blame]
Mike Frysinger9f7e4ee2013-03-13 15:43:03 -04001#!/usr/bin/python
Mike Frysinger0a647fc2012-08-06 14:36:05 -04002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
David Jamesfcb70ef2011-02-02 16:02:30 -08003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Program to run emerge in parallel, for significant speedup.
7
8Usage:
David James386ccd12011-05-04 20:17:42 -07009 ./parallel_emerge [--board=BOARD] [--workon=PKGS]
David Jamesfcb70ef2011-02-02 16:02:30 -080010 [--force-remote-binary=PKGS] [emerge args] package
11
David James78b6cd92012-04-02 21:36:12 -070012This script runs multiple emerge processes in parallel, using appropriate
13Portage APIs. It is faster than standard emerge because it has a
14multiprocess model instead of an asynchronous model.
David Jamesfcb70ef2011-02-02 16:02:30 -080015"""
16
17import codecs
18import copy
19import errno
Brian Harring8294d652012-05-23 02:20:52 -070020import gc
David James8c7e5e32011-06-28 11:26:03 -070021import heapq
David Jamesfcb70ef2011-02-02 16:02:30 -080022import multiprocessing
23import os
24import Queue
David Jamesfcb70ef2011-02-02 16:02:30 -080025import signal
26import sys
27import tempfile
Brian Harring8294d652012-05-23 02:20:52 -070028import threading
David Jamesfcb70ef2011-02-02 16:02:30 -080029import time
30import traceback
David Jamesfcb70ef2011-02-02 16:02:30 -080031
32# If PORTAGE_USERNAME isn't specified, scrape it from the $HOME variable. On
33# Chromium OS, the default "portage" user doesn't have the necessary
34# permissions. It'd be easier if we could default to $USERNAME, but $USERNAME
35# is "root" here because we get called through sudo.
36#
37# We need to set this before importing any portage modules, because portage
38# looks up "PORTAGE_USERNAME" at import time.
39#
40# NOTE: .bashrc sets PORTAGE_USERNAME = $USERNAME, so most people won't
41# encounter this case unless they have an old chroot or blow away the
42# environment by running sudo without the -E specifier.
43if "PORTAGE_USERNAME" not in os.environ:
44 homedir = os.environ.get("HOME")
45 if homedir:
46 os.environ["PORTAGE_USERNAME"] = os.path.basename(homedir)
47
48# Portage doesn't expose dependency trees in its public API, so we have to
49# make use of some private APIs here. These modules are found under
50# /usr/lib/portage/pym/.
51#
52# TODO(davidjames): Update Portage to expose public APIs for these features.
David James321490a2012-12-17 12:05:56 -080053# pylint: disable=W0212
David Jamesfcb70ef2011-02-02 16:02:30 -080054from _emerge.actions import adjust_configs
55from _emerge.actions import load_emerge_config
56from _emerge.create_depgraph_params import create_depgraph_params
David James386ccd12011-05-04 20:17:42 -070057from _emerge.depgraph import backtrack_depgraph
Mike Frysinger901eaad2012-10-10 18:18:03 -040058try:
59 from _emerge.main import clean_logs
60except ImportError:
61 # Older portage versions did not provide clean_logs, so stub it.
62 # We need this if running in an older chroot that hasn't yet upgraded
63 # the portage version.
64 clean_logs = lambda x: None
David Jamesfcb70ef2011-02-02 16:02:30 -080065from _emerge.main import emerge_main
66from _emerge.main import parse_opts
67from _emerge.Package import Package
68from _emerge.Scheduler import Scheduler
David Jamesfcb70ef2011-02-02 16:02:30 -080069from _emerge.stdout_spinner import stdout_spinner
David James386ccd12011-05-04 20:17:42 -070070from portage._global_updates import _global_updates
David Jamesfcb70ef2011-02-02 16:02:30 -080071import portage
72import portage.debug
Mike Frysinger91d7da92013-02-19 15:53:46 -050073from portage.versions import vercmp
74
David Jamesfcb70ef2011-02-02 16:02:30 -080075
David Jamesfcb70ef2011-02-02 16:02:30 -080076def Usage():
77 """Print usage."""
78 print "Usage:"
David James386ccd12011-05-04 20:17:42 -070079 print " ./parallel_emerge [--board=BOARD] [--workon=PKGS]"
David Jamesfcb70ef2011-02-02 16:02:30 -080080 print " [--rebuild] [emerge args] package"
81 print
82 print "Packages specified as workon packages are always built from source."
David Jamesfcb70ef2011-02-02 16:02:30 -080083 print
84 print "The --workon argument is mainly useful when you want to build and"
85 print "install packages that you are working on unconditionally, but do not"
86 print "to have to rev the package to indicate you want to build it from"
87 print "source. The build_packages script will automatically supply the"
88 print "workon argument to emerge, ensuring that packages selected using"
89 print "cros-workon are rebuilt."
90 print
91 print "The --rebuild option rebuilds packages whenever their dependencies"
92 print "are changed. This ensures that your build is correct."
David Jamesfcb70ef2011-02-02 16:02:30 -080093
94
David Jamesfcb70ef2011-02-02 16:02:30 -080095# Global start time
96GLOBAL_START = time.time()
97
David James7358d032011-05-19 10:40:03 -070098# Whether process has been killed by a signal.
99KILLED = multiprocessing.Event()
100
David Jamesfcb70ef2011-02-02 16:02:30 -0800101
102class EmergeData(object):
103 """This simple struct holds various emerge variables.
104
105 This struct helps us easily pass emerge variables around as a unit.
106 These variables are used for calculating dependencies and installing
107 packages.
108 """
109
David Jamesbf1e3442011-05-28 07:44:20 -0700110 __slots__ = ["action", "cmdline_packages", "depgraph", "favorites",
111 "mtimedb", "opts", "root_config", "scheduler_graph",
112 "settings", "spinner", "trees"]
David Jamesfcb70ef2011-02-02 16:02:30 -0800113
114 def __init__(self):
115 # The action the user requested. If the user is installing packages, this
116 # is None. If the user is doing anything other than installing packages,
117 # this will contain the action name, which will map exactly to the
118 # long-form name of the associated emerge option.
119 #
120 # Example: If you call parallel_emerge --unmerge package, the action name
121 # will be "unmerge"
122 self.action = None
123
124 # The list of packages the user passed on the command-line.
125 self.cmdline_packages = None
126
127 # The emerge dependency graph. It'll contain all the packages involved in
128 # this merge, along with their versions.
129 self.depgraph = None
130
David Jamesbf1e3442011-05-28 07:44:20 -0700131 # The list of candidates to add to the world file.
132 self.favorites = None
133
David Jamesfcb70ef2011-02-02 16:02:30 -0800134 # A dict of the options passed to emerge. This dict has been cleaned up
135 # a bit by parse_opts, so that it's a bit easier for the emerge code to
136 # look at the options.
137 #
138 # Emerge takes a few shortcuts in its cleanup process to make parsing of
139 # the options dict easier. For example, if you pass in "--usepkg=n", the
140 # "--usepkg" flag is just left out of the dictionary altogether. Because
141 # --usepkg=n is the default, this makes parsing easier, because emerge
142 # can just assume that if "--usepkg" is in the dictionary, it's enabled.
143 #
144 # These cleanup processes aren't applied to all options. For example, the
145 # --with-bdeps flag is passed in as-is. For a full list of the cleanups
146 # applied by emerge, see the parse_opts function in the _emerge.main
147 # package.
148 self.opts = None
149
150 # A dictionary used by portage to maintain global state. This state is
151 # loaded from disk when portage starts up, and saved to disk whenever we
152 # call mtimedb.commit().
153 #
154 # This database contains information about global updates (i.e., what
155 # version of portage we have) and what we're currently doing. Portage
156 # saves what it is currently doing in this database so that it can be
157 # resumed when you call it with the --resume option.
158 #
159 # parallel_emerge does not save what it is currently doing in the mtimedb,
160 # so we do not support the --resume option.
161 self.mtimedb = None
162
163 # The portage configuration for our current root. This contains the portage
164 # settings (see below) and the three portage trees for our current root.
165 # (The three portage trees are explained below, in the documentation for
166 # the "trees" member.)
167 self.root_config = None
168
169 # The scheduler graph is used by emerge to calculate what packages to
170 # install. We don't actually install any deps, so this isn't really used,
171 # but we pass it in to the Scheduler object anyway.
172 self.scheduler_graph = None
173
174 # Portage settings for our current session. Most of these settings are set
175 # in make.conf inside our current install root.
176 self.settings = None
177
178 # The spinner, which spews stuff to stdout to indicate that portage is
179 # doing something. We maintain our own spinner, so we set the portage
180 # spinner to "silent" mode.
181 self.spinner = None
182
183 # The portage trees. There are separate portage trees for each root. To get
184 # the portage tree for the current root, you can look in self.trees[root],
185 # where root = self.settings["ROOT"].
186 #
187 # In each root, there are three trees: vartree, porttree, and bintree.
188 # - vartree: A database of the currently-installed packages.
189 # - porttree: A database of ebuilds, that can be used to build packages.
190 # - bintree: A database of binary packages.
191 self.trees = None
192
193
194class DepGraphGenerator(object):
195 """Grab dependency information about packages from portage.
196
197 Typical usage:
198 deps = DepGraphGenerator()
199 deps.Initialize(sys.argv[1:])
200 deps_tree, deps_info = deps.GenDependencyTree()
201 deps_graph = deps.GenDependencyGraph(deps_tree, deps_info)
202 deps.PrintTree(deps_tree)
203 PrintDepsMap(deps_graph)
204 """
205
David James386ccd12011-05-04 20:17:42 -0700206 __slots__ = ["board", "emerge", "package_db", "show_output"]
David Jamesfcb70ef2011-02-02 16:02:30 -0800207
208 def __init__(self):
209 self.board = None
210 self.emerge = EmergeData()
David Jamesfcb70ef2011-02-02 16:02:30 -0800211 self.package_db = {}
David Jamesfcb70ef2011-02-02 16:02:30 -0800212 self.show_output = False
David Jamesfcb70ef2011-02-02 16:02:30 -0800213
214 def ParseParallelEmergeArgs(self, argv):
215 """Read the parallel emerge arguments from the command-line.
216
217 We need to be compatible with emerge arg format. We scrape arguments that
218 are specific to parallel_emerge, and pass through the rest directly to
219 emerge.
220 Args:
221 argv: arguments list
222 Returns:
223 Arguments that don't belong to parallel_emerge
224 """
225 emerge_args = []
226 for arg in argv:
227 # Specifically match arguments that are specific to parallel_emerge, and
228 # pass through the rest.
229 if arg.startswith("--board="):
230 self.board = arg.replace("--board=", "")
231 elif arg.startswith("--workon="):
232 workon_str = arg.replace("--workon=", "")
David James7a1ea4b2011-10-13 15:06:41 -0700233 emerge_args.append("--reinstall-atoms=%s" % workon_str)
234 emerge_args.append("--usepkg-exclude=%s" % workon_str)
David Jamesfcb70ef2011-02-02 16:02:30 -0800235 elif arg.startswith("--force-remote-binary="):
236 force_remote_binary = arg.replace("--force-remote-binary=", "")
David James7a1ea4b2011-10-13 15:06:41 -0700237 emerge_args.append("--useoldpkg-atoms=%s" % force_remote_binary)
David Jamesfcb70ef2011-02-02 16:02:30 -0800238 elif arg == "--show-output":
239 self.show_output = True
David James386ccd12011-05-04 20:17:42 -0700240 elif arg == "--rebuild":
David James7a1ea4b2011-10-13 15:06:41 -0700241 emerge_args.append("--rebuild-if-unbuilt")
David Jamesfcb70ef2011-02-02 16:02:30 -0800242 else:
243 # Not one of our options, so pass through to emerge.
244 emerge_args.append(arg)
245
David James386ccd12011-05-04 20:17:42 -0700246 # These packages take a really long time to build, so, for expediency, we
247 # are blacklisting them from automatic rebuilds because one of their
248 # dependencies needs to be recompiled.
249 for pkg in ("chromeos-base/chromeos-chrome", "media-plugins/o3d",
250 "dev-java/icedtea"):
David James7a1ea4b2011-10-13 15:06:41 -0700251 emerge_args.append("--rebuild-exclude=%s" % pkg)
David Jamesfcb70ef2011-02-02 16:02:30 -0800252
253 return emerge_args
254
255 def Initialize(self, args):
256 """Initializer. Parses arguments and sets up portage state."""
257
258 # Parse and strip out args that are just intended for parallel_emerge.
259 emerge_args = self.ParseParallelEmergeArgs(args)
260
261 # Setup various environment variables based on our current board. These
262 # variables are normally setup inside emerge-${BOARD}, but since we don't
263 # call that script, we have to set it up here. These variables serve to
264 # point our tools at /build/BOARD and to setup cross compiles to the
265 # appropriate board as configured in toolchain.conf.
266 if self.board:
267 os.environ["PORTAGE_CONFIGROOT"] = "/build/" + self.board
268 os.environ["PORTAGE_SYSROOT"] = "/build/" + self.board
269 os.environ["SYSROOT"] = "/build/" + self.board
David Jamesfcb70ef2011-02-02 16:02:30 -0800270
271 # Although CHROMEOS_ROOT isn't specific to boards, it's normally setup
272 # inside emerge-${BOARD}, so we set it up here for compatibility. It
273 # will be going away soon as we migrate to CROS_WORKON_SRCROOT.
274 os.environ.setdefault("CHROMEOS_ROOT", os.environ["HOME"] + "/trunk")
275
276 # Turn off interactive delays
277 os.environ["EBEEP_IGNORE"] = "1"
278 os.environ["EPAUSE_IGNORE"] = "1"
Mike Frysinger0a647fc2012-08-06 14:36:05 -0400279 os.environ["CLEAN_DELAY"] = "0"
David Jamesfcb70ef2011-02-02 16:02:30 -0800280
281 # Parse the emerge options.
David Jamesea3ca332011-05-26 11:48:29 -0700282 action, opts, cmdline_packages = parse_opts(emerge_args, silent=True)
David Jamesfcb70ef2011-02-02 16:02:30 -0800283
284 # Set environment variables based on options. Portage normally sets these
285 # environment variables in emerge_main, but we can't use that function,
286 # because it also does a bunch of other stuff that we don't want.
287 # TODO(davidjames): Patch portage to move this logic into a function we can
288 # reuse here.
289 if "--debug" in opts:
290 os.environ["PORTAGE_DEBUG"] = "1"
291 if "--config-root" in opts:
292 os.environ["PORTAGE_CONFIGROOT"] = opts["--config-root"]
293 if "--root" in opts:
294 os.environ["ROOT"] = opts["--root"]
295 if "--accept-properties" in opts:
296 os.environ["ACCEPT_PROPERTIES"] = opts["--accept-properties"]
297
David Jamesfcb70ef2011-02-02 16:02:30 -0800298 # If we're installing packages to the board, and we're not using the
David James927a56d2012-04-03 11:26:39 -0700299 # official flag, we can disable vardb locks. This is safe because we
300 # only run up to one instance of parallel_emerge in parallel.
David Jamesfcb70ef2011-02-02 16:02:30 -0800301 if self.board and os.environ.get("CHROMEOS_OFFICIAL") != "1":
302 os.environ.setdefault("PORTAGE_LOCKS", "false")
David Jamesfcb70ef2011-02-02 16:02:30 -0800303
304 # Now that we've setup the necessary environment variables, we can load the
305 # emerge config from disk.
306 settings, trees, mtimedb = load_emerge_config()
307
David Jamesea3ca332011-05-26 11:48:29 -0700308 # Add in EMERGE_DEFAULT_OPTS, if specified.
309 tmpcmdline = []
310 if "--ignore-default-opts" not in opts:
311 tmpcmdline.extend(settings["EMERGE_DEFAULT_OPTS"].split())
312 tmpcmdline.extend(emerge_args)
313 action, opts, cmdline_packages = parse_opts(tmpcmdline)
314
315 # If we're installing to the board, we want the --root-deps option so that
316 # portage will install the build dependencies to that location as well.
317 if self.board:
318 opts.setdefault("--root-deps", True)
319
David Jamesfcb70ef2011-02-02 16:02:30 -0800320 # Check whether our portage tree is out of date. Typically, this happens
321 # when you're setting up a new portage tree, such as in setup_board and
322 # make_chroot. In that case, portage applies a bunch of global updates
323 # here. Once the updates are finished, we need to commit any changes
324 # that the global update made to our mtimedb, and reload the config.
325 #
326 # Portage normally handles this logic in emerge_main, but again, we can't
327 # use that function here.
328 if _global_updates(trees, mtimedb["updates"]):
329 mtimedb.commit()
330 settings, trees, mtimedb = load_emerge_config(trees=trees)
331
332 # Setup implied options. Portage normally handles this logic in
333 # emerge_main.
334 if "--buildpkgonly" in opts or "buildpkg" in settings.features:
335 opts.setdefault("--buildpkg", True)
336 if "--getbinpkgonly" in opts:
337 opts.setdefault("--usepkgonly", True)
338 opts.setdefault("--getbinpkg", True)
339 if "getbinpkg" in settings.features:
340 # Per emerge_main, FEATURES=getbinpkg overrides --getbinpkg=n
341 opts["--getbinpkg"] = True
342 if "--getbinpkg" in opts or "--usepkgonly" in opts:
343 opts.setdefault("--usepkg", True)
344 if "--fetch-all-uri" in opts:
345 opts.setdefault("--fetchonly", True)
346 if "--skipfirst" in opts:
347 opts.setdefault("--resume", True)
348 if "--buildpkgonly" in opts:
349 # --buildpkgonly will not merge anything, so it overrides all binary
350 # package options.
351 for opt in ("--getbinpkg", "--getbinpkgonly",
352 "--usepkg", "--usepkgonly"):
353 opts.pop(opt, None)
354 if (settings.get("PORTAGE_DEBUG", "") == "1" and
355 "python-trace" in settings.features):
356 portage.debug.set_trace(True)
357
358 # Complain about unsupported options
David James386ccd12011-05-04 20:17:42 -0700359 for opt in ("--ask", "--ask-enter-invalid", "--resume", "--skipfirst"):
David Jamesfcb70ef2011-02-02 16:02:30 -0800360 if opt in opts:
361 print "%s is not supported by parallel_emerge" % opt
362 sys.exit(1)
363
364 # Make emerge specific adjustments to the config (e.g. colors!)
365 adjust_configs(opts, trees)
366
367 # Save our configuration so far in the emerge object
368 emerge = self.emerge
369 emerge.action, emerge.opts = action, opts
370 emerge.settings, emerge.trees, emerge.mtimedb = settings, trees, mtimedb
371 emerge.cmdline_packages = cmdline_packages
372 root = settings["ROOT"]
373 emerge.root_config = trees[root]["root_config"]
374
David James386ccd12011-05-04 20:17:42 -0700375 if "--usepkg" in opts:
David Jamesfcb70ef2011-02-02 16:02:30 -0800376 emerge.trees[root]["bintree"].populate("--getbinpkg" in opts)
377
David Jamesfcb70ef2011-02-02 16:02:30 -0800378 def CreateDepgraph(self, emerge, packages):
379 """Create an emerge depgraph object."""
380 # Setup emerge options.
381 emerge_opts = emerge.opts.copy()
382
David James386ccd12011-05-04 20:17:42 -0700383 # Ask portage to build a dependency graph. with the options we specified
384 # above.
David Jamesfcb70ef2011-02-02 16:02:30 -0800385 params = create_depgraph_params(emerge_opts, emerge.action)
David Jamesbf1e3442011-05-28 07:44:20 -0700386 success, depgraph, favorites = backtrack_depgraph(
David James386ccd12011-05-04 20:17:42 -0700387 emerge.settings, emerge.trees, emerge_opts, params, emerge.action,
388 packages, emerge.spinner)
389 emerge.depgraph = depgraph
David Jamesfcb70ef2011-02-02 16:02:30 -0800390
David James386ccd12011-05-04 20:17:42 -0700391 # Is it impossible to honor the user's request? Bail!
392 if not success:
393 depgraph.display_problems()
394 sys.exit(1)
David Jamesfcb70ef2011-02-02 16:02:30 -0800395
396 emerge.depgraph = depgraph
David Jamesbf1e3442011-05-28 07:44:20 -0700397 emerge.favorites = favorites
David Jamesfcb70ef2011-02-02 16:02:30 -0800398
David Jamesdeebd692011-05-09 17:02:52 -0700399 # Prime and flush emerge caches.
400 root = emerge.settings["ROOT"]
401 vardb = emerge.trees[root]["vartree"].dbapi
David James0bdc5de2011-05-12 16:22:26 -0700402 if "--pretend" not in emerge.opts:
403 vardb.counter_tick()
David Jamesdeebd692011-05-09 17:02:52 -0700404 vardb.flush_cache()
405
David James386ccd12011-05-04 20:17:42 -0700406 def GenDependencyTree(self):
David Jamesfcb70ef2011-02-02 16:02:30 -0800407 """Get dependency tree info from emerge.
408
David Jamesfcb70ef2011-02-02 16:02:30 -0800409 Returns:
410 Dependency tree
411 """
412 start = time.time()
413
414 emerge = self.emerge
415
416 # Create a list of packages to merge
417 packages = set(emerge.cmdline_packages[:])
David Jamesfcb70ef2011-02-02 16:02:30 -0800418
419 # Tell emerge to be quiet. We print plenty of info ourselves so we don't
420 # need any extra output from portage.
421 portage.util.noiselimit = -1
422
423 # My favorite feature: The silent spinner. It doesn't spin. Ever.
424 # I'd disable the colors by default too, but they look kind of cool.
425 emerge.spinner = stdout_spinner()
426 emerge.spinner.update = emerge.spinner.update_quiet
427
428 if "--quiet" not in emerge.opts:
429 print "Calculating deps..."
430
431 self.CreateDepgraph(emerge, packages)
432 depgraph = emerge.depgraph
433
434 # Build our own tree from the emerge digraph.
435 deps_tree = {}
436 digraph = depgraph._dynamic_config.digraph
David James3f778802011-08-25 19:31:45 -0700437 root = emerge.settings["ROOT"]
438 final_db = depgraph._dynamic_config.mydbapi[root]
David Jamesfcb70ef2011-02-02 16:02:30 -0800439 for node, node_deps in digraph.nodes.items():
440 # Calculate dependency packages that need to be installed first. Each
441 # child on the digraph is a dependency. The "operation" field specifies
442 # what we're doing (e.g. merge, uninstall, etc.). The "priorities" array
443 # contains the type of dependency (e.g. build, runtime, runtime_post,
444 # etc.)
445 #
David Jamesfcb70ef2011-02-02 16:02:30 -0800446 # Portage refers to the identifiers for packages as a CPV. This acronym
447 # stands for Component/Path/Version.
448 #
449 # Here's an example CPV: chromeos-base/power_manager-0.0.1-r1
450 # Split up, this CPV would be:
451 # C -- Component: chromeos-base
452 # P -- Path: power_manager
453 # V -- Version: 0.0.1-r1
454 #
455 # We just refer to CPVs as packages here because it's easier.
456 deps = {}
457 for child, priorities in node_deps[0].items():
David James3f778802011-08-25 19:31:45 -0700458 if isinstance(child, Package) and child.root == root:
459 cpv = str(child.cpv)
460 action = str(child.operation)
461
462 # If we're uninstalling a package, check whether Portage is
463 # installing a replacement. If so, just depend on the installation
464 # of the new package, because the old package will automatically
465 # be uninstalled at that time.
466 if action == "uninstall":
467 for pkg in final_db.match_pkgs(child.slot_atom):
468 cpv = str(pkg.cpv)
469 action = "merge"
470 break
471
472 deps[cpv] = dict(action=action,
473 deptypes=[str(x) for x in priorities],
474 deps={})
David Jamesfcb70ef2011-02-02 16:02:30 -0800475
476 # We've built our list of deps, so we can add our package to the tree.
David James3f778802011-08-25 19:31:45 -0700477 if isinstance(node, Package) and node.root == root:
David Jamesfcb70ef2011-02-02 16:02:30 -0800478 deps_tree[str(node.cpv)] = dict(action=str(node.operation),
479 deps=deps)
480
David Jamesfcb70ef2011-02-02 16:02:30 -0800481 # Ask portage for its install plan, so that we can only throw out
David James386ccd12011-05-04 20:17:42 -0700482 # dependencies that portage throws out.
David Jamesfcb70ef2011-02-02 16:02:30 -0800483 deps_info = {}
484 for pkg in depgraph.altlist():
485 if isinstance(pkg, Package):
David James3f778802011-08-25 19:31:45 -0700486 assert pkg.root == root
David Jamesfcb70ef2011-02-02 16:02:30 -0800487 self.package_db[pkg.cpv] = pkg
488
David Jamesfcb70ef2011-02-02 16:02:30 -0800489 # Save off info about the package
David James386ccd12011-05-04 20:17:42 -0700490 deps_info[str(pkg.cpv)] = {"idx": len(deps_info)}
David Jamesfcb70ef2011-02-02 16:02:30 -0800491
492 seconds = time.time() - start
493 if "--quiet" not in emerge.opts:
494 print "Deps calculated in %dm%.1fs" % (seconds / 60, seconds % 60)
495
496 return deps_tree, deps_info
497
498 def PrintTree(self, deps, depth=""):
499 """Print the deps we have seen in the emerge output.
500
501 Args:
502 deps: Dependency tree structure.
503 depth: Allows printing the tree recursively, with indentation.
504 """
505 for entry in sorted(deps):
506 action = deps[entry]["action"]
507 print "%s %s (%s)" % (depth, entry, action)
508 self.PrintTree(deps[entry]["deps"], depth=depth + " ")
509
David James386ccd12011-05-04 20:17:42 -0700510 def GenDependencyGraph(self, deps_tree, deps_info):
David Jamesfcb70ef2011-02-02 16:02:30 -0800511 """Generate a doubly linked dependency graph.
512
513 Args:
514 deps_tree: Dependency tree structure.
515 deps_info: More details on the dependencies.
516 Returns:
517 Deps graph in the form of a dict of packages, with each package
518 specifying a "needs" list and "provides" list.
519 """
520 emerge = self.emerge
David Jamesfcb70ef2011-02-02 16:02:30 -0800521
David Jamesfcb70ef2011-02-02 16:02:30 -0800522 # deps_map is the actual dependency graph.
523 #
524 # Each package specifies a "needs" list and a "provides" list. The "needs"
525 # list indicates which packages we depend on. The "provides" list
526 # indicates the reverse dependencies -- what packages need us.
527 #
528 # We also provide some other information in the dependency graph:
529 # - action: What we're planning on doing with this package. Generally,
530 # "merge", "nomerge", or "uninstall"
David Jamesfcb70ef2011-02-02 16:02:30 -0800531 deps_map = {}
532
533 def ReverseTree(packages):
534 """Convert tree to digraph.
535
536 Take the tree of package -> requirements and reverse it to a digraph of
537 buildable packages -> packages they unblock.
538 Args:
539 packages: Tree(s) of dependencies.
540 Returns:
541 Unsanitized digraph.
542 """
David James8c7e5e32011-06-28 11:26:03 -0700543 binpkg_phases = set(["setup", "preinst", "postinst"])
David James3f778802011-08-25 19:31:45 -0700544 needed_dep_types = set(["blocker", "buildtime", "runtime"])
David Jamesfcb70ef2011-02-02 16:02:30 -0800545 for pkg in packages:
546
547 # Create an entry for the package
548 action = packages[pkg]["action"]
David James8c7e5e32011-06-28 11:26:03 -0700549 default_pkg = {"needs": {}, "provides": set(), "action": action,
550 "nodeps": False, "binary": False}
David Jamesfcb70ef2011-02-02 16:02:30 -0800551 this_pkg = deps_map.setdefault(pkg, default_pkg)
552
David James8c7e5e32011-06-28 11:26:03 -0700553 if pkg in deps_info:
554 this_pkg["idx"] = deps_info[pkg]["idx"]
555
556 # If a package doesn't have any defined phases that might use the
557 # dependent packages (i.e. pkg_setup, pkg_preinst, or pkg_postinst),
558 # we can install this package before its deps are ready.
559 emerge_pkg = self.package_db.get(pkg)
560 if emerge_pkg and emerge_pkg.type_name == "binary":
561 this_pkg["binary"] = True
Mike Frysinger91d7da92013-02-19 15:53:46 -0500562 if 0 <= vercmp(portage.VERSION, "2.1.11.50"):
563 defined_phases = emerge_pkg.defined_phases
564 else:
565 defined_phases = emerge_pkg.metadata.defined_phases
David James8c7e5e32011-06-28 11:26:03 -0700566 defined_binpkg_phases = binpkg_phases.intersection(defined_phases)
567 if not defined_binpkg_phases:
568 this_pkg["nodeps"] = True
569
David Jamesfcb70ef2011-02-02 16:02:30 -0800570 # Create entries for dependencies of this package first.
571 ReverseTree(packages[pkg]["deps"])
572
573 # Add dependencies to this package.
574 for dep, dep_item in packages[pkg]["deps"].iteritems():
David James8c7e5e32011-06-28 11:26:03 -0700575 # We only need to enforce strict ordering of dependencies if the
David James3f778802011-08-25 19:31:45 -0700576 # dependency is a blocker, or is a buildtime or runtime dependency.
577 # (I.e., ignored, optional, and runtime_post dependencies don't
578 # depend on ordering.)
David James8c7e5e32011-06-28 11:26:03 -0700579 dep_types = dep_item["deptypes"]
580 if needed_dep_types.intersection(dep_types):
581 deps_map[dep]["provides"].add(pkg)
582 this_pkg["needs"][dep] = "/".join(dep_types)
David Jamesfcb70ef2011-02-02 16:02:30 -0800583
David James3f778802011-08-25 19:31:45 -0700584 # If there's a blocker, Portage may need to move files from one
585 # package to another, which requires editing the CONTENTS files of
586 # both packages. To avoid race conditions while editing this file,
587 # the two packages must not be installed in parallel, so we can't
588 # safely ignore dependencies. See http://crosbug.com/19328
589 if "blocker" in dep_types:
590 this_pkg["nodeps"] = False
591
David Jamesfcb70ef2011-02-02 16:02:30 -0800592 def FindCycles():
593 """Find cycles in the dependency tree.
594
595 Returns:
596 A dict mapping cyclic packages to a dict of the deps that cause
597 cycles. For each dep that causes cycles, it returns an example
598 traversal of the graph that shows the cycle.
599 """
600
601 def FindCyclesAtNode(pkg, cycles, unresolved, resolved):
602 """Find cycles in cyclic dependencies starting at specified package.
603
604 Args:
605 pkg: Package identifier.
606 cycles: A dict mapping cyclic packages to a dict of the deps that
607 cause cycles. For each dep that causes cycles, it returns an
608 example traversal of the graph that shows the cycle.
609 unresolved: Nodes that have been visited but are not fully processed.
610 resolved: Nodes that have been visited and are fully processed.
611 """
612 pkg_cycles = cycles.get(pkg)
613 if pkg in resolved and not pkg_cycles:
614 # If we already looked at this package, and found no cyclic
615 # dependencies, we can stop now.
616 return
617 unresolved.append(pkg)
618 for dep in deps_map[pkg]["needs"]:
619 if dep in unresolved:
620 idx = unresolved.index(dep)
621 mycycle = unresolved[idx:] + [dep]
David James321490a2012-12-17 12:05:56 -0800622 for i in xrange(len(mycycle) - 1):
David Jamesfcb70ef2011-02-02 16:02:30 -0800623 pkg1, pkg2 = mycycle[i], mycycle[i+1]
624 cycles.setdefault(pkg1, {}).setdefault(pkg2, mycycle)
625 elif not pkg_cycles or dep not in pkg_cycles:
626 # Looks like we haven't seen this edge before.
627 FindCyclesAtNode(dep, cycles, unresolved, resolved)
628 unresolved.pop()
629 resolved.add(pkg)
630
631 cycles, unresolved, resolved = {}, [], set()
632 for pkg in deps_map:
633 FindCyclesAtNode(pkg, cycles, unresolved, resolved)
634 return cycles
635
David James386ccd12011-05-04 20:17:42 -0700636 def RemoveUnusedPackages():
David Jamesfcb70ef2011-02-02 16:02:30 -0800637 """Remove installed packages, propagating dependencies."""
David Jamesfcb70ef2011-02-02 16:02:30 -0800638 # Schedule packages that aren't on the install list for removal
639 rm_pkgs = set(deps_map.keys()) - set(deps_info.keys())
640
David Jamesfcb70ef2011-02-02 16:02:30 -0800641 # Remove the packages we don't want, simplifying the graph and making
642 # it easier for us to crack cycles.
643 for pkg in sorted(rm_pkgs):
644 this_pkg = deps_map[pkg]
645 needs = this_pkg["needs"]
646 provides = this_pkg["provides"]
647 for dep in needs:
648 dep_provides = deps_map[dep]["provides"]
649 dep_provides.update(provides)
650 dep_provides.discard(pkg)
651 dep_provides.discard(dep)
652 for target in provides:
653 target_needs = deps_map[target]["needs"]
654 target_needs.update(needs)
655 target_needs.pop(pkg, None)
656 target_needs.pop(target, None)
657 del deps_map[pkg]
658
659 def PrintCycleBreak(basedep, dep, mycycle):
660 """Print details about a cycle that we are planning on breaking.
661
662 We are breaking a cycle where dep needs basedep. mycycle is an
663 example cycle which contains dep -> basedep."""
664
David Jamesfcb70ef2011-02-02 16:02:30 -0800665 needs = deps_map[dep]["needs"]
666 depinfo = needs.get(basedep, "deleted")
David Jamesfcb70ef2011-02-02 16:02:30 -0800667
David James3f778802011-08-25 19:31:45 -0700668 # It's OK to swap install order for blockers, as long as the two
669 # packages aren't installed in parallel. If there is a cycle, then
670 # we know the packages depend on each other already, so we can drop the
671 # blocker safely without printing a warning.
672 if depinfo == "blocker":
673 return
674
David Jamesfcb70ef2011-02-02 16:02:30 -0800675 # Notify the user that we're breaking a cycle.
676 print "Breaking %s -> %s (%s)" % (dep, basedep, depinfo)
677
678 # Show cycle.
David James321490a2012-12-17 12:05:56 -0800679 for i in xrange(len(mycycle) - 1):
David Jamesfcb70ef2011-02-02 16:02:30 -0800680 pkg1, pkg2 = mycycle[i], mycycle[i+1]
681 needs = deps_map[pkg1]["needs"]
682 depinfo = needs.get(pkg2, "deleted")
683 if pkg1 == dep and pkg2 == basedep:
684 depinfo = depinfo + ", deleting"
685 print " %s -> %s (%s)" % (pkg1, pkg2, depinfo)
686
687 def SanitizeTree():
688 """Remove circular dependencies.
689
690 We prune all dependencies involved in cycles that go against the emerge
691 ordering. This has a nice property: we're guaranteed to merge
692 dependencies in the same order that portage does.
693
694 Because we don't treat any dependencies as "soft" unless they're killed
695 by a cycle, we pay attention to a larger number of dependencies when
696 merging. This hurts performance a bit, but helps reliability.
697 """
698 start = time.time()
699 cycles = FindCycles()
700 while cycles:
701 for dep, mycycles in cycles.iteritems():
702 for basedep, mycycle in mycycles.iteritems():
703 if deps_info[basedep]["idx"] >= deps_info[dep]["idx"]:
Matt Tennant08797302011-10-17 16:18:45 -0700704 if "--quiet" not in emerge.opts:
705 PrintCycleBreak(basedep, dep, mycycle)
David Jamesfcb70ef2011-02-02 16:02:30 -0800706 del deps_map[dep]["needs"][basedep]
707 deps_map[basedep]["provides"].remove(dep)
708 cycles = FindCycles()
709 seconds = time.time() - start
710 if "--quiet" not in emerge.opts and seconds >= 0.1:
711 print "Tree sanitized in %dm%.1fs" % (seconds / 60, seconds % 60)
712
David James8c7e5e32011-06-28 11:26:03 -0700713 def FindRecursiveProvides(pkg, seen):
714 """Find all nodes that require a particular package.
715
716 Assumes that graph is acyclic.
717
718 Args:
719 pkg: Package identifier.
720 seen: Nodes that have been visited so far.
721 """
722 if pkg in seen:
723 return
724 seen.add(pkg)
725 info = deps_map[pkg]
726 info["tprovides"] = info["provides"].copy()
727 for dep in info["provides"]:
728 FindRecursiveProvides(dep, seen)
729 info["tprovides"].update(deps_map[dep]["tprovides"])
730
David Jamesa22906f2011-05-04 19:53:26 -0700731 ReverseTree(deps_tree)
David Jamesa22906f2011-05-04 19:53:26 -0700732
David James386ccd12011-05-04 20:17:42 -0700733 # We need to remove unused packages so that we can use the dependency
734 # ordering of the install process to show us what cycles to crack.
735 RemoveUnusedPackages()
David Jamesfcb70ef2011-02-02 16:02:30 -0800736 SanitizeTree()
David James8c7e5e32011-06-28 11:26:03 -0700737 seen = set()
738 for pkg in deps_map:
739 FindRecursiveProvides(pkg, seen)
David Jamesfcb70ef2011-02-02 16:02:30 -0800740 return deps_map
741
742 def PrintInstallPlan(self, deps_map):
743 """Print an emerge-style install plan.
744
745 The install plan lists what packages we're installing, in order.
746 It's useful for understanding what parallel_emerge is doing.
747
748 Args:
749 deps_map: The dependency graph.
750 """
751
752 def InstallPlanAtNode(target, deps_map):
753 nodes = []
754 nodes.append(target)
755 for dep in deps_map[target]["provides"]:
756 del deps_map[dep]["needs"][target]
757 if not deps_map[dep]["needs"]:
758 nodes.extend(InstallPlanAtNode(dep, deps_map))
759 return nodes
760
761 deps_map = copy.deepcopy(deps_map)
762 install_plan = []
763 plan = set()
764 for target, info in deps_map.iteritems():
765 if not info["needs"] and target not in plan:
766 for item in InstallPlanAtNode(target, deps_map):
767 plan.add(item)
768 install_plan.append(self.package_db[item])
769
770 for pkg in plan:
771 del deps_map[pkg]
772
773 if deps_map:
774 print "Cyclic dependencies:", " ".join(deps_map)
775 PrintDepsMap(deps_map)
776 sys.exit(1)
777
778 self.emerge.depgraph.display(install_plan)
779
780
781def PrintDepsMap(deps_map):
782 """Print dependency graph, for each package list it's prerequisites."""
783 for i in sorted(deps_map):
784 print "%s: (%s) needs" % (i, deps_map[i]["action"])
785 needs = deps_map[i]["needs"]
786 for j in sorted(needs):
787 print " %s" % (j)
788 if not needs:
789 print " no dependencies"
790
791
792class EmergeJobState(object):
793 __slots__ = ["done", "filename", "last_notify_timestamp", "last_output_seek",
794 "last_output_timestamp", "pkgname", "retcode", "start_timestamp",
Brian Harring0be85c62012-03-17 19:52:12 -0700795 "target", "fetch_only"]
David Jamesfcb70ef2011-02-02 16:02:30 -0800796
797 def __init__(self, target, pkgname, done, filename, start_timestamp,
Brian Harring0be85c62012-03-17 19:52:12 -0700798 retcode=None, fetch_only=False):
David Jamesfcb70ef2011-02-02 16:02:30 -0800799
800 # The full name of the target we're building (e.g.
801 # chromeos-base/chromeos-0.0.1-r60)
802 self.target = target
803
804 # The short name of the target we're building (e.g. chromeos-0.0.1-r60)
805 self.pkgname = pkgname
806
807 # Whether the job is done. (True if the job is done; false otherwise.)
808 self.done = done
809
810 # The filename where output is currently stored.
811 self.filename = filename
812
813 # The timestamp of the last time we printed the name of the log file. We
814 # print this at the beginning of the job, so this starts at
815 # start_timestamp.
816 self.last_notify_timestamp = start_timestamp
817
818 # The location (in bytes) of the end of the last complete line we printed.
819 # This starts off at zero. We use this to jump to the right place when we
820 # print output from the same ebuild multiple times.
821 self.last_output_seek = 0
822
823 # The timestamp of the last time we printed output. Since we haven't
824 # printed output yet, this starts at zero.
825 self.last_output_timestamp = 0
826
827 # The return code of our job, if the job is actually finished.
828 self.retcode = retcode
829
Brian Harring0be85c62012-03-17 19:52:12 -0700830 # Was this just a fetch job?
831 self.fetch_only = fetch_only
832
David Jamesfcb70ef2011-02-02 16:02:30 -0800833 # The timestamp when our job started.
834 self.start_timestamp = start_timestamp
835
836
David James321490a2012-12-17 12:05:56 -0800837def KillHandler(_signum, _frame):
David James7358d032011-05-19 10:40:03 -0700838 # Kill self and all subprocesses.
839 os.killpg(0, signal.SIGKILL)
840
David Jamesfcb70ef2011-02-02 16:02:30 -0800841def SetupWorkerSignals():
David James321490a2012-12-17 12:05:56 -0800842 def ExitHandler(_signum, _frame):
David James7358d032011-05-19 10:40:03 -0700843 # Set KILLED flag.
844 KILLED.set()
David James13cead42011-05-18 16:22:01 -0700845
David James7358d032011-05-19 10:40:03 -0700846 # Remove our signal handlers so we don't get called recursively.
847 signal.signal(signal.SIGINT, KillHandler)
848 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -0800849
850 # Ensure that we exit quietly and cleanly, if possible, when we receive
851 # SIGTERM or SIGINT signals. By default, when the user hits CTRL-C, all
852 # of the child processes will print details about KeyboardInterrupt
853 # exceptions, which isn't very helpful.
854 signal.signal(signal.SIGINT, ExitHandler)
855 signal.signal(signal.SIGTERM, ExitHandler)
856
David James6b29d052012-11-02 10:27:27 -0700857def EmergeProcess(output, *args, **kwargs):
David James1ed3e252011-10-05 20:26:15 -0700858 """Merge a package in a subprocess.
859
860 Args:
David James1ed3e252011-10-05 20:26:15 -0700861 output: Temporary file to write output.
David James6b29d052012-11-02 10:27:27 -0700862 *args: Arguments to pass to Scheduler constructor.
863 **kwargs: Keyword arguments to pass to Scheduler constructor.
David James1ed3e252011-10-05 20:26:15 -0700864
865 Returns:
866 The exit code returned by the subprocess.
867 """
868 pid = os.fork()
869 if pid == 0:
870 try:
871 # Sanity checks.
872 if sys.stdout.fileno() != 1: raise Exception("sys.stdout.fileno() != 1")
873 if sys.stderr.fileno() != 2: raise Exception("sys.stderr.fileno() != 2")
874
875 # - Redirect 1 (stdout) and 2 (stderr) at our temporary file.
876 # - Redirect 0 to point at sys.stdin. In this case, sys.stdin
877 # points at a file reading os.devnull, because multiprocessing mucks
878 # with sys.stdin.
879 # - Leave the sys.stdin and output filehandles alone.
880 fd_pipes = {0: sys.stdin.fileno(),
881 1: output.fileno(),
882 2: output.fileno(),
883 sys.stdin.fileno(): sys.stdin.fileno(),
884 output.fileno(): output.fileno()}
885 portage.process._setup_pipes(fd_pipes)
886
887 # Portage doesn't like when sys.stdin.fileno() != 0, so point sys.stdin
888 # at the filehandle we just created in _setup_pipes.
889 if sys.stdin.fileno() != 0:
David James6b29d052012-11-02 10:27:27 -0700890 sys.__stdin__ = sys.stdin = os.fdopen(0, "r")
891
892 scheduler = Scheduler(*args, **kwargs)
893
894 # Enable blocker handling even though we're in --nodeps mode. This
895 # allows us to unmerge the blocker after we've merged the replacement.
896 scheduler._opts_ignore_blockers = frozenset()
David James1ed3e252011-10-05 20:26:15 -0700897
898 # Actually do the merge.
899 retval = scheduler.merge()
900
901 # We catch all exceptions here (including SystemExit, KeyboardInterrupt,
902 # etc) so as to ensure that we don't confuse the multiprocessing module,
903 # which expects that all forked children exit with os._exit().
David James321490a2012-12-17 12:05:56 -0800904 # pylint: disable=W0702
David James1ed3e252011-10-05 20:26:15 -0700905 except:
906 traceback.print_exc(file=output)
907 retval = 1
908 sys.stdout.flush()
909 sys.stderr.flush()
910 output.flush()
911 os._exit(retval)
912 else:
913 # Return the exit code of the subprocess.
914 return os.waitpid(pid, 0)[1]
David Jamesfcb70ef2011-02-02 16:02:30 -0800915
Brian Harring0be85c62012-03-17 19:52:12 -0700916def EmergeWorker(task_queue, job_queue, emerge, package_db, fetch_only=False):
David Jamesfcb70ef2011-02-02 16:02:30 -0800917 """This worker emerges any packages given to it on the task_queue.
918
919 Args:
920 task_queue: The queue of tasks for this worker to do.
921 job_queue: The queue of results from the worker.
922 emerge: An EmergeData() object.
923 package_db: A dict, mapping package ids to portage Package objects.
Brian Harring0be85c62012-03-17 19:52:12 -0700924 fetch_only: A bool, indicating if we should just fetch the target.
David Jamesfcb70ef2011-02-02 16:02:30 -0800925
926 It expects package identifiers to be passed to it via task_queue. When
927 a task is started, it pushes the (target, filename) to the started_queue.
928 The output is stored in filename. When a merge starts or finishes, we push
929 EmergeJobState objects to the job_queue.
930 """
931
932 SetupWorkerSignals()
933 settings, trees, mtimedb = emerge.settings, emerge.trees, emerge.mtimedb
David Jamesdeebd692011-05-09 17:02:52 -0700934
935 # Disable flushing of caches to save on I/O.
David James7a1ea4b2011-10-13 15:06:41 -0700936 root = emerge.settings["ROOT"]
937 vardb = emerge.trees[root]["vartree"].dbapi
938 vardb._flush_cache_enabled = False
Brian Harring0be85c62012-03-17 19:52:12 -0700939 bindb = emerge.trees[root]["bintree"].dbapi
940 # Might be a set, might be a list, might be None; no clue, just use shallow
941 # copy to ensure we can roll it back.
942 original_remotepkgs = copy.copy(bindb.bintree._remotepkgs)
David Jamesdeebd692011-05-09 17:02:52 -0700943
David Jamesfcb70ef2011-02-02 16:02:30 -0800944 opts, spinner = emerge.opts, emerge.spinner
945 opts["--nodeps"] = True
Brian Harring0be85c62012-03-17 19:52:12 -0700946 if fetch_only:
947 opts["--fetchonly"] = True
948
David Jamesfcb70ef2011-02-02 16:02:30 -0800949 while True:
950 # Wait for a new item to show up on the queue. This is a blocking wait,
951 # so if there's nothing to do, we just sit here.
Brian Harring0be85c62012-03-17 19:52:12 -0700952 pkg_state = task_queue.get()
953 if pkg_state is None:
David Jamesfcb70ef2011-02-02 16:02:30 -0800954 # If target is None, this means that the main thread wants us to quit.
955 # The other workers need to exit too, so we'll push the message back on
956 # to the queue so they'll get it too.
Brian Harring0be85c62012-03-17 19:52:12 -0700957 task_queue.put(None)
David Jamesfcb70ef2011-02-02 16:02:30 -0800958 return
David James7358d032011-05-19 10:40:03 -0700959 if KILLED.is_set():
960 return
961
Brian Harring0be85c62012-03-17 19:52:12 -0700962 target = pkg_state.target
963
David Jamesfcb70ef2011-02-02 16:02:30 -0800964 db_pkg = package_db[target]
Brian Harring0be85c62012-03-17 19:52:12 -0700965
966 if db_pkg.type_name == "binary":
967 if not fetch_only and pkg_state.fetched_successfully:
968 # Ensure portage doesn't think our pkg is remote- else it'll force
969 # a redownload of it (even if the on-disk file is fine). In-memory
970 # caching basically, implemented dumbly.
971 bindb.bintree._remotepkgs = None
972 else:
973 bindb.bintree_remotepkgs = original_remotepkgs
974
David Jamesfcb70ef2011-02-02 16:02:30 -0800975 db_pkg.root_config = emerge.root_config
976 install_list = [db_pkg]
977 pkgname = db_pkg.pf
978 output = tempfile.NamedTemporaryFile(prefix=pkgname + "-", delete=False)
David James01b1e0f2012-06-07 17:18:05 -0700979 os.chmod(output.name, 644)
David Jamesfcb70ef2011-02-02 16:02:30 -0800980 start_timestamp = time.time()
Brian Harring0be85c62012-03-17 19:52:12 -0700981 job = EmergeJobState(target, pkgname, False, output.name, start_timestamp,
982 fetch_only=fetch_only)
David Jamesfcb70ef2011-02-02 16:02:30 -0800983 job_queue.put(job)
984 if "--pretend" in opts:
985 retcode = 0
986 else:
David Jamesfcb70ef2011-02-02 16:02:30 -0800987 try:
David James386ccd12011-05-04 20:17:42 -0700988 emerge.scheduler_graph.mergelist = install_list
David James6b29d052012-11-02 10:27:27 -0700989 retcode = EmergeProcess(output, settings, trees, mtimedb, opts,
990 spinner, favorites=emerge.favorites,
991 graph_config=emerge.scheduler_graph)
David Jamesfcb70ef2011-02-02 16:02:30 -0800992 except Exception:
993 traceback.print_exc(file=output)
994 retcode = 1
David James1ed3e252011-10-05 20:26:15 -0700995 output.close()
David Jamesfcb70ef2011-02-02 16:02:30 -0800996
David James7358d032011-05-19 10:40:03 -0700997 if KILLED.is_set():
998 return
999
David Jamesfcb70ef2011-02-02 16:02:30 -08001000 job = EmergeJobState(target, pkgname, True, output.name, start_timestamp,
Brian Harring0be85c62012-03-17 19:52:12 -07001001 retcode, fetch_only=fetch_only)
David Jamesfcb70ef2011-02-02 16:02:30 -08001002 job_queue.put(job)
1003
1004
1005class LinePrinter(object):
1006 """Helper object to print a single line."""
1007
1008 def __init__(self, line):
1009 self.line = line
1010
David James321490a2012-12-17 12:05:56 -08001011 def Print(self, _seek_locations):
David Jamesfcb70ef2011-02-02 16:02:30 -08001012 print self.line
1013
1014
1015class JobPrinter(object):
1016 """Helper object to print output of a job."""
1017
1018 def __init__(self, job, unlink=False):
1019 """Print output of job.
1020
1021 If unlink is True, unlink the job output file when done."""
1022 self.current_time = time.time()
1023 self.job = job
1024 self.unlink = unlink
1025
1026 def Print(self, seek_locations):
1027
1028 job = self.job
1029
1030 # Calculate how long the job has been running.
1031 seconds = self.current_time - job.start_timestamp
1032
1033 # Note that we've printed out the job so far.
1034 job.last_output_timestamp = self.current_time
1035
1036 # Note that we're starting the job
1037 info = "job %s (%dm%.1fs)" % (job.pkgname, seconds / 60, seconds % 60)
1038 last_output_seek = seek_locations.get(job.filename, 0)
1039 if last_output_seek:
1040 print "=== Continue output for %s ===" % info
1041 else:
1042 print "=== Start output for %s ===" % info
1043
1044 # Print actual output from job
1045 f = codecs.open(job.filename, encoding='utf-8', errors='replace')
1046 f.seek(last_output_seek)
1047 prefix = job.pkgname + ":"
1048 for line in f:
1049
1050 # Save off our position in the file
1051 if line and line[-1] == "\n":
1052 last_output_seek = f.tell()
1053 line = line[:-1]
1054
1055 # Print our line
1056 print prefix, line.encode('utf-8', 'replace')
1057 f.close()
1058
1059 # Save our last spot in the file so that we don't print out the same
1060 # location twice.
1061 seek_locations[job.filename] = last_output_seek
1062
1063 # Note end of output section
1064 if job.done:
1065 print "=== Complete: %s ===" % info
1066 else:
1067 print "=== Still running: %s ===" % info
1068
1069 if self.unlink:
1070 os.unlink(job.filename)
1071
1072
1073def PrintWorker(queue):
1074 """A worker that prints stuff to the screen as requested."""
1075
David James321490a2012-12-17 12:05:56 -08001076 def ExitHandler(_signum, _frame):
David James7358d032011-05-19 10:40:03 -07001077 # Set KILLED flag.
1078 KILLED.set()
1079
David Jamesfcb70ef2011-02-02 16:02:30 -08001080 # Switch to default signal handlers so that we'll die after two signals.
David James7358d032011-05-19 10:40:03 -07001081 signal.signal(signal.SIGINT, KillHandler)
1082 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -08001083
1084 # Don't exit on the first SIGINT / SIGTERM, because the parent worker will
1085 # handle it and tell us when we need to exit.
1086 signal.signal(signal.SIGINT, ExitHandler)
1087 signal.signal(signal.SIGTERM, ExitHandler)
1088
1089 # seek_locations is a map indicating the position we are at in each file.
1090 # It starts off empty, but is set by the various Print jobs as we go along
1091 # to indicate where we left off in each file.
1092 seek_locations = {}
1093 while True:
1094 try:
1095 job = queue.get()
1096 if job:
1097 job.Print(seek_locations)
David Jamesbccf8eb2011-07-27 14:06:06 -07001098 sys.stdout.flush()
David Jamesfcb70ef2011-02-02 16:02:30 -08001099 else:
1100 break
1101 except IOError as ex:
1102 if ex.errno == errno.EINTR:
1103 # Looks like we received a signal. Keep printing.
1104 continue
1105 raise
1106
Brian Harring867e2362012-03-17 04:05:17 -07001107
Brian Harring0be85c62012-03-17 19:52:12 -07001108class TargetState(object):
Brian Harring867e2362012-03-17 04:05:17 -07001109
Brian Harring0be85c62012-03-17 19:52:12 -07001110 __slots__ = ("target", "info", "score", "prefetched", "fetched_successfully")
Brian Harring867e2362012-03-17 04:05:17 -07001111
David James321490a2012-12-17 12:05:56 -08001112 def __init__(self, target, info):
Brian Harring867e2362012-03-17 04:05:17 -07001113 self.target, self.info = target, info
Brian Harring0be85c62012-03-17 19:52:12 -07001114 self.fetched_successfully = False
1115 self.prefetched = False
David James321490a2012-12-17 12:05:56 -08001116 self.score = None
Brian Harring867e2362012-03-17 04:05:17 -07001117 self.update_score()
1118
1119 def __cmp__(self, other):
1120 return cmp(self.score, other.score)
1121
1122 def update_score(self):
1123 self.score = (
1124 -len(self.info["tprovides"]),
Brian Harring0be85c62012-03-17 19:52:12 -07001125 len(self.info["needs"]),
Brian Harring11c5eeb2012-03-18 11:02:39 -07001126 not self.info["binary"],
Brian Harring867e2362012-03-17 04:05:17 -07001127 -len(self.info["provides"]),
1128 self.info["idx"],
1129 self.target,
1130 )
1131
1132
1133class ScoredHeap(object):
1134
Brian Harring0be85c62012-03-17 19:52:12 -07001135 __slots__ = ("heap", "_heap_set")
1136
Brian Harring867e2362012-03-17 04:05:17 -07001137 def __init__(self, initial=()):
Brian Harring0be85c62012-03-17 19:52:12 -07001138 self.heap = list()
1139 self._heap_set = set()
1140 if initial:
1141 self.multi_put(initial)
Brian Harring867e2362012-03-17 04:05:17 -07001142
1143 def get(self):
Brian Harring0be85c62012-03-17 19:52:12 -07001144 item = heapq.heappop(self.heap)
1145 self._heap_set.remove(item.target)
1146 return item
Brian Harring867e2362012-03-17 04:05:17 -07001147
Brian Harring0be85c62012-03-17 19:52:12 -07001148 def put(self, item):
1149 if not isinstance(item, TargetState):
1150 raise ValueError("Item %r isn't a TargetState" % (item,))
1151 heapq.heappush(self.heap, item)
1152 self._heap_set.add(item.target)
Brian Harring867e2362012-03-17 04:05:17 -07001153
Brian Harring0be85c62012-03-17 19:52:12 -07001154 def multi_put(self, sequence):
1155 sequence = list(sequence)
1156 self.heap.extend(sequence)
1157 self._heap_set.update(x.target for x in sequence)
Brian Harring867e2362012-03-17 04:05:17 -07001158 self.sort()
1159
David James5c9996d2012-03-24 10:50:46 -07001160 def sort(self):
1161 heapq.heapify(self.heap)
1162
Brian Harring0be85c62012-03-17 19:52:12 -07001163 def __contains__(self, target):
1164 return target in self._heap_set
1165
1166 def __nonzero__(self):
1167 return bool(self.heap)
1168
Brian Harring867e2362012-03-17 04:05:17 -07001169 def __len__(self):
1170 return len(self.heap)
1171
1172
David Jamesfcb70ef2011-02-02 16:02:30 -08001173class EmergeQueue(object):
1174 """Class to schedule emerge jobs according to a dependency graph."""
1175
1176 def __init__(self, deps_map, emerge, package_db, show_output):
1177 # Store the dependency graph.
1178 self._deps_map = deps_map
Brian Harring0be85c62012-03-17 19:52:12 -07001179 self._state_map = {}
David Jamesfcb70ef2011-02-02 16:02:30 -08001180 # Initialize the running queue to empty
Brian Harring0be85c62012-03-17 19:52:12 -07001181 self._build_jobs = {}
1182 self._build_ready = ScoredHeap()
1183 self._fetch_jobs = {}
1184 self._fetch_ready = ScoredHeap()
David Jamesfcb70ef2011-02-02 16:02:30 -08001185 # List of total package installs represented in deps_map.
1186 install_jobs = [x for x in deps_map if deps_map[x]["action"] == "merge"]
1187 self._total_jobs = len(install_jobs)
1188 self._show_output = show_output
1189
1190 if "--pretend" in emerge.opts:
1191 print "Skipping merge because of --pretend mode."
1192 sys.exit(0)
1193
David James7358d032011-05-19 10:40:03 -07001194 # Set a process group so we can easily terminate all children.
1195 os.setsid()
1196
David Jamesfcb70ef2011-02-02 16:02:30 -08001197 # Setup scheduler graph object. This is used by the child processes
1198 # to help schedule jobs.
1199 emerge.scheduler_graph = emerge.depgraph.schedulerGraph()
1200
1201 # Calculate how many jobs we can run in parallel. We don't want to pass
1202 # the --jobs flag over to emerge itself, because that'll tell emerge to
1203 # hide its output, and said output is quite useful for debugging hung
1204 # jobs.
1205 procs = min(self._total_jobs,
1206 emerge.opts.pop("--jobs", multiprocessing.cpu_count()))
David James7746e112013-02-24 19:32:50 -08001207 self._build_procs = self._fetch_procs = max(1, procs)
David James8c7e5e32011-06-28 11:26:03 -07001208 self._load_avg = emerge.opts.pop("--load-average", None)
David Jamesfcb70ef2011-02-02 16:02:30 -08001209 self._job_queue = multiprocessing.Queue()
1210 self._print_queue = multiprocessing.Queue()
Brian Harring0be85c62012-03-17 19:52:12 -07001211
1212 self._fetch_queue = multiprocessing.Queue()
1213 args = (self._fetch_queue, self._job_queue, emerge, package_db, True)
1214 self._fetch_pool = multiprocessing.Pool(self._fetch_procs, EmergeWorker,
1215 args)
1216
1217 self._build_queue = multiprocessing.Queue()
1218 args = (self._build_queue, self._job_queue, emerge, package_db)
1219 self._build_pool = multiprocessing.Pool(self._build_procs, EmergeWorker,
1220 args)
1221
David Jamesfcb70ef2011-02-02 16:02:30 -08001222 self._print_worker = multiprocessing.Process(target=PrintWorker,
1223 args=[self._print_queue])
1224 self._print_worker.start()
1225
1226 # Initialize the failed queue to empty.
1227 self._retry_queue = []
1228 self._failed = set()
1229
David Jamesfcb70ef2011-02-02 16:02:30 -08001230 # Setup an exit handler so that we print nice messages if we are
1231 # terminated.
1232 self._SetupExitHandler()
1233
1234 # Schedule our jobs.
Brian Harring0be85c62012-03-17 19:52:12 -07001235 self._state_map.update(
1236 (pkg, TargetState(pkg, data)) for pkg, data in deps_map.iteritems())
1237 self._fetch_ready.multi_put(self._state_map.itervalues())
David Jamesfcb70ef2011-02-02 16:02:30 -08001238
1239 def _SetupExitHandler(self):
1240
David James321490a2012-12-17 12:05:56 -08001241 def ExitHandler(signum, _frame):
David James7358d032011-05-19 10:40:03 -07001242 # Set KILLED flag.
1243 KILLED.set()
David Jamesfcb70ef2011-02-02 16:02:30 -08001244
1245 # Kill our signal handlers so we don't get called recursively
David James7358d032011-05-19 10:40:03 -07001246 signal.signal(signal.SIGINT, KillHandler)
1247 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -08001248
1249 # Print our current job status
Brian Harring0be85c62012-03-17 19:52:12 -07001250 for job in self._build_jobs.itervalues():
David Jamesfcb70ef2011-02-02 16:02:30 -08001251 if job:
1252 self._print_queue.put(JobPrinter(job, unlink=True))
1253
1254 # Notify the user that we are exiting
1255 self._Print("Exiting on signal %s" % signum)
David James7358d032011-05-19 10:40:03 -07001256 self._print_queue.put(None)
1257 self._print_worker.join()
David Jamesfcb70ef2011-02-02 16:02:30 -08001258
1259 # Kill child threads, then exit.
David James7358d032011-05-19 10:40:03 -07001260 os.killpg(0, signal.SIGKILL)
David Jamesfcb70ef2011-02-02 16:02:30 -08001261 sys.exit(1)
1262
1263 # Print out job status when we are killed
1264 signal.signal(signal.SIGINT, ExitHandler)
1265 signal.signal(signal.SIGTERM, ExitHandler)
1266
Brian Harring0be85c62012-03-17 19:52:12 -07001267 def _Schedule(self, pkg_state):
David Jamesfcb70ef2011-02-02 16:02:30 -08001268 # We maintain a tree of all deps, if this doesn't need
David James8c7e5e32011-06-28 11:26:03 -07001269 # to be installed just free up its children and continue.
David Jamesfcb70ef2011-02-02 16:02:30 -08001270 # It is possible to reinstall deps of deps, without reinstalling
1271 # first level deps, like so:
1272 # chromeos (merge) -> eselect (nomerge) -> python (merge)
Brian Harring0be85c62012-03-17 19:52:12 -07001273 this_pkg = pkg_state.info
1274 target = pkg_state.target
1275 if pkg_state.info is not None:
1276 if this_pkg["action"] == "nomerge":
1277 self._Finish(target)
1278 elif target not in self._build_jobs:
1279 # Kick off the build if it's marked to be built.
1280 self._build_jobs[target] = None
1281 self._build_queue.put(pkg_state)
1282 return True
David Jamesfcb70ef2011-02-02 16:02:30 -08001283
David James8c7e5e32011-06-28 11:26:03 -07001284 def _ScheduleLoop(self):
1285 # If the current load exceeds our desired load average, don't schedule
1286 # more than one job.
1287 if self._load_avg and os.getloadavg()[0] > self._load_avg:
1288 needed_jobs = 1
1289 else:
Brian Harring0be85c62012-03-17 19:52:12 -07001290 needed_jobs = self._build_procs
David James8c7e5e32011-06-28 11:26:03 -07001291
1292 # Schedule more jobs.
Brian Harring0be85c62012-03-17 19:52:12 -07001293 while self._build_ready and len(self._build_jobs) < needed_jobs:
1294 state = self._build_ready.get()
1295 if state.target not in self._failed:
1296 self._Schedule(state)
David Jamesfcb70ef2011-02-02 16:02:30 -08001297
1298 def _Print(self, line):
1299 """Print a single line."""
1300 self._print_queue.put(LinePrinter(line))
1301
1302 def _Status(self):
1303 """Print status."""
1304 current_time = time.time()
1305 no_output = True
1306
1307 # Print interim output every minute if --show-output is used. Otherwise,
1308 # print notifications about running packages every 2 minutes, and print
1309 # full output for jobs that have been running for 60 minutes or more.
1310 if self._show_output:
1311 interval = 60
1312 notify_interval = 0
1313 else:
1314 interval = 60 * 60
1315 notify_interval = 60 * 2
David James321490a2012-12-17 12:05:56 -08001316 for job in self._build_jobs.itervalues():
David Jamesfcb70ef2011-02-02 16:02:30 -08001317 if job:
1318 last_timestamp = max(job.start_timestamp, job.last_output_timestamp)
1319 if last_timestamp + interval < current_time:
1320 self._print_queue.put(JobPrinter(job))
1321 job.last_output_timestamp = current_time
1322 no_output = False
1323 elif (notify_interval and
1324 job.last_notify_timestamp + notify_interval < current_time):
1325 job_seconds = current_time - job.start_timestamp
1326 args = (job.pkgname, job_seconds / 60, job_seconds % 60, job.filename)
1327 info = "Still building %s (%dm%.1fs). Logs in %s" % args
1328 job.last_notify_timestamp = current_time
1329 self._Print(info)
1330 no_output = False
1331
1332 # If we haven't printed any messages yet, print a general status message
1333 # here.
1334 if no_output:
1335 seconds = current_time - GLOBAL_START
Brian Harring0be85c62012-03-17 19:52:12 -07001336 fjobs, fready = len(self._fetch_jobs), len(self._fetch_ready)
1337 bjobs, bready = len(self._build_jobs), len(self._build_ready)
1338 retries = len(self._retry_queue)
1339 pending = max(0, len(self._deps_map) - fjobs - bjobs)
1340 line = "Pending %s/%s, " % (pending, self._total_jobs)
1341 if fjobs or fready:
1342 line += "Fetching %s/%s, " % (fjobs, fready + fjobs)
1343 if bjobs or bready or retries:
1344 line += "Building %s/%s, " % (bjobs, bready + bjobs)
1345 if retries:
1346 line += "Retrying %s, " % (retries,)
David James8c7e5e32011-06-28 11:26:03 -07001347 load = " ".join(str(x) for x in os.getloadavg())
Brian Harring0be85c62012-03-17 19:52:12 -07001348 line += ("[Time %dm%.1fs Load %s]" % (seconds/60, seconds %60, load))
1349 self._Print(line)
David Jamesfcb70ef2011-02-02 16:02:30 -08001350
1351 def _Finish(self, target):
David James8c7e5e32011-06-28 11:26:03 -07001352 """Mark a target as completed and unblock dependencies."""
1353 this_pkg = self._deps_map[target]
1354 if this_pkg["needs"] and this_pkg["nodeps"]:
1355 # We got installed, but our deps have not been installed yet. Dependent
1356 # packages should only be installed when our needs have been fully met.
1357 this_pkg["action"] = "nomerge"
1358 else:
David James8c7e5e32011-06-28 11:26:03 -07001359 for dep in this_pkg["provides"]:
1360 dep_pkg = self._deps_map[dep]
Brian Harring0be85c62012-03-17 19:52:12 -07001361 state = self._state_map[dep]
David James8c7e5e32011-06-28 11:26:03 -07001362 del dep_pkg["needs"][target]
Brian Harring0be85c62012-03-17 19:52:12 -07001363 state.update_score()
1364 if not state.prefetched:
1365 if dep in self._fetch_ready:
1366 # If it's not currently being fetched, update the prioritization
1367 self._fetch_ready.sort()
1368 elif not dep_pkg["needs"]:
David James8c7e5e32011-06-28 11:26:03 -07001369 if dep_pkg["nodeps"] and dep_pkg["action"] == "nomerge":
1370 self._Finish(dep)
1371 else:
Brian Harring0be85c62012-03-17 19:52:12 -07001372 self._build_ready.put(self._state_map[dep])
David James8c7e5e32011-06-28 11:26:03 -07001373 self._deps_map.pop(target)
David Jamesfcb70ef2011-02-02 16:02:30 -08001374
1375 def _Retry(self):
David James8c7e5e32011-06-28 11:26:03 -07001376 while self._retry_queue:
Brian Harring0be85c62012-03-17 19:52:12 -07001377 state = self._retry_queue.pop(0)
1378 if self._Schedule(state):
1379 self._Print("Retrying emerge of %s." % state.target)
David James8c7e5e32011-06-28 11:26:03 -07001380 break
David Jamesfcb70ef2011-02-02 16:02:30 -08001381
Brian Harringa43f5952012-04-12 01:19:34 -07001382 def _Shutdown(self):
David Jamesfcb70ef2011-02-02 16:02:30 -08001383 # Tell emerge workers to exit. They all exit when 'None' is pushed
1384 # to the queue.
Brian Harring0be85c62012-03-17 19:52:12 -07001385
Brian Harringa43f5952012-04-12 01:19:34 -07001386 # Shutdown the workers first; then jobs (which is how they feed things back)
1387 # then finally the print queue.
Brian Harring0be85c62012-03-17 19:52:12 -07001388
Brian Harringa43f5952012-04-12 01:19:34 -07001389 def _stop(queue, pool):
1390 if pool is None:
1391 return
1392 try:
1393 queue.put(None)
1394 pool.close()
1395 pool.join()
1396 finally:
1397 pool.terminate()
Brian Harring0be85c62012-03-17 19:52:12 -07001398
Brian Harringa43f5952012-04-12 01:19:34 -07001399 _stop(self._fetch_queue, self._fetch_pool)
1400 self._fetch_queue = self._fetch_pool = None
Brian Harring0be85c62012-03-17 19:52:12 -07001401
Brian Harringa43f5952012-04-12 01:19:34 -07001402 _stop(self._build_queue, self._build_pool)
1403 self._build_queue = self._build_pool = None
1404
1405 if self._job_queue is not None:
1406 self._job_queue.close()
1407 self._job_queue = None
David Jamesfcb70ef2011-02-02 16:02:30 -08001408
1409 # Now that our workers are finished, we can kill the print queue.
Brian Harringa43f5952012-04-12 01:19:34 -07001410 if self._print_worker is not None:
1411 try:
1412 self._print_queue.put(None)
1413 self._print_queue.close()
1414 self._print_worker.join()
1415 finally:
1416 self._print_worker.terminate()
1417 self._print_queue = self._print_worker = None
David Jamesfcb70ef2011-02-02 16:02:30 -08001418
1419 def Run(self):
1420 """Run through the scheduled ebuilds.
1421
1422 Keep running so long as we have uninstalled packages in the
1423 dependency graph to merge.
1424 """
Brian Harringa43f5952012-04-12 01:19:34 -07001425 if not self._deps_map:
1426 return
1427
Brian Harring0be85c62012-03-17 19:52:12 -07001428 # Start the fetchers.
1429 for _ in xrange(min(self._fetch_procs, len(self._fetch_ready))):
1430 state = self._fetch_ready.get()
1431 self._fetch_jobs[state.target] = None
1432 self._fetch_queue.put(state)
1433
1434 # Print an update, then get going.
1435 self._Status()
1436
David Jamese703d0f2012-01-12 16:27:45 -08001437 retried = set()
David Jamesfcb70ef2011-02-02 16:02:30 -08001438 while self._deps_map:
1439 # Check here that we are actually waiting for something.
Brian Harring0be85c62012-03-17 19:52:12 -07001440 if (self._build_queue.empty() and
David Jamesfcb70ef2011-02-02 16:02:30 -08001441 self._job_queue.empty() and
Brian Harring0be85c62012-03-17 19:52:12 -07001442 not self._fetch_jobs and
1443 not self._fetch_ready and
1444 not self._build_jobs and
1445 not self._build_ready and
David Jamesfcb70ef2011-02-02 16:02:30 -08001446 self._deps_map):
1447 # If we have failed on a package, retry it now.
1448 if self._retry_queue:
1449 self._Retry()
1450 else:
David Jamesfcb70ef2011-02-02 16:02:30 -08001451 # Tell the user why we're exiting.
1452 if self._failed:
Mike Frysingerf2ff9172012-11-01 18:47:41 -04001453 print 'Packages failed:\n\t%s' % '\n\t'.join(self._failed)
David James0eae23e2012-07-03 15:04:25 -07001454 status_file = os.environ.get("PARALLEL_EMERGE_STATUS_FILE")
1455 if status_file:
David James321490a2012-12-17 12:05:56 -08001456 failed_pkgs = set(portage.versions.cpv_getkey(x)
1457 for x in self._failed)
David James0eae23e2012-07-03 15:04:25 -07001458 with open(status_file, "a") as f:
1459 f.write("%s\n" % " ".join(failed_pkgs))
David Jamesfcb70ef2011-02-02 16:02:30 -08001460 else:
1461 print "Deadlock! Circular dependencies!"
1462 sys.exit(1)
1463
David James321490a2012-12-17 12:05:56 -08001464 for _ in xrange(12):
David Jamesa74289a2011-08-12 10:41:24 -07001465 try:
1466 job = self._job_queue.get(timeout=5)
1467 break
1468 except Queue.Empty:
1469 # Check if any more jobs can be scheduled.
1470 self._ScheduleLoop()
1471 else:
Brian Harring706747c2012-03-16 03:04:31 -07001472 # Print an update every 60 seconds.
David Jamesfcb70ef2011-02-02 16:02:30 -08001473 self._Status()
1474 continue
1475
1476 target = job.target
1477
Brian Harring0be85c62012-03-17 19:52:12 -07001478 if job.fetch_only:
1479 if not job.done:
1480 self._fetch_jobs[job.target] = job
1481 else:
1482 state = self._state_map[job.target]
1483 state.prefetched = True
1484 state.fetched_successfully = (job.retcode == 0)
1485 del self._fetch_jobs[job.target]
1486 self._Print("Fetched %s in %2.2fs"
1487 % (target, time.time() - job.start_timestamp))
1488
1489 if self._show_output or job.retcode != 0:
1490 self._print_queue.put(JobPrinter(job, unlink=True))
1491 else:
1492 os.unlink(job.filename)
1493 # Failure or not, let build work with it next.
1494 if not self._deps_map[job.target]["needs"]:
1495 self._build_ready.put(state)
1496 self._ScheduleLoop()
1497
1498 if self._fetch_ready:
1499 state = self._fetch_ready.get()
1500 self._fetch_queue.put(state)
1501 self._fetch_jobs[state.target] = None
1502 else:
1503 # Minor optimization; shut down fetchers early since we know
1504 # the queue is empty.
1505 self._fetch_queue.put(None)
1506 continue
1507
David Jamesfcb70ef2011-02-02 16:02:30 -08001508 if not job.done:
Brian Harring0be85c62012-03-17 19:52:12 -07001509 self._build_jobs[target] = job
David Jamesfcb70ef2011-02-02 16:02:30 -08001510 self._Print("Started %s (logged in %s)" % (target, job.filename))
1511 continue
1512
1513 # Print output of job
1514 if self._show_output or job.retcode != 0:
1515 self._print_queue.put(JobPrinter(job, unlink=True))
1516 else:
1517 os.unlink(job.filename)
Brian Harring0be85c62012-03-17 19:52:12 -07001518 del self._build_jobs[target]
David Jamesfcb70ef2011-02-02 16:02:30 -08001519
1520 seconds = time.time() - job.start_timestamp
1521 details = "%s (in %dm%.1fs)" % (target, seconds / 60, seconds % 60)
David James32420cc2011-08-25 21:32:46 -07001522 previously_failed = target in self._failed
David Jamesfcb70ef2011-02-02 16:02:30 -08001523
1524 # Complain if necessary.
1525 if job.retcode != 0:
1526 # Handle job failure.
David James32420cc2011-08-25 21:32:46 -07001527 if previously_failed:
David Jamesfcb70ef2011-02-02 16:02:30 -08001528 # If this job has failed previously, give up.
1529 self._Print("Failed %s. Your build has failed." % details)
1530 else:
1531 # Queue up this build to try again after a long while.
David Jamese703d0f2012-01-12 16:27:45 -08001532 retried.add(target)
Brian Harring0be85c62012-03-17 19:52:12 -07001533 self._retry_queue.append(self._state_map[target])
David Jamesfcb70ef2011-02-02 16:02:30 -08001534 self._failed.add(target)
1535 self._Print("Failed %s, retrying later." % details)
1536 else:
David James32420cc2011-08-25 21:32:46 -07001537 if previously_failed:
1538 # Remove target from list of failed packages.
1539 self._failed.remove(target)
1540
1541 self._Print("Completed %s" % details)
1542
1543 # Mark as completed and unblock waiting ebuilds.
1544 self._Finish(target)
1545
1546 if previously_failed and self._retry_queue:
David Jamesfcb70ef2011-02-02 16:02:30 -08001547 # If we have successfully retried a failed package, and there
1548 # are more failed packages, try the next one. We will only have
1549 # one retrying package actively running at a time.
1550 self._Retry()
1551
David Jamesfcb70ef2011-02-02 16:02:30 -08001552
David James8c7e5e32011-06-28 11:26:03 -07001553 # Schedule pending jobs and print an update.
1554 self._ScheduleLoop()
1555 self._Status()
David Jamesfcb70ef2011-02-02 16:02:30 -08001556
David Jamese703d0f2012-01-12 16:27:45 -08001557 # If packages were retried, output a warning.
1558 if retried:
1559 self._Print("")
1560 self._Print("WARNING: The following packages failed the first time,")
1561 self._Print("but succeeded upon retry. This might indicate incorrect")
1562 self._Print("dependencies.")
1563 for pkg in retried:
1564 self._Print(" %s" % pkg)
1565 self._Print("@@@STEP_WARNINGS@@@")
1566 self._Print("")
1567
David Jamesfcb70ef2011-02-02 16:02:30 -08001568 # Tell child threads to exit.
1569 self._Print("Merge complete")
David Jamesfcb70ef2011-02-02 16:02:30 -08001570
1571
Brian Harring30675052012-02-29 12:18:22 -08001572def main(argv):
Brian Harring8294d652012-05-23 02:20:52 -07001573 try:
1574 return real_main(argv)
1575 finally:
1576 # Work around multiprocessing sucking and not cleaning up after itself.
1577 # http://bugs.python.org/issue4106;
1578 # Step one; ensure GC is ran *prior* to the VM starting shutdown.
1579 gc.collect()
1580 # Step two; go looking for those threads and try to manually reap
1581 # them if we can.
1582 for x in threading.enumerate():
1583 # Filter on the name, and ident; if ident is None, the thread
1584 # wasn't started.
1585 if x.name == 'QueueFeederThread' and x.ident is not None:
1586 x.join(1)
David Jamesfcb70ef2011-02-02 16:02:30 -08001587
Brian Harring8294d652012-05-23 02:20:52 -07001588
1589def real_main(argv):
Brian Harring30675052012-02-29 12:18:22 -08001590 parallel_emerge_args = argv[:]
David Jamesfcb70ef2011-02-02 16:02:30 -08001591 deps = DepGraphGenerator()
Brian Harring30675052012-02-29 12:18:22 -08001592 deps.Initialize(parallel_emerge_args)
David Jamesfcb70ef2011-02-02 16:02:30 -08001593 emerge = deps.emerge
1594
1595 if emerge.action is not None:
Brian Harring30675052012-02-29 12:18:22 -08001596 argv = deps.ParseParallelEmergeArgs(argv)
Brian Harring8294d652012-05-23 02:20:52 -07001597 return emerge_main(argv)
David Jamesfcb70ef2011-02-02 16:02:30 -08001598 elif not emerge.cmdline_packages:
1599 Usage()
Brian Harring8294d652012-05-23 02:20:52 -07001600 return 1
David Jamesfcb70ef2011-02-02 16:02:30 -08001601
1602 # Unless we're in pretend mode, there's not much point running without
1603 # root access. We need to be able to install packages.
1604 #
1605 # NOTE: Even if you're running --pretend, it's a good idea to run
1606 # parallel_emerge with root access so that portage can write to the
1607 # dependency cache. This is important for performance.
David James321490a2012-12-17 12:05:56 -08001608 if "--pretend" not in emerge.opts and portage.data.secpass < 2:
David Jamesfcb70ef2011-02-02 16:02:30 -08001609 print "parallel_emerge: superuser access is required."
Brian Harring8294d652012-05-23 02:20:52 -07001610 return 1
David Jamesfcb70ef2011-02-02 16:02:30 -08001611
1612 if "--quiet" not in emerge.opts:
1613 cmdline_packages = " ".join(emerge.cmdline_packages)
David Jamesfcb70ef2011-02-02 16:02:30 -08001614 print "Starting fast-emerge."
1615 print " Building package %s on %s" % (cmdline_packages,
1616 deps.board or "root")
David Jamesfcb70ef2011-02-02 16:02:30 -08001617
David James386ccd12011-05-04 20:17:42 -07001618 deps_tree, deps_info = deps.GenDependencyTree()
David Jamesfcb70ef2011-02-02 16:02:30 -08001619
1620 # You want me to be verbose? I'll give you two trees! Twice as much value.
1621 if "--tree" in emerge.opts and "--verbose" in emerge.opts:
1622 deps.PrintTree(deps_tree)
1623
David James386ccd12011-05-04 20:17:42 -07001624 deps_graph = deps.GenDependencyGraph(deps_tree, deps_info)
David Jamesfcb70ef2011-02-02 16:02:30 -08001625
1626 # OK, time to print out our progress so far.
1627 deps.PrintInstallPlan(deps_graph)
1628 if "--tree" in emerge.opts:
1629 PrintDepsMap(deps_graph)
1630
1631 # Are we upgrading portage? If so, and there are more packages to merge,
1632 # schedule a restart of parallel_emerge to merge the rest. This ensures that
1633 # we pick up all updates to portage settings before merging any more
1634 # packages.
1635 portage_upgrade = False
1636 root = emerge.settings["ROOT"]
1637 final_db = emerge.depgraph._dynamic_config.mydbapi[root]
1638 if root == "/":
1639 for db_pkg in final_db.match_pkgs("sys-apps/portage"):
1640 portage_pkg = deps_graph.get(db_pkg.cpv)
David James0ff16f22012-11-02 14:18:07 -07001641 if portage_pkg:
David Jamesfcb70ef2011-02-02 16:02:30 -08001642 portage_upgrade = True
1643 if "--quiet" not in emerge.opts:
1644 print "Upgrading portage first, then restarting..."
1645
David James0ff16f22012-11-02 14:18:07 -07001646 # Upgrade Portage first, then the rest of the packages.
1647 #
1648 # In order to grant the child permission to run setsid, we need to run sudo
1649 # again. We preserve SUDO_USER here in case an ebuild depends on it.
1650 if portage_upgrade:
1651 # Calculate what arguments to use when re-invoking.
1652 args = ["sudo", "-E", "SUDO_USER=%s" % os.environ.get("SUDO_USER", "")]
1653 args += [os.path.abspath(sys.argv[0])] + parallel_emerge_args
1654 args += ["--exclude=sys-apps/portage"]
1655
1656 # First upgrade Portage.
1657 passthrough_args = ("--quiet", "--pretend", "--verbose")
1658 emerge_args = [k for k in emerge.opts if k in passthrough_args]
1659 ret = emerge_main(emerge_args + ["portage"])
1660 if ret != 0:
1661 return ret
1662
1663 # Now upgrade the rest.
1664 os.execvp(args[0], args)
1665
David Jamesfcb70ef2011-02-02 16:02:30 -08001666 # Run the queued emerges.
1667 scheduler = EmergeQueue(deps_graph, emerge, deps.package_db, deps.show_output)
Brian Harringa43f5952012-04-12 01:19:34 -07001668 try:
1669 scheduler.Run()
1670 finally:
1671 scheduler._Shutdown()
David James97ce8902011-08-16 09:51:05 -07001672 scheduler = None
David Jamesfcb70ef2011-02-02 16:02:30 -08001673
Mike Frysingerd20a6e22012-10-04 19:01:10 -04001674 clean_logs(emerge.settings)
1675
David Jamesfcb70ef2011-02-02 16:02:30 -08001676 print "Done"
Brian Harring8294d652012-05-23 02:20:52 -07001677 return 0