blob: 53cad0fcd10bf9969c1b8a40037ba6aa2e3e2ffe [file] [log] [blame]
David Jamesfcb70ef2011-02-02 16:02:30 -08001#!/usr/bin/python2.6
2# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
3# 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
12Basic operation:
13 Runs 'emerge -p --debug' to display dependencies, and stores a
14 dependency graph. All non-blocked packages are launched in parallel,
15 as 'emerge --nodeps package' with any blocked packages being emerged
16 immediately upon deps being met.
17
18 For this to work effectively, /usr/lib/portage/pym/portage/locks.py
19 must be stubbed out, preventing portage from slowing itself with
20 unneccesary locking, as this script ensures that emerge is run in such
21 a way that common resources are never in conflict. This is controlled
22 by an environment variable PORTAGE_LOCKS set in parallel emerge
23 subprocesses.
24
25 Parallel Emerge unlocks two things during operation, here's what you
26 must do to keep this safe:
27 * Storage dir containing binary packages. - Don't emerge new
28 packages while installing the existing ones.
29 * Portage database - You must not examine deps while modifying the
30 database. Therefore you may only parallelize "-p" read only access,
31 or "--nodeps" write only access.
32 Caveats:
33 * Some ebuild packages have incorrectly specified deps, and running
34 them in parallel is more likely to bring out these failures.
35 * Some ebuilds (especially the build part) have complex dependencies
36 that are not captured well by this script (it may be necessary to
37 install an old package to build, but then install a newer version
38 of the same package for a runtime dep).
39"""
40
41import codecs
42import copy
43import errno
David James8c7e5e32011-06-28 11:26:03 -070044import heapq
David Jamesfcb70ef2011-02-02 16:02:30 -080045import multiprocessing
46import os
47import Queue
David Jamesfcb70ef2011-02-02 16:02:30 -080048import signal
49import sys
50import tempfile
51import time
52import traceback
David Jamesfcb70ef2011-02-02 16:02:30 -080053
54# If PORTAGE_USERNAME isn't specified, scrape it from the $HOME variable. On
55# Chromium OS, the default "portage" user doesn't have the necessary
56# permissions. It'd be easier if we could default to $USERNAME, but $USERNAME
57# is "root" here because we get called through sudo.
58#
59# We need to set this before importing any portage modules, because portage
60# looks up "PORTAGE_USERNAME" at import time.
61#
62# NOTE: .bashrc sets PORTAGE_USERNAME = $USERNAME, so most people won't
63# encounter this case unless they have an old chroot or blow away the
64# environment by running sudo without the -E specifier.
65if "PORTAGE_USERNAME" not in os.environ:
66 homedir = os.environ.get("HOME")
67 if homedir:
68 os.environ["PORTAGE_USERNAME"] = os.path.basename(homedir)
69
70# Portage doesn't expose dependency trees in its public API, so we have to
71# make use of some private APIs here. These modules are found under
72# /usr/lib/portage/pym/.
73#
74# TODO(davidjames): Update Portage to expose public APIs for these features.
75from _emerge.actions import adjust_configs
76from _emerge.actions import load_emerge_config
77from _emerge.create_depgraph_params import create_depgraph_params
David James386ccd12011-05-04 20:17:42 -070078from _emerge.depgraph import backtrack_depgraph
David Jamesfcb70ef2011-02-02 16:02:30 -080079from _emerge.main import emerge_main
80from _emerge.main import parse_opts
81from _emerge.Package import Package
82from _emerge.Scheduler import Scheduler
83from _emerge.SetArg import SetArg
84from _emerge.stdout_spinner import stdout_spinner
David James386ccd12011-05-04 20:17:42 -070085from portage._global_updates import _global_updates
86from portage.versions import vercmp
David Jamesfcb70ef2011-02-02 16:02:30 -080087import portage
88import portage.debug
David Jamesfcb70ef2011-02-02 16:02:30 -080089
David James386ccd12011-05-04 20:17:42 -070090NEW_PORTAGE = (0 <= vercmp(portage.VERSION, "2.1.9.46-r2"))
David Jamesfcb70ef2011-02-02 16:02:30 -080091
92def Usage():
93 """Print usage."""
94 print "Usage:"
David James386ccd12011-05-04 20:17:42 -070095 print " ./parallel_emerge [--board=BOARD] [--workon=PKGS]"
David Jamesfcb70ef2011-02-02 16:02:30 -080096 print " [--rebuild] [emerge args] package"
97 print
98 print "Packages specified as workon packages are always built from source."
David Jamesfcb70ef2011-02-02 16:02:30 -080099 print
100 print "The --workon argument is mainly useful when you want to build and"
101 print "install packages that you are working on unconditionally, but do not"
102 print "to have to rev the package to indicate you want to build it from"
103 print "source. The build_packages script will automatically supply the"
104 print "workon argument to emerge, ensuring that packages selected using"
105 print "cros-workon are rebuilt."
106 print
107 print "The --rebuild option rebuilds packages whenever their dependencies"
108 print "are changed. This ensures that your build is correct."
109 sys.exit(1)
110
111
David Jamesfcb70ef2011-02-02 16:02:30 -0800112# Global start time
113GLOBAL_START = time.time()
114
David James7358d032011-05-19 10:40:03 -0700115# Whether process has been killed by a signal.
116KILLED = multiprocessing.Event()
117
David Jamesfcb70ef2011-02-02 16:02:30 -0800118
119class EmergeData(object):
120 """This simple struct holds various emerge variables.
121
122 This struct helps us easily pass emerge variables around as a unit.
123 These variables are used for calculating dependencies and installing
124 packages.
125 """
126
David Jamesbf1e3442011-05-28 07:44:20 -0700127 __slots__ = ["action", "cmdline_packages", "depgraph", "favorites",
128 "mtimedb", "opts", "root_config", "scheduler_graph",
129 "settings", "spinner", "trees"]
David Jamesfcb70ef2011-02-02 16:02:30 -0800130
131 def __init__(self):
132 # The action the user requested. If the user is installing packages, this
133 # is None. If the user is doing anything other than installing packages,
134 # this will contain the action name, which will map exactly to the
135 # long-form name of the associated emerge option.
136 #
137 # Example: If you call parallel_emerge --unmerge package, the action name
138 # will be "unmerge"
139 self.action = None
140
141 # The list of packages the user passed on the command-line.
142 self.cmdline_packages = None
143
144 # The emerge dependency graph. It'll contain all the packages involved in
145 # this merge, along with their versions.
146 self.depgraph = None
147
David Jamesbf1e3442011-05-28 07:44:20 -0700148 # The list of candidates to add to the world file.
149 self.favorites = None
150
David Jamesfcb70ef2011-02-02 16:02:30 -0800151 # A dict of the options passed to emerge. This dict has been cleaned up
152 # a bit by parse_opts, so that it's a bit easier for the emerge code to
153 # look at the options.
154 #
155 # Emerge takes a few shortcuts in its cleanup process to make parsing of
156 # the options dict easier. For example, if you pass in "--usepkg=n", the
157 # "--usepkg" flag is just left out of the dictionary altogether. Because
158 # --usepkg=n is the default, this makes parsing easier, because emerge
159 # can just assume that if "--usepkg" is in the dictionary, it's enabled.
160 #
161 # These cleanup processes aren't applied to all options. For example, the
162 # --with-bdeps flag is passed in as-is. For a full list of the cleanups
163 # applied by emerge, see the parse_opts function in the _emerge.main
164 # package.
165 self.opts = None
166
167 # A dictionary used by portage to maintain global state. This state is
168 # loaded from disk when portage starts up, and saved to disk whenever we
169 # call mtimedb.commit().
170 #
171 # This database contains information about global updates (i.e., what
172 # version of portage we have) and what we're currently doing. Portage
173 # saves what it is currently doing in this database so that it can be
174 # resumed when you call it with the --resume option.
175 #
176 # parallel_emerge does not save what it is currently doing in the mtimedb,
177 # so we do not support the --resume option.
178 self.mtimedb = None
179
180 # The portage configuration for our current root. This contains the portage
181 # settings (see below) and the three portage trees for our current root.
182 # (The three portage trees are explained below, in the documentation for
183 # the "trees" member.)
184 self.root_config = None
185
186 # The scheduler graph is used by emerge to calculate what packages to
187 # install. We don't actually install any deps, so this isn't really used,
188 # but we pass it in to the Scheduler object anyway.
189 self.scheduler_graph = None
190
191 # Portage settings for our current session. Most of these settings are set
192 # in make.conf inside our current install root.
193 self.settings = None
194
195 # The spinner, which spews stuff to stdout to indicate that portage is
196 # doing something. We maintain our own spinner, so we set the portage
197 # spinner to "silent" mode.
198 self.spinner = None
199
200 # The portage trees. There are separate portage trees for each root. To get
201 # the portage tree for the current root, you can look in self.trees[root],
202 # where root = self.settings["ROOT"].
203 #
204 # In each root, there are three trees: vartree, porttree, and bintree.
205 # - vartree: A database of the currently-installed packages.
206 # - porttree: A database of ebuilds, that can be used to build packages.
207 # - bintree: A database of binary packages.
208 self.trees = None
209
210
211class DepGraphGenerator(object):
212 """Grab dependency information about packages from portage.
213
214 Typical usage:
215 deps = DepGraphGenerator()
216 deps.Initialize(sys.argv[1:])
217 deps_tree, deps_info = deps.GenDependencyTree()
218 deps_graph = deps.GenDependencyGraph(deps_tree, deps_info)
219 deps.PrintTree(deps_tree)
220 PrintDepsMap(deps_graph)
221 """
222
David James386ccd12011-05-04 20:17:42 -0700223 __slots__ = ["board", "emerge", "package_db", "show_output"]
David Jamesfcb70ef2011-02-02 16:02:30 -0800224
225 def __init__(self):
226 self.board = None
227 self.emerge = EmergeData()
David Jamesfcb70ef2011-02-02 16:02:30 -0800228 self.package_db = {}
David Jamesfcb70ef2011-02-02 16:02:30 -0800229 self.show_output = False
David Jamesfcb70ef2011-02-02 16:02:30 -0800230
231 def ParseParallelEmergeArgs(self, argv):
232 """Read the parallel emerge arguments from the command-line.
233
234 We need to be compatible with emerge arg format. We scrape arguments that
235 are specific to parallel_emerge, and pass through the rest directly to
236 emerge.
237 Args:
238 argv: arguments list
239 Returns:
240 Arguments that don't belong to parallel_emerge
241 """
242 emerge_args = []
243 for arg in argv:
244 # Specifically match arguments that are specific to parallel_emerge, and
245 # pass through the rest.
246 if arg.startswith("--board="):
247 self.board = arg.replace("--board=", "")
248 elif arg.startswith("--workon="):
249 workon_str = arg.replace("--workon=", "")
David James386ccd12011-05-04 20:17:42 -0700250 if NEW_PORTAGE:
251 emerge_args.append("--reinstall-atoms=%s" % workon_str)
252 emerge_args.append("--usepkg-exclude=%s" % workon_str)
David Jamesfcb70ef2011-02-02 16:02:30 -0800253 elif arg.startswith("--force-remote-binary="):
254 force_remote_binary = arg.replace("--force-remote-binary=", "")
David James386ccd12011-05-04 20:17:42 -0700255 if NEW_PORTAGE:
256 emerge_args.append("--useoldpkg-atoms=%s" % force_remote_binary)
David Jamesfcb70ef2011-02-02 16:02:30 -0800257 elif arg == "--show-output":
258 self.show_output = True
David James386ccd12011-05-04 20:17:42 -0700259 elif arg == "--rebuild":
260 if NEW_PORTAGE:
261 emerge_args.append("--rebuild-if-unbuilt")
David Jamesfcb70ef2011-02-02 16:02:30 -0800262 else:
263 # Not one of our options, so pass through to emerge.
264 emerge_args.append(arg)
265
David James386ccd12011-05-04 20:17:42 -0700266 # These packages take a really long time to build, so, for expediency, we
267 # are blacklisting them from automatic rebuilds because one of their
268 # dependencies needs to be recompiled.
269 for pkg in ("chromeos-base/chromeos-chrome", "media-plugins/o3d",
270 "dev-java/icedtea"):
271 if NEW_PORTAGE:
272 emerge_args.append("--rebuild-exclude=%s" % pkg)
David Jamesfcb70ef2011-02-02 16:02:30 -0800273
274 return emerge_args
275
276 def Initialize(self, args):
277 """Initializer. Parses arguments and sets up portage state."""
278
279 # Parse and strip out args that are just intended for parallel_emerge.
280 emerge_args = self.ParseParallelEmergeArgs(args)
281
282 # Setup various environment variables based on our current board. These
283 # variables are normally setup inside emerge-${BOARD}, but since we don't
284 # call that script, we have to set it up here. These variables serve to
285 # point our tools at /build/BOARD and to setup cross compiles to the
286 # appropriate board as configured in toolchain.conf.
287 if self.board:
288 os.environ["PORTAGE_CONFIGROOT"] = "/build/" + self.board
289 os.environ["PORTAGE_SYSROOT"] = "/build/" + self.board
290 os.environ["SYSROOT"] = "/build/" + self.board
291 srcroot = "%s/../../src" % os.path.dirname(os.path.realpath(__file__))
292 # Strip the variant out of the board name to look for the toolchain. This
293 # is similar to what setup_board does.
294 board_no_variant = self.board.split('_')[0]
295 public_toolchain_path = ("%s/overlays/overlay-%s/toolchain.conf" %
296 (srcroot, board_no_variant))
297 private_toolchain_path = (
298 "%s/private-overlays/overlay-%s-private/toolchain.conf" %
299 (srcroot, board_no_variant))
300 if os.path.isfile(public_toolchain_path):
301 toolchain_path = public_toolchain_path
302 elif os.path.isfile(private_toolchain_path):
303 toolchain_path = private_toolchain_path
304 else:
305 print "Not able to locate toolchain.conf in board overlays"
306 sys.exit(1)
307
308 f = open(toolchain_path)
309 os.environ["CHOST"] = f.readline().strip()
310 f.close()
311
312 # Although CHROMEOS_ROOT isn't specific to boards, it's normally setup
313 # inside emerge-${BOARD}, so we set it up here for compatibility. It
314 # will be going away soon as we migrate to CROS_WORKON_SRCROOT.
315 os.environ.setdefault("CHROMEOS_ROOT", os.environ["HOME"] + "/trunk")
316
317 # Turn off interactive delays
318 os.environ["EBEEP_IGNORE"] = "1"
319 os.environ["EPAUSE_IGNORE"] = "1"
320 os.environ["UNMERGE_DELAY"] = "0"
321
322 # Parse the emerge options.
David Jamesea3ca332011-05-26 11:48:29 -0700323 action, opts, cmdline_packages = parse_opts(emerge_args, silent=True)
David Jamesfcb70ef2011-02-02 16:02:30 -0800324
325 # Set environment variables based on options. Portage normally sets these
326 # environment variables in emerge_main, but we can't use that function,
327 # because it also does a bunch of other stuff that we don't want.
328 # TODO(davidjames): Patch portage to move this logic into a function we can
329 # reuse here.
330 if "--debug" in opts:
331 os.environ["PORTAGE_DEBUG"] = "1"
332 if "--config-root" in opts:
333 os.environ["PORTAGE_CONFIGROOT"] = opts["--config-root"]
334 if "--root" in opts:
335 os.environ["ROOT"] = opts["--root"]
336 if "--accept-properties" in opts:
337 os.environ["ACCEPT_PROPERTIES"] = opts["--accept-properties"]
338
339 # Portage has two flags for doing collision protection: collision-protect
340 # and protect-owned. The protect-owned feature is enabled by default and
341 # is quite useful: it checks to make sure that we don't have multiple
342 # packages that own the same file. The collision-protect feature is more
343 # strict, and less useful: it fails if it finds a conflicting file, even
344 # if that file was created by an earlier ebuild that failed to install.
345 #
346 # We want to disable collision-protect here because we don't handle
347 # failures during the merge step very well. Sometimes we leave old files
348 # lying around and they cause problems, so for now we disable the flag.
349 # TODO(davidjames): Look for a better solution.
350 features = os.environ.get("FEATURES", "") + " -collision-protect"
351
David Jamesdeebd692011-05-09 17:02:52 -0700352 # Install packages in parallel.
353 features = features + " parallel-install"
354
David Jamesfcb70ef2011-02-02 16:02:30 -0800355 # If we're installing packages to the board, and we're not using the
356 # official flag, we can enable the following optimizations:
357 # 1) Don't lock during install step. This allows multiple packages to be
358 # installed at once. This is safe because our board packages do not
359 # muck with each other during the post-install step.
360 # 2) Don't update the environment until the end of the build. This is
361 # safe because board packages don't need to run during the build --
362 # they're cross-compiled, so our CPU architecture doesn't support them
363 # anyway.
364 if self.board and os.environ.get("CHROMEOS_OFFICIAL") != "1":
365 os.environ.setdefault("PORTAGE_LOCKS", "false")
David Jamesdeebd692011-05-09 17:02:52 -0700366 features = features + " -ebuild-locks no-env-update"
David Jamesfcb70ef2011-02-02 16:02:30 -0800367
368 os.environ["FEATURES"] = features
369
370 # Now that we've setup the necessary environment variables, we can load the
371 # emerge config from disk.
372 settings, trees, mtimedb = load_emerge_config()
373
David Jamesea3ca332011-05-26 11:48:29 -0700374 # Add in EMERGE_DEFAULT_OPTS, if specified.
375 tmpcmdline = []
376 if "--ignore-default-opts" not in opts:
377 tmpcmdline.extend(settings["EMERGE_DEFAULT_OPTS"].split())
378 tmpcmdline.extend(emerge_args)
379 action, opts, cmdline_packages = parse_opts(tmpcmdline)
380
381 # If we're installing to the board, we want the --root-deps option so that
382 # portage will install the build dependencies to that location as well.
383 if self.board:
384 opts.setdefault("--root-deps", True)
385
David Jamesfcb70ef2011-02-02 16:02:30 -0800386 # Check whether our portage tree is out of date. Typically, this happens
387 # when you're setting up a new portage tree, such as in setup_board and
388 # make_chroot. In that case, portage applies a bunch of global updates
389 # here. Once the updates are finished, we need to commit any changes
390 # that the global update made to our mtimedb, and reload the config.
391 #
392 # Portage normally handles this logic in emerge_main, but again, we can't
393 # use that function here.
394 if _global_updates(trees, mtimedb["updates"]):
395 mtimedb.commit()
396 settings, trees, mtimedb = load_emerge_config(trees=trees)
397
398 # Setup implied options. Portage normally handles this logic in
399 # emerge_main.
400 if "--buildpkgonly" in opts or "buildpkg" in settings.features:
401 opts.setdefault("--buildpkg", True)
402 if "--getbinpkgonly" in opts:
403 opts.setdefault("--usepkgonly", True)
404 opts.setdefault("--getbinpkg", True)
405 if "getbinpkg" in settings.features:
406 # Per emerge_main, FEATURES=getbinpkg overrides --getbinpkg=n
407 opts["--getbinpkg"] = True
408 if "--getbinpkg" in opts or "--usepkgonly" in opts:
409 opts.setdefault("--usepkg", True)
410 if "--fetch-all-uri" in opts:
411 opts.setdefault("--fetchonly", True)
412 if "--skipfirst" in opts:
413 opts.setdefault("--resume", True)
414 if "--buildpkgonly" in opts:
415 # --buildpkgonly will not merge anything, so it overrides all binary
416 # package options.
417 for opt in ("--getbinpkg", "--getbinpkgonly",
418 "--usepkg", "--usepkgonly"):
419 opts.pop(opt, None)
420 if (settings.get("PORTAGE_DEBUG", "") == "1" and
421 "python-trace" in settings.features):
422 portage.debug.set_trace(True)
423
424 # Complain about unsupported options
David James386ccd12011-05-04 20:17:42 -0700425 for opt in ("--ask", "--ask-enter-invalid", "--resume", "--skipfirst"):
David Jamesfcb70ef2011-02-02 16:02:30 -0800426 if opt in opts:
427 print "%s is not supported by parallel_emerge" % opt
428 sys.exit(1)
429
430 # Make emerge specific adjustments to the config (e.g. colors!)
431 adjust_configs(opts, trees)
432
433 # Save our configuration so far in the emerge object
434 emerge = self.emerge
435 emerge.action, emerge.opts = action, opts
436 emerge.settings, emerge.trees, emerge.mtimedb = settings, trees, mtimedb
437 emerge.cmdline_packages = cmdline_packages
438 root = settings["ROOT"]
439 emerge.root_config = trees[root]["root_config"]
440
David James386ccd12011-05-04 20:17:42 -0700441 if "--usepkg" in opts:
David Jamesfcb70ef2011-02-02 16:02:30 -0800442 emerge.trees[root]["bintree"].populate("--getbinpkg" in opts)
443
David Jamesfcb70ef2011-02-02 16:02:30 -0800444 def CreateDepgraph(self, emerge, packages):
445 """Create an emerge depgraph object."""
446 # Setup emerge options.
447 emerge_opts = emerge.opts.copy()
448
David James386ccd12011-05-04 20:17:42 -0700449 # Ask portage to build a dependency graph. with the options we specified
450 # above.
David Jamesfcb70ef2011-02-02 16:02:30 -0800451 params = create_depgraph_params(emerge_opts, emerge.action)
David Jamesbf1e3442011-05-28 07:44:20 -0700452 success, depgraph, favorites = backtrack_depgraph(
David James386ccd12011-05-04 20:17:42 -0700453 emerge.settings, emerge.trees, emerge_opts, params, emerge.action,
454 packages, emerge.spinner)
455 emerge.depgraph = depgraph
David Jamesfcb70ef2011-02-02 16:02:30 -0800456
David James386ccd12011-05-04 20:17:42 -0700457 # Is it impossible to honor the user's request? Bail!
458 if not success:
459 depgraph.display_problems()
460 sys.exit(1)
David Jamesfcb70ef2011-02-02 16:02:30 -0800461
462 emerge.depgraph = depgraph
David Jamesbf1e3442011-05-28 07:44:20 -0700463 emerge.favorites = favorites
David Jamesfcb70ef2011-02-02 16:02:30 -0800464
465 # Is it impossible to honor the user's request? Bail!
466 if not success:
467 depgraph.display_problems()
468 sys.exit(1)
469
David Jamesdeebd692011-05-09 17:02:52 -0700470 # Prime and flush emerge caches.
471 root = emerge.settings["ROOT"]
472 vardb = emerge.trees[root]["vartree"].dbapi
David James0bdc5de2011-05-12 16:22:26 -0700473 if "--pretend" not in emerge.opts:
474 vardb.counter_tick()
David Jamesdeebd692011-05-09 17:02:52 -0700475 vardb.flush_cache()
476
David James386ccd12011-05-04 20:17:42 -0700477 def GenDependencyTree(self):
David Jamesfcb70ef2011-02-02 16:02:30 -0800478 """Get dependency tree info from emerge.
479
David Jamesfcb70ef2011-02-02 16:02:30 -0800480 Returns:
481 Dependency tree
482 """
483 start = time.time()
484
485 emerge = self.emerge
486
487 # Create a list of packages to merge
488 packages = set(emerge.cmdline_packages[:])
David Jamesfcb70ef2011-02-02 16:02:30 -0800489
490 # Tell emerge to be quiet. We print plenty of info ourselves so we don't
491 # need any extra output from portage.
492 portage.util.noiselimit = -1
493
494 # My favorite feature: The silent spinner. It doesn't spin. Ever.
495 # I'd disable the colors by default too, but they look kind of cool.
496 emerge.spinner = stdout_spinner()
497 emerge.spinner.update = emerge.spinner.update_quiet
498
499 if "--quiet" not in emerge.opts:
500 print "Calculating deps..."
501
502 self.CreateDepgraph(emerge, packages)
503 depgraph = emerge.depgraph
504
505 # Build our own tree from the emerge digraph.
506 deps_tree = {}
507 digraph = depgraph._dynamic_config.digraph
508 for node, node_deps in digraph.nodes.items():
509 # Calculate dependency packages that need to be installed first. Each
510 # child on the digraph is a dependency. The "operation" field specifies
511 # what we're doing (e.g. merge, uninstall, etc.). The "priorities" array
512 # contains the type of dependency (e.g. build, runtime, runtime_post,
513 # etc.)
514 #
David Jamesfcb70ef2011-02-02 16:02:30 -0800515 # Portage refers to the identifiers for packages as a CPV. This acronym
516 # stands for Component/Path/Version.
517 #
518 # Here's an example CPV: chromeos-base/power_manager-0.0.1-r1
519 # Split up, this CPV would be:
520 # C -- Component: chromeos-base
521 # P -- Path: power_manager
522 # V -- Version: 0.0.1-r1
523 #
524 # We just refer to CPVs as packages here because it's easier.
525 deps = {}
526 for child, priorities in node_deps[0].items():
527 if isinstance(child, SetArg): continue
528 deps[str(child.cpv)] = dict(action=str(child.operation),
David James8c7e5e32011-06-28 11:26:03 -0700529 deptypes=[str(x) for x in priorities],
David Jamesfcb70ef2011-02-02 16:02:30 -0800530 deps={})
531
532 # We've built our list of deps, so we can add our package to the tree.
David James386ccd12011-05-04 20:17:42 -0700533 if isinstance(node, Package) and node.root == emerge.settings["ROOT"]:
David Jamesfcb70ef2011-02-02 16:02:30 -0800534 deps_tree[str(node.cpv)] = dict(action=str(node.operation),
535 deps=deps)
536
David Jamesfcb70ef2011-02-02 16:02:30 -0800537 # Ask portage for its install plan, so that we can only throw out
David James386ccd12011-05-04 20:17:42 -0700538 # dependencies that portage throws out.
David Jamesfcb70ef2011-02-02 16:02:30 -0800539 deps_info = {}
540 for pkg in depgraph.altlist():
541 if isinstance(pkg, Package):
David James386ccd12011-05-04 20:17:42 -0700542 assert pkg.root == emerge.settings["ROOT"]
David Jamesfcb70ef2011-02-02 16:02:30 -0800543 self.package_db[pkg.cpv] = pkg
544
David Jamesfcb70ef2011-02-02 16:02:30 -0800545 # Save off info about the package
David James386ccd12011-05-04 20:17:42 -0700546 deps_info[str(pkg.cpv)] = {"idx": len(deps_info)}
David Jamesfcb70ef2011-02-02 16:02:30 -0800547
548 seconds = time.time() - start
549 if "--quiet" not in emerge.opts:
550 print "Deps calculated in %dm%.1fs" % (seconds / 60, seconds % 60)
551
552 return deps_tree, deps_info
553
554 def PrintTree(self, deps, depth=""):
555 """Print the deps we have seen in the emerge output.
556
557 Args:
558 deps: Dependency tree structure.
559 depth: Allows printing the tree recursively, with indentation.
560 """
561 for entry in sorted(deps):
562 action = deps[entry]["action"]
563 print "%s %s (%s)" % (depth, entry, action)
564 self.PrintTree(deps[entry]["deps"], depth=depth + " ")
565
David James386ccd12011-05-04 20:17:42 -0700566 def GenDependencyGraph(self, deps_tree, deps_info):
David Jamesfcb70ef2011-02-02 16:02:30 -0800567 """Generate a doubly linked dependency graph.
568
569 Args:
570 deps_tree: Dependency tree structure.
571 deps_info: More details on the dependencies.
572 Returns:
573 Deps graph in the form of a dict of packages, with each package
574 specifying a "needs" list and "provides" list.
575 """
576 emerge = self.emerge
577 root = emerge.settings["ROOT"]
578
David Jamesfcb70ef2011-02-02 16:02:30 -0800579 # deps_map is the actual dependency graph.
580 #
581 # Each package specifies a "needs" list and a "provides" list. The "needs"
582 # list indicates which packages we depend on. The "provides" list
583 # indicates the reverse dependencies -- what packages need us.
584 #
585 # We also provide some other information in the dependency graph:
586 # - action: What we're planning on doing with this package. Generally,
587 # "merge", "nomerge", or "uninstall"
David Jamesfcb70ef2011-02-02 16:02:30 -0800588 deps_map = {}
589
590 def ReverseTree(packages):
591 """Convert tree to digraph.
592
593 Take the tree of package -> requirements and reverse it to a digraph of
594 buildable packages -> packages they unblock.
595 Args:
596 packages: Tree(s) of dependencies.
597 Returns:
598 Unsanitized digraph.
599 """
David James8c7e5e32011-06-28 11:26:03 -0700600 binpkg_phases = set(["setup", "preinst", "postinst"])
601 needed_dep_types = set(["buildtime", "runtime"])
David Jamesfcb70ef2011-02-02 16:02:30 -0800602 for pkg in packages:
603
604 # Create an entry for the package
605 action = packages[pkg]["action"]
David James8c7e5e32011-06-28 11:26:03 -0700606 default_pkg = {"needs": {}, "provides": set(), "action": action,
607 "nodeps": False, "binary": False}
David Jamesfcb70ef2011-02-02 16:02:30 -0800608 this_pkg = deps_map.setdefault(pkg, default_pkg)
609
David James8c7e5e32011-06-28 11:26:03 -0700610 if pkg in deps_info:
611 this_pkg["idx"] = deps_info[pkg]["idx"]
612
613 # If a package doesn't have any defined phases that might use the
614 # dependent packages (i.e. pkg_setup, pkg_preinst, or pkg_postinst),
615 # we can install this package before its deps are ready.
616 emerge_pkg = self.package_db.get(pkg)
617 if emerge_pkg and emerge_pkg.type_name == "binary":
618 this_pkg["binary"] = True
619 defined_phases = emerge_pkg.metadata.defined_phases
620 defined_binpkg_phases = binpkg_phases.intersection(defined_phases)
621 if not defined_binpkg_phases:
622 this_pkg["nodeps"] = True
623
David Jamesfcb70ef2011-02-02 16:02:30 -0800624 # Create entries for dependencies of this package first.
625 ReverseTree(packages[pkg]["deps"])
626
627 # Add dependencies to this package.
628 for dep, dep_item in packages[pkg]["deps"].iteritems():
David James8c7e5e32011-06-28 11:26:03 -0700629 # We only need to enforce strict ordering of dependencies if the
630 # dependency is a buildtime or runtime dependency. (I.e., ignored,
631 # optional, and runtime_post dependencies don't depend on ordering.)
632 dep_types = dep_item["deptypes"]
633 if needed_dep_types.intersection(dep_types):
634 deps_map[dep]["provides"].add(pkg)
635 this_pkg["needs"][dep] = "/".join(dep_types)
David Jamesfcb70ef2011-02-02 16:02:30 -0800636
David Jamesfcb70ef2011-02-02 16:02:30 -0800637 def FindCycles():
638 """Find cycles in the dependency tree.
639
640 Returns:
641 A dict mapping cyclic packages to a dict of the deps that cause
642 cycles. For each dep that causes cycles, it returns an example
643 traversal of the graph that shows the cycle.
644 """
645
646 def FindCyclesAtNode(pkg, cycles, unresolved, resolved):
647 """Find cycles in cyclic dependencies starting at specified package.
648
649 Args:
650 pkg: Package identifier.
651 cycles: A dict mapping cyclic packages to a dict of the deps that
652 cause cycles. For each dep that causes cycles, it returns an
653 example traversal of the graph that shows the cycle.
654 unresolved: Nodes that have been visited but are not fully processed.
655 resolved: Nodes that have been visited and are fully processed.
656 """
657 pkg_cycles = cycles.get(pkg)
658 if pkg in resolved and not pkg_cycles:
659 # If we already looked at this package, and found no cyclic
660 # dependencies, we can stop now.
661 return
662 unresolved.append(pkg)
663 for dep in deps_map[pkg]["needs"]:
664 if dep in unresolved:
665 idx = unresolved.index(dep)
666 mycycle = unresolved[idx:] + [dep]
667 for i in range(len(mycycle) - 1):
668 pkg1, pkg2 = mycycle[i], mycycle[i+1]
669 cycles.setdefault(pkg1, {}).setdefault(pkg2, mycycle)
670 elif not pkg_cycles or dep not in pkg_cycles:
671 # Looks like we haven't seen this edge before.
672 FindCyclesAtNode(dep, cycles, unresolved, resolved)
673 unresolved.pop()
674 resolved.add(pkg)
675
676 cycles, unresolved, resolved = {}, [], set()
677 for pkg in deps_map:
678 FindCyclesAtNode(pkg, cycles, unresolved, resolved)
679 return cycles
680
David James386ccd12011-05-04 20:17:42 -0700681 def RemoveUnusedPackages():
David Jamesfcb70ef2011-02-02 16:02:30 -0800682 """Remove installed packages, propagating dependencies."""
David Jamesfcb70ef2011-02-02 16:02:30 -0800683 # Schedule packages that aren't on the install list for removal
684 rm_pkgs = set(deps_map.keys()) - set(deps_info.keys())
685
David Jamesfcb70ef2011-02-02 16:02:30 -0800686 # Remove the packages we don't want, simplifying the graph and making
687 # it easier for us to crack cycles.
688 for pkg in sorted(rm_pkgs):
689 this_pkg = deps_map[pkg]
690 needs = this_pkg["needs"]
691 provides = this_pkg["provides"]
692 for dep in needs:
693 dep_provides = deps_map[dep]["provides"]
694 dep_provides.update(provides)
695 dep_provides.discard(pkg)
696 dep_provides.discard(dep)
697 for target in provides:
698 target_needs = deps_map[target]["needs"]
699 target_needs.update(needs)
700 target_needs.pop(pkg, None)
701 target_needs.pop(target, None)
702 del deps_map[pkg]
703
704 def PrintCycleBreak(basedep, dep, mycycle):
705 """Print details about a cycle that we are planning on breaking.
706
707 We are breaking a cycle where dep needs basedep. mycycle is an
708 example cycle which contains dep -> basedep."""
709
David Jamesfcb70ef2011-02-02 16:02:30 -0800710 needs = deps_map[dep]["needs"]
711 depinfo = needs.get(basedep, "deleted")
David Jamesfcb70ef2011-02-02 16:02:30 -0800712
713 # Notify the user that we're breaking a cycle.
714 print "Breaking %s -> %s (%s)" % (dep, basedep, depinfo)
715
716 # Show cycle.
717 for i in range(len(mycycle) - 1):
718 pkg1, pkg2 = mycycle[i], mycycle[i+1]
719 needs = deps_map[pkg1]["needs"]
720 depinfo = needs.get(pkg2, "deleted")
721 if pkg1 == dep and pkg2 == basedep:
722 depinfo = depinfo + ", deleting"
723 print " %s -> %s (%s)" % (pkg1, pkg2, depinfo)
724
725 def SanitizeTree():
726 """Remove circular dependencies.
727
728 We prune all dependencies involved in cycles that go against the emerge
729 ordering. This has a nice property: we're guaranteed to merge
730 dependencies in the same order that portage does.
731
732 Because we don't treat any dependencies as "soft" unless they're killed
733 by a cycle, we pay attention to a larger number of dependencies when
734 merging. This hurts performance a bit, but helps reliability.
735 """
736 start = time.time()
737 cycles = FindCycles()
738 while cycles:
739 for dep, mycycles in cycles.iteritems():
740 for basedep, mycycle in mycycles.iteritems():
741 if deps_info[basedep]["idx"] >= deps_info[dep]["idx"]:
742 PrintCycleBreak(basedep, dep, mycycle)
743 del deps_map[dep]["needs"][basedep]
744 deps_map[basedep]["provides"].remove(dep)
745 cycles = FindCycles()
746 seconds = time.time() - start
747 if "--quiet" not in emerge.opts and seconds >= 0.1:
748 print "Tree sanitized in %dm%.1fs" % (seconds / 60, seconds % 60)
749
David James8c7e5e32011-06-28 11:26:03 -0700750 def FindRecursiveProvides(pkg, seen):
751 """Find all nodes that require a particular package.
752
753 Assumes that graph is acyclic.
754
755 Args:
756 pkg: Package identifier.
757 seen: Nodes that have been visited so far.
758 """
759 if pkg in seen:
760 return
761 seen.add(pkg)
762 info = deps_map[pkg]
763 info["tprovides"] = info["provides"].copy()
764 for dep in info["provides"]:
765 FindRecursiveProvides(dep, seen)
766 info["tprovides"].update(deps_map[dep]["tprovides"])
767
David Jamesa22906f2011-05-04 19:53:26 -0700768 ReverseTree(deps_tree)
David Jamesa22906f2011-05-04 19:53:26 -0700769
David James386ccd12011-05-04 20:17:42 -0700770 # We need to remove unused packages so that we can use the dependency
771 # ordering of the install process to show us what cycles to crack.
772 RemoveUnusedPackages()
David Jamesfcb70ef2011-02-02 16:02:30 -0800773 SanitizeTree()
David James8c7e5e32011-06-28 11:26:03 -0700774 seen = set()
775 for pkg in deps_map:
776 FindRecursiveProvides(pkg, seen)
David Jamesfcb70ef2011-02-02 16:02:30 -0800777 return deps_map
778
779 def PrintInstallPlan(self, deps_map):
780 """Print an emerge-style install plan.
781
782 The install plan lists what packages we're installing, in order.
783 It's useful for understanding what parallel_emerge is doing.
784
785 Args:
786 deps_map: The dependency graph.
787 """
788
789 def InstallPlanAtNode(target, deps_map):
790 nodes = []
791 nodes.append(target)
792 for dep in deps_map[target]["provides"]:
793 del deps_map[dep]["needs"][target]
794 if not deps_map[dep]["needs"]:
795 nodes.extend(InstallPlanAtNode(dep, deps_map))
796 return nodes
797
798 deps_map = copy.deepcopy(deps_map)
799 install_plan = []
800 plan = set()
801 for target, info in deps_map.iteritems():
802 if not info["needs"] and target not in plan:
803 for item in InstallPlanAtNode(target, deps_map):
804 plan.add(item)
805 install_plan.append(self.package_db[item])
806
807 for pkg in plan:
808 del deps_map[pkg]
809
810 if deps_map:
811 print "Cyclic dependencies:", " ".join(deps_map)
812 PrintDepsMap(deps_map)
813 sys.exit(1)
814
815 self.emerge.depgraph.display(install_plan)
816
817
818def PrintDepsMap(deps_map):
819 """Print dependency graph, for each package list it's prerequisites."""
820 for i in sorted(deps_map):
821 print "%s: (%s) needs" % (i, deps_map[i]["action"])
822 needs = deps_map[i]["needs"]
823 for j in sorted(needs):
824 print " %s" % (j)
825 if not needs:
826 print " no dependencies"
827
828
829class EmergeJobState(object):
830 __slots__ = ["done", "filename", "last_notify_timestamp", "last_output_seek",
831 "last_output_timestamp", "pkgname", "retcode", "start_timestamp",
832 "target"]
833
834 def __init__(self, target, pkgname, done, filename, start_timestamp,
835 retcode=None):
836
837 # The full name of the target we're building (e.g.
838 # chromeos-base/chromeos-0.0.1-r60)
839 self.target = target
840
841 # The short name of the target we're building (e.g. chromeos-0.0.1-r60)
842 self.pkgname = pkgname
843
844 # Whether the job is done. (True if the job is done; false otherwise.)
845 self.done = done
846
847 # The filename where output is currently stored.
848 self.filename = filename
849
850 # The timestamp of the last time we printed the name of the log file. We
851 # print this at the beginning of the job, so this starts at
852 # start_timestamp.
853 self.last_notify_timestamp = start_timestamp
854
855 # The location (in bytes) of the end of the last complete line we printed.
856 # This starts off at zero. We use this to jump to the right place when we
857 # print output from the same ebuild multiple times.
858 self.last_output_seek = 0
859
860 # The timestamp of the last time we printed output. Since we haven't
861 # printed output yet, this starts at zero.
862 self.last_output_timestamp = 0
863
864 # The return code of our job, if the job is actually finished.
865 self.retcode = retcode
866
867 # The timestamp when our job started.
868 self.start_timestamp = start_timestamp
869
870
David James7358d032011-05-19 10:40:03 -0700871def KillHandler(signum, frame):
872 # Kill self and all subprocesses.
873 os.killpg(0, signal.SIGKILL)
874
David Jamesfcb70ef2011-02-02 16:02:30 -0800875def SetupWorkerSignals():
876 def ExitHandler(signum, frame):
David James7358d032011-05-19 10:40:03 -0700877 # Set KILLED flag.
878 KILLED.set()
David James13cead42011-05-18 16:22:01 -0700879
David James7358d032011-05-19 10:40:03 -0700880 # Remove our signal handlers so we don't get called recursively.
881 signal.signal(signal.SIGINT, KillHandler)
882 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -0800883
884 # Ensure that we exit quietly and cleanly, if possible, when we receive
885 # SIGTERM or SIGINT signals. By default, when the user hits CTRL-C, all
886 # of the child processes will print details about KeyboardInterrupt
887 # exceptions, which isn't very helpful.
888 signal.signal(signal.SIGINT, ExitHandler)
889 signal.signal(signal.SIGTERM, ExitHandler)
890
891
892def EmergeWorker(task_queue, job_queue, emerge, package_db):
893 """This worker emerges any packages given to it on the task_queue.
894
895 Args:
896 task_queue: The queue of tasks for this worker to do.
897 job_queue: The queue of results from the worker.
898 emerge: An EmergeData() object.
899 package_db: A dict, mapping package ids to portage Package objects.
900
901 It expects package identifiers to be passed to it via task_queue. When
902 a task is started, it pushes the (target, filename) to the started_queue.
903 The output is stored in filename. When a merge starts or finishes, we push
904 EmergeJobState objects to the job_queue.
905 """
906
907 SetupWorkerSignals()
908 settings, trees, mtimedb = emerge.settings, emerge.trees, emerge.mtimedb
David Jamesdeebd692011-05-09 17:02:52 -0700909
910 # Disable flushing of caches to save on I/O.
911 if 0 <= vercmp(portage.VERSION, "2.1.9.48"):
912 root = emerge.settings["ROOT"]
913 vardb = emerge.trees[root]["vartree"].dbapi
914 vardb._flush_cache_enabled = False
915
David Jamesfcb70ef2011-02-02 16:02:30 -0800916 opts, spinner = emerge.opts, emerge.spinner
917 opts["--nodeps"] = True
David James386ccd12011-05-04 20:17:42 -0700918 # When Portage launches new processes, it goes on a rampage and closes all
919 # open file descriptors. Ask Portage not to do that, as it breaks us.
920 portage.process.get_open_fds = lambda: []
David Jamesfcb70ef2011-02-02 16:02:30 -0800921 while True:
922 # Wait for a new item to show up on the queue. This is a blocking wait,
923 # so if there's nothing to do, we just sit here.
924 target = task_queue.get()
925 if not target:
926 # If target is None, this means that the main thread wants us to quit.
927 # The other workers need to exit too, so we'll push the message back on
928 # to the queue so they'll get it too.
929 task_queue.put(target)
930 return
David James7358d032011-05-19 10:40:03 -0700931 if KILLED.is_set():
932 return
933
David Jamesfcb70ef2011-02-02 16:02:30 -0800934 db_pkg = package_db[target]
935 db_pkg.root_config = emerge.root_config
936 install_list = [db_pkg]
937 pkgname = db_pkg.pf
938 output = tempfile.NamedTemporaryFile(prefix=pkgname + "-", delete=False)
939 start_timestamp = time.time()
940 job = EmergeJobState(target, pkgname, False, output.name, start_timestamp)
941 job_queue.put(job)
942 if "--pretend" in opts:
943 retcode = 0
944 else:
945 save_stdout = sys.stdout
946 save_stderr = sys.stderr
947 try:
948 sys.stdout = output
949 sys.stderr = output
David James386ccd12011-05-04 20:17:42 -0700950 emerge.scheduler_graph.mergelist = install_list
951 scheduler = Scheduler(settings, trees, mtimedb, opts, spinner,
David Jamesbf1e3442011-05-28 07:44:20 -0700952 favorites=emerge.favorites, graph_config=emerge.scheduler_graph)
David Jamesace2e212011-07-13 11:47:39 -0700953
954 # Enable blocker handling even though we're in --nodeps mode. This
955 # allows us to unmerge the blocker after we've merged the replacement.
956 scheduler._opts_ignore_blockers = frozenset()
957
David Jamesfcb70ef2011-02-02 16:02:30 -0800958 retcode = scheduler.merge()
959 except Exception:
960 traceback.print_exc(file=output)
961 retcode = 1
962 finally:
963 sys.stdout = save_stdout
964 sys.stderr = save_stderr
965 output.close()
966 if retcode is None:
967 retcode = 0
968
David James7358d032011-05-19 10:40:03 -0700969 if KILLED.is_set():
970 return
971
David Jamesfcb70ef2011-02-02 16:02:30 -0800972 job = EmergeJobState(target, pkgname, True, output.name, start_timestamp,
973 retcode)
974 job_queue.put(job)
975
976
977class LinePrinter(object):
978 """Helper object to print a single line."""
979
980 def __init__(self, line):
981 self.line = line
982
983 def Print(self, seek_locations):
984 print self.line
985
986
987class JobPrinter(object):
988 """Helper object to print output of a job."""
989
990 def __init__(self, job, unlink=False):
991 """Print output of job.
992
993 If unlink is True, unlink the job output file when done."""
994 self.current_time = time.time()
995 self.job = job
996 self.unlink = unlink
997
998 def Print(self, seek_locations):
999
1000 job = self.job
1001
1002 # Calculate how long the job has been running.
1003 seconds = self.current_time - job.start_timestamp
1004
1005 # Note that we've printed out the job so far.
1006 job.last_output_timestamp = self.current_time
1007
1008 # Note that we're starting the job
1009 info = "job %s (%dm%.1fs)" % (job.pkgname, seconds / 60, seconds % 60)
1010 last_output_seek = seek_locations.get(job.filename, 0)
1011 if last_output_seek:
1012 print "=== Continue output for %s ===" % info
1013 else:
1014 print "=== Start output for %s ===" % info
1015
1016 # Print actual output from job
1017 f = codecs.open(job.filename, encoding='utf-8', errors='replace')
1018 f.seek(last_output_seek)
1019 prefix = job.pkgname + ":"
1020 for line in f:
1021
1022 # Save off our position in the file
1023 if line and line[-1] == "\n":
1024 last_output_seek = f.tell()
1025 line = line[:-1]
1026
1027 # Print our line
1028 print prefix, line.encode('utf-8', 'replace')
1029 f.close()
1030
1031 # Save our last spot in the file so that we don't print out the same
1032 # location twice.
1033 seek_locations[job.filename] = last_output_seek
1034
1035 # Note end of output section
1036 if job.done:
1037 print "=== Complete: %s ===" % info
1038 else:
1039 print "=== Still running: %s ===" % info
1040
1041 if self.unlink:
1042 os.unlink(job.filename)
1043
1044
1045def PrintWorker(queue):
1046 """A worker that prints stuff to the screen as requested."""
1047
1048 def ExitHandler(signum, frame):
David James7358d032011-05-19 10:40:03 -07001049 # Set KILLED flag.
1050 KILLED.set()
1051
David Jamesfcb70ef2011-02-02 16:02:30 -08001052 # Switch to default signal handlers so that we'll die after two signals.
David James7358d032011-05-19 10:40:03 -07001053 signal.signal(signal.SIGINT, KillHandler)
1054 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -08001055
1056 # Don't exit on the first SIGINT / SIGTERM, because the parent worker will
1057 # handle it and tell us when we need to exit.
1058 signal.signal(signal.SIGINT, ExitHandler)
1059 signal.signal(signal.SIGTERM, ExitHandler)
1060
1061 # seek_locations is a map indicating the position we are at in each file.
1062 # It starts off empty, but is set by the various Print jobs as we go along
1063 # to indicate where we left off in each file.
1064 seek_locations = {}
1065 while True:
1066 try:
1067 job = queue.get()
1068 if job:
1069 job.Print(seek_locations)
David Jamesbccf8eb2011-07-27 14:06:06 -07001070 sys.stdout.flush()
David Jamesfcb70ef2011-02-02 16:02:30 -08001071 else:
1072 break
1073 except IOError as ex:
1074 if ex.errno == errno.EINTR:
1075 # Looks like we received a signal. Keep printing.
1076 continue
1077 raise
1078
David Jamesfcb70ef2011-02-02 16:02:30 -08001079class EmergeQueue(object):
1080 """Class to schedule emerge jobs according to a dependency graph."""
1081
1082 def __init__(self, deps_map, emerge, package_db, show_output):
1083 # Store the dependency graph.
1084 self._deps_map = deps_map
1085 # Initialize the running queue to empty
1086 self._jobs = {}
David James8c7e5e32011-06-28 11:26:03 -07001087 self._ready = []
David Jamesfcb70ef2011-02-02 16:02:30 -08001088 # List of total package installs represented in deps_map.
1089 install_jobs = [x for x in deps_map if deps_map[x]["action"] == "merge"]
1090 self._total_jobs = len(install_jobs)
1091 self._show_output = show_output
1092
1093 if "--pretend" in emerge.opts:
1094 print "Skipping merge because of --pretend mode."
1095 sys.exit(0)
1096
David James7358d032011-05-19 10:40:03 -07001097 # Set a process group so we can easily terminate all children.
1098 os.setsid()
1099
David Jamesfcb70ef2011-02-02 16:02:30 -08001100 # Setup scheduler graph object. This is used by the child processes
1101 # to help schedule jobs.
1102 emerge.scheduler_graph = emerge.depgraph.schedulerGraph()
1103
1104 # Calculate how many jobs we can run in parallel. We don't want to pass
1105 # the --jobs flag over to emerge itself, because that'll tell emerge to
1106 # hide its output, and said output is quite useful for debugging hung
1107 # jobs.
1108 procs = min(self._total_jobs,
1109 emerge.opts.pop("--jobs", multiprocessing.cpu_count()))
David James8c7e5e32011-06-28 11:26:03 -07001110 self._load_avg = emerge.opts.pop("--load-average", None)
David Jamesfcb70ef2011-02-02 16:02:30 -08001111 self._emerge_queue = multiprocessing.Queue()
1112 self._job_queue = multiprocessing.Queue()
1113 self._print_queue = multiprocessing.Queue()
1114 args = (self._emerge_queue, self._job_queue, emerge, package_db)
1115 self._pool = multiprocessing.Pool(procs, EmergeWorker, args)
1116 self._print_worker = multiprocessing.Process(target=PrintWorker,
1117 args=[self._print_queue])
1118 self._print_worker.start()
1119
1120 # Initialize the failed queue to empty.
1121 self._retry_queue = []
1122 self._failed = set()
1123
David Jamesfcb70ef2011-02-02 16:02:30 -08001124 # Setup an exit handler so that we print nice messages if we are
1125 # terminated.
1126 self._SetupExitHandler()
1127
1128 # Schedule our jobs.
1129 for target, info in deps_map.items():
David James8c7e5e32011-06-28 11:26:03 -07001130 if info["nodeps"] or not info["needs"]:
1131 score = (-len(info["tprovides"]), info["binary"], info["idx"])
1132 self._ready.append((score, target))
1133 heapq.heapify(self._ready)
1134 self._procs = procs
1135 self._ScheduleLoop()
1136
1137 # Print an update.
1138 self._Status()
David Jamesfcb70ef2011-02-02 16:02:30 -08001139
1140 def _SetupExitHandler(self):
1141
1142 def ExitHandler(signum, frame):
David James7358d032011-05-19 10:40:03 -07001143 # Set KILLED flag.
1144 KILLED.set()
David Jamesfcb70ef2011-02-02 16:02:30 -08001145
1146 # Kill our signal handlers so we don't get called recursively
David James7358d032011-05-19 10:40:03 -07001147 signal.signal(signal.SIGINT, KillHandler)
1148 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -08001149
1150 # Print our current job status
1151 for target, job in self._jobs.iteritems():
1152 if job:
1153 self._print_queue.put(JobPrinter(job, unlink=True))
1154
1155 # Notify the user that we are exiting
1156 self._Print("Exiting on signal %s" % signum)
David James7358d032011-05-19 10:40:03 -07001157 self._print_queue.put(None)
1158 self._print_worker.join()
David Jamesfcb70ef2011-02-02 16:02:30 -08001159
1160 # Kill child threads, then exit.
David James7358d032011-05-19 10:40:03 -07001161 os.killpg(0, signal.SIGKILL)
David Jamesfcb70ef2011-02-02 16:02:30 -08001162 sys.exit(1)
1163
1164 # Print out job status when we are killed
1165 signal.signal(signal.SIGINT, ExitHandler)
1166 signal.signal(signal.SIGTERM, ExitHandler)
1167
1168 def _Schedule(self, target):
1169 # We maintain a tree of all deps, if this doesn't need
David James8c7e5e32011-06-28 11:26:03 -07001170 # to be installed just free up its children and continue.
David Jamesfcb70ef2011-02-02 16:02:30 -08001171 # It is possible to reinstall deps of deps, without reinstalling
1172 # first level deps, like so:
1173 # chromeos (merge) -> eselect (nomerge) -> python (merge)
David James8c7e5e32011-06-28 11:26:03 -07001174 this_pkg = self._deps_map.get(target)
1175 if this_pkg is None:
David James386ccd12011-05-04 20:17:42 -07001176 pass
David James8c7e5e32011-06-28 11:26:03 -07001177 elif this_pkg["action"] == "nomerge":
David Jamesfcb70ef2011-02-02 16:02:30 -08001178 self._Finish(target)
David Jamesd20a6d92011-04-26 16:11:59 -07001179 elif target not in self._jobs:
David Jamesfcb70ef2011-02-02 16:02:30 -08001180 # Kick off the build if it's marked to be built.
1181 self._jobs[target] = None
1182 self._emerge_queue.put(target)
David James8c7e5e32011-06-28 11:26:03 -07001183 return True
David Jamesfcb70ef2011-02-02 16:02:30 -08001184
David James8c7e5e32011-06-28 11:26:03 -07001185 def _ScheduleLoop(self):
1186 # If the current load exceeds our desired load average, don't schedule
1187 # more than one job.
1188 if self._load_avg and os.getloadavg()[0] > self._load_avg:
1189 needed_jobs = 1
1190 else:
1191 needed_jobs = self._procs
1192
1193 # Schedule more jobs.
1194 while self._ready and len(self._jobs) < needed_jobs:
1195 score, pkg = heapq.heappop(self._ready)
1196 self._Schedule(pkg)
David Jamesfcb70ef2011-02-02 16:02:30 -08001197
1198 def _Print(self, line):
1199 """Print a single line."""
1200 self._print_queue.put(LinePrinter(line))
1201
1202 def _Status(self):
1203 """Print status."""
1204 current_time = time.time()
1205 no_output = True
1206
1207 # Print interim output every minute if --show-output is used. Otherwise,
1208 # print notifications about running packages every 2 minutes, and print
1209 # full output for jobs that have been running for 60 minutes or more.
1210 if self._show_output:
1211 interval = 60
1212 notify_interval = 0
1213 else:
1214 interval = 60 * 60
1215 notify_interval = 60 * 2
1216 for target, job in self._jobs.iteritems():
1217 if job:
1218 last_timestamp = max(job.start_timestamp, job.last_output_timestamp)
1219 if last_timestamp + interval < current_time:
1220 self._print_queue.put(JobPrinter(job))
1221 job.last_output_timestamp = current_time
1222 no_output = False
1223 elif (notify_interval and
1224 job.last_notify_timestamp + notify_interval < current_time):
1225 job_seconds = current_time - job.start_timestamp
1226 args = (job.pkgname, job_seconds / 60, job_seconds % 60, job.filename)
1227 info = "Still building %s (%dm%.1fs). Logs in %s" % args
1228 job.last_notify_timestamp = current_time
1229 self._Print(info)
1230 no_output = False
1231
1232 # If we haven't printed any messages yet, print a general status message
1233 # here.
1234 if no_output:
1235 seconds = current_time - GLOBAL_START
1236 line = ("Pending %s, Ready %s, Running %s, Retrying %s, Total %s "
1237 "[Time %dm%.1fs Load %s]")
David James8c7e5e32011-06-28 11:26:03 -07001238 load = " ".join(str(x) for x in os.getloadavg())
1239 self._Print(line % (len(self._deps_map), len(self._ready),
1240 len(self._jobs), len(self._retry_queue),
1241 self._total_jobs, seconds / 60, seconds % 60, load))
David Jamesfcb70ef2011-02-02 16:02:30 -08001242
1243 def _Finish(self, target):
David James8c7e5e32011-06-28 11:26:03 -07001244 """Mark a target as completed and unblock dependencies."""
1245 this_pkg = self._deps_map[target]
1246 if this_pkg["needs"] and this_pkg["nodeps"]:
1247 # We got installed, but our deps have not been installed yet. Dependent
1248 # packages should only be installed when our needs have been fully met.
1249 this_pkg["action"] = "nomerge"
1250 else:
1251 finish = []
1252 for dep in this_pkg["provides"]:
1253 dep_pkg = self._deps_map[dep]
1254 del dep_pkg["needs"][target]
1255 if not dep_pkg["needs"]:
1256 if dep_pkg["nodeps"] and dep_pkg["action"] == "nomerge":
1257 self._Finish(dep)
1258 else:
1259 score = (-len(dep_pkg["tprovides"]), dep_pkg["binary"],
1260 dep_pkg["idx"])
1261 heapq.heappush(self._ready, (score, dep))
1262 self._deps_map.pop(target)
David Jamesfcb70ef2011-02-02 16:02:30 -08001263
1264 def _Retry(self):
David James8c7e5e32011-06-28 11:26:03 -07001265 while self._retry_queue:
David Jamesfcb70ef2011-02-02 16:02:30 -08001266 target = self._retry_queue.pop(0)
David James8c7e5e32011-06-28 11:26:03 -07001267 if self._Schedule(target):
1268 self._Print("Retrying emerge of %s." % target)
1269 break
David Jamesfcb70ef2011-02-02 16:02:30 -08001270
1271 def _Exit(self):
1272 # Tell emerge workers to exit. They all exit when 'None' is pushed
1273 # to the queue.
1274 self._emerge_queue.put(None)
1275 self._pool.close()
1276 self._pool.join()
David James97ce8902011-08-16 09:51:05 -07001277 self._emerge_queue.close()
1278 self._emerge_queue = None
David Jamesfcb70ef2011-02-02 16:02:30 -08001279
1280 # Now that our workers are finished, we can kill the print queue.
1281 self._print_queue.put(None)
1282 self._print_worker.join()
David James97ce8902011-08-16 09:51:05 -07001283 self._print_queue.close()
1284 self._print_queue = None
1285 self._job_queue.close()
1286 self._job_queue = None
David Jamesfcb70ef2011-02-02 16:02:30 -08001287
1288 def Run(self):
1289 """Run through the scheduled ebuilds.
1290
1291 Keep running so long as we have uninstalled packages in the
1292 dependency graph to merge.
1293 """
1294 while self._deps_map:
1295 # Check here that we are actually waiting for something.
1296 if (self._emerge_queue.empty() and
1297 self._job_queue.empty() and
1298 not self._jobs and
David James8c7e5e32011-06-28 11:26:03 -07001299 not self._ready and
David Jamesfcb70ef2011-02-02 16:02:30 -08001300 self._deps_map):
1301 # If we have failed on a package, retry it now.
1302 if self._retry_queue:
1303 self._Retry()
1304 else:
1305 # Tell child threads to exit.
1306 self._Exit()
1307
1308 # The dependency map is helpful for debugging failures.
1309 PrintDepsMap(self._deps_map)
1310
1311 # Tell the user why we're exiting.
1312 if self._failed:
1313 print "Packages failed: %s" % " ,".join(self._failed)
1314 else:
1315 print "Deadlock! Circular dependencies!"
1316 sys.exit(1)
1317
David Jamesa74289a2011-08-12 10:41:24 -07001318 for i in range(3):
1319 try:
1320 job = self._job_queue.get(timeout=5)
1321 break
1322 except Queue.Empty:
1323 # Check if any more jobs can be scheduled.
1324 self._ScheduleLoop()
1325 else:
1326 # Print an update every 15 seconds.
David Jamesfcb70ef2011-02-02 16:02:30 -08001327 self._Status()
1328 continue
1329
1330 target = job.target
1331
1332 if not job.done:
1333 self._jobs[target] = job
1334 self._Print("Started %s (logged in %s)" % (target, job.filename))
1335 continue
1336
1337 # Print output of job
1338 if self._show_output or job.retcode != 0:
1339 self._print_queue.put(JobPrinter(job, unlink=True))
1340 else:
1341 os.unlink(job.filename)
1342 del self._jobs[target]
1343
1344 seconds = time.time() - job.start_timestamp
1345 details = "%s (in %dm%.1fs)" % (target, seconds / 60, seconds % 60)
1346
1347 # Complain if necessary.
1348 if job.retcode != 0:
1349 # Handle job failure.
1350 if target in self._failed:
1351 # If this job has failed previously, give up.
1352 self._Print("Failed %s. Your build has failed." % details)
1353 else:
1354 # Queue up this build to try again after a long while.
1355 self._retry_queue.append(target)
1356 self._failed.add(target)
1357 self._Print("Failed %s, retrying later." % details)
1358 else:
1359 if target in self._failed and self._retry_queue:
1360 # If we have successfully retried a failed package, and there
1361 # are more failed packages, try the next one. We will only have
1362 # one retrying package actively running at a time.
1363 self._Retry()
1364
1365 self._Print("Completed %s" % details)
1366 # Mark as completed and unblock waiting ebuilds.
1367 self._Finish(target)
1368
David James8c7e5e32011-06-28 11:26:03 -07001369 # Schedule pending jobs and print an update.
1370 self._ScheduleLoop()
1371 self._Status()
David Jamesfcb70ef2011-02-02 16:02:30 -08001372
1373 # Tell child threads to exit.
1374 self._Print("Merge complete")
1375 self._Exit()
1376
1377
1378def main():
1379
David James57437532011-05-06 15:51:21 -07001380 parallel_emerge_args = sys.argv[:]
David Jamesfcb70ef2011-02-02 16:02:30 -08001381 deps = DepGraphGenerator()
David James57437532011-05-06 15:51:21 -07001382 deps.Initialize(parallel_emerge_args[1:])
David Jamesfcb70ef2011-02-02 16:02:30 -08001383 emerge = deps.emerge
1384
1385 if emerge.action is not None:
1386 sys.argv = deps.ParseParallelEmergeArgs(sys.argv)
1387 sys.exit(emerge_main())
1388 elif not emerge.cmdline_packages:
1389 Usage()
1390 sys.exit(1)
1391
1392 # Unless we're in pretend mode, there's not much point running without
1393 # root access. We need to be able to install packages.
1394 #
1395 # NOTE: Even if you're running --pretend, it's a good idea to run
1396 # parallel_emerge with root access so that portage can write to the
1397 # dependency cache. This is important for performance.
1398 if "--pretend" not in emerge.opts and portage.secpass < 2:
1399 print "parallel_emerge: superuser access is required."
1400 sys.exit(1)
1401
1402 if "--quiet" not in emerge.opts:
1403 cmdline_packages = " ".join(emerge.cmdline_packages)
David Jamesfcb70ef2011-02-02 16:02:30 -08001404 print "Starting fast-emerge."
1405 print " Building package %s on %s" % (cmdline_packages,
1406 deps.board or "root")
David Jamesfcb70ef2011-02-02 16:02:30 -08001407
David James386ccd12011-05-04 20:17:42 -07001408 deps_tree, deps_info = deps.GenDependencyTree()
David Jamesfcb70ef2011-02-02 16:02:30 -08001409
1410 # You want me to be verbose? I'll give you two trees! Twice as much value.
1411 if "--tree" in emerge.opts and "--verbose" in emerge.opts:
1412 deps.PrintTree(deps_tree)
1413
David James386ccd12011-05-04 20:17:42 -07001414 deps_graph = deps.GenDependencyGraph(deps_tree, deps_info)
David Jamesfcb70ef2011-02-02 16:02:30 -08001415
1416 # OK, time to print out our progress so far.
1417 deps.PrintInstallPlan(deps_graph)
1418 if "--tree" in emerge.opts:
1419 PrintDepsMap(deps_graph)
1420
1421 # Are we upgrading portage? If so, and there are more packages to merge,
1422 # schedule a restart of parallel_emerge to merge the rest. This ensures that
1423 # we pick up all updates to portage settings before merging any more
1424 # packages.
1425 portage_upgrade = False
1426 root = emerge.settings["ROOT"]
1427 final_db = emerge.depgraph._dynamic_config.mydbapi[root]
1428 if root == "/":
1429 for db_pkg in final_db.match_pkgs("sys-apps/portage"):
1430 portage_pkg = deps_graph.get(db_pkg.cpv)
1431 if portage_pkg and len(deps_graph) > 1:
1432 portage_pkg["needs"].clear()
1433 portage_pkg["provides"].clear()
1434 deps_graph = { str(db_pkg.cpv): portage_pkg }
1435 portage_upgrade = True
1436 if "--quiet" not in emerge.opts:
1437 print "Upgrading portage first, then restarting..."
1438
1439 # Run the queued emerges.
1440 scheduler = EmergeQueue(deps_graph, emerge, deps.package_db, deps.show_output)
1441 scheduler.Run()
David James97ce8902011-08-16 09:51:05 -07001442 scheduler = None
David Jamesfcb70ef2011-02-02 16:02:30 -08001443
David Jamesfcb70ef2011-02-02 16:02:30 -08001444 # Update environment (library cache, symlinks, etc.)
1445 if deps.board and "--pretend" not in emerge.opts:
1446 portage.env_update()
1447
1448 # If we already upgraded portage, we don't need to do so again. But we do
1449 # need to upgrade the rest of the packages. So we'll go ahead and do that.
David Jamesebc3ae02011-05-21 20:46:10 -07001450 #
1451 # In order to grant the child permission to run setsid, we need to run sudo
1452 # again. We preserve SUDO_USER here in case an ebuild depends on it.
David Jamesfcb70ef2011-02-02 16:02:30 -08001453 if portage_upgrade:
David Jamesebc3ae02011-05-21 20:46:10 -07001454 sudo = ["sudo", "-E", "SUDO_USER=%s" % os.environ.get("SUDO_USER", "")]
1455 args = sudo + parallel_emerge_args + ["--exclude=sys-apps/portage"]
1456 os.execvp("sudo", args)
David Jamesfcb70ef2011-02-02 16:02:30 -08001457
1458 print "Done"
1459 sys.exit(0)
1460
1461if __name__ == "__main__":
1462 main()