blob: 622d842206bc003637ed0be7d35ff97138184691 [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 Jamesfcb70ef2011-02-02 16:02:30 -0800953 retcode = scheduler.merge()
954 except Exception:
955 traceback.print_exc(file=output)
956 retcode = 1
957 finally:
958 sys.stdout = save_stdout
959 sys.stderr = save_stderr
960 output.close()
961 if retcode is None:
962 retcode = 0
963
David James7358d032011-05-19 10:40:03 -0700964 if KILLED.is_set():
965 return
966
David Jamesfcb70ef2011-02-02 16:02:30 -0800967 job = EmergeJobState(target, pkgname, True, output.name, start_timestamp,
968 retcode)
969 job_queue.put(job)
970
971
972class LinePrinter(object):
973 """Helper object to print a single line."""
974
975 def __init__(self, line):
976 self.line = line
977
978 def Print(self, seek_locations):
979 print self.line
980
981
982class JobPrinter(object):
983 """Helper object to print output of a job."""
984
985 def __init__(self, job, unlink=False):
986 """Print output of job.
987
988 If unlink is True, unlink the job output file when done."""
989 self.current_time = time.time()
990 self.job = job
991 self.unlink = unlink
992
993 def Print(self, seek_locations):
994
995 job = self.job
996
997 # Calculate how long the job has been running.
998 seconds = self.current_time - job.start_timestamp
999
1000 # Note that we've printed out the job so far.
1001 job.last_output_timestamp = self.current_time
1002
1003 # Note that we're starting the job
1004 info = "job %s (%dm%.1fs)" % (job.pkgname, seconds / 60, seconds % 60)
1005 last_output_seek = seek_locations.get(job.filename, 0)
1006 if last_output_seek:
1007 print "=== Continue output for %s ===" % info
1008 else:
1009 print "=== Start output for %s ===" % info
1010
1011 # Print actual output from job
1012 f = codecs.open(job.filename, encoding='utf-8', errors='replace')
1013 f.seek(last_output_seek)
1014 prefix = job.pkgname + ":"
1015 for line in f:
1016
1017 # Save off our position in the file
1018 if line and line[-1] == "\n":
1019 last_output_seek = f.tell()
1020 line = line[:-1]
1021
1022 # Print our line
1023 print prefix, line.encode('utf-8', 'replace')
1024 f.close()
1025
1026 # Save our last spot in the file so that we don't print out the same
1027 # location twice.
1028 seek_locations[job.filename] = last_output_seek
1029
1030 # Note end of output section
1031 if job.done:
1032 print "=== Complete: %s ===" % info
1033 else:
1034 print "=== Still running: %s ===" % info
1035
1036 if self.unlink:
1037 os.unlink(job.filename)
1038
1039
1040def PrintWorker(queue):
1041 """A worker that prints stuff to the screen as requested."""
1042
1043 def ExitHandler(signum, frame):
David James7358d032011-05-19 10:40:03 -07001044 # Set KILLED flag.
1045 KILLED.set()
1046
David Jamesfcb70ef2011-02-02 16:02:30 -08001047 # Switch to default signal handlers so that we'll die after two signals.
David James7358d032011-05-19 10:40:03 -07001048 signal.signal(signal.SIGINT, KillHandler)
1049 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -08001050
1051 # Don't exit on the first SIGINT / SIGTERM, because the parent worker will
1052 # handle it and tell us when we need to exit.
1053 signal.signal(signal.SIGINT, ExitHandler)
1054 signal.signal(signal.SIGTERM, ExitHandler)
1055
1056 # seek_locations is a map indicating the position we are at in each file.
1057 # It starts off empty, but is set by the various Print jobs as we go along
1058 # to indicate where we left off in each file.
1059 seek_locations = {}
1060 while True:
1061 try:
1062 job = queue.get()
1063 if job:
1064 job.Print(seek_locations)
1065 else:
1066 break
1067 except IOError as ex:
1068 if ex.errno == errno.EINTR:
1069 # Looks like we received a signal. Keep printing.
1070 continue
1071 raise
1072
David Jamesfcb70ef2011-02-02 16:02:30 -08001073class EmergeQueue(object):
1074 """Class to schedule emerge jobs according to a dependency graph."""
1075
1076 def __init__(self, deps_map, emerge, package_db, show_output):
1077 # Store the dependency graph.
1078 self._deps_map = deps_map
1079 # Initialize the running queue to empty
1080 self._jobs = {}
David James8c7e5e32011-06-28 11:26:03 -07001081 self._ready = []
David Jamesfcb70ef2011-02-02 16:02:30 -08001082 # List of total package installs represented in deps_map.
1083 install_jobs = [x for x in deps_map if deps_map[x]["action"] == "merge"]
1084 self._total_jobs = len(install_jobs)
1085 self._show_output = show_output
1086
1087 if "--pretend" in emerge.opts:
1088 print "Skipping merge because of --pretend mode."
1089 sys.exit(0)
1090
David James7358d032011-05-19 10:40:03 -07001091 # Set a process group so we can easily terminate all children.
1092 os.setsid()
1093
David Jamesfcb70ef2011-02-02 16:02:30 -08001094 # Setup scheduler graph object. This is used by the child processes
1095 # to help schedule jobs.
1096 emerge.scheduler_graph = emerge.depgraph.schedulerGraph()
1097
1098 # Calculate how many jobs we can run in parallel. We don't want to pass
1099 # the --jobs flag over to emerge itself, because that'll tell emerge to
1100 # hide its output, and said output is quite useful for debugging hung
1101 # jobs.
1102 procs = min(self._total_jobs,
1103 emerge.opts.pop("--jobs", multiprocessing.cpu_count()))
David James8c7e5e32011-06-28 11:26:03 -07001104 self._load_avg = emerge.opts.pop("--load-average", None)
David Jamesfcb70ef2011-02-02 16:02:30 -08001105 self._emerge_queue = multiprocessing.Queue()
1106 self._job_queue = multiprocessing.Queue()
1107 self._print_queue = multiprocessing.Queue()
1108 args = (self._emerge_queue, self._job_queue, emerge, package_db)
1109 self._pool = multiprocessing.Pool(procs, EmergeWorker, args)
1110 self._print_worker = multiprocessing.Process(target=PrintWorker,
1111 args=[self._print_queue])
1112 self._print_worker.start()
1113
1114 # Initialize the failed queue to empty.
1115 self._retry_queue = []
1116 self._failed = set()
1117
David Jamesfcb70ef2011-02-02 16:02:30 -08001118 # Setup an exit handler so that we print nice messages if we are
1119 # terminated.
1120 self._SetupExitHandler()
1121
1122 # Schedule our jobs.
1123 for target, info in deps_map.items():
David James8c7e5e32011-06-28 11:26:03 -07001124 if info["nodeps"] or not info["needs"]:
1125 score = (-len(info["tprovides"]), info["binary"], info["idx"])
1126 self._ready.append((score, target))
1127 heapq.heapify(self._ready)
1128 self._procs = procs
1129 self._ScheduleLoop()
1130
1131 # Print an update.
1132 self._Status()
David Jamesfcb70ef2011-02-02 16:02:30 -08001133
1134 def _SetupExitHandler(self):
1135
1136 def ExitHandler(signum, frame):
David James7358d032011-05-19 10:40:03 -07001137 # Set KILLED flag.
1138 KILLED.set()
David Jamesfcb70ef2011-02-02 16:02:30 -08001139
1140 # Kill our signal handlers so we don't get called recursively
David James7358d032011-05-19 10:40:03 -07001141 signal.signal(signal.SIGINT, KillHandler)
1142 signal.signal(signal.SIGTERM, KillHandler)
David Jamesfcb70ef2011-02-02 16:02:30 -08001143
1144 # Print our current job status
1145 for target, job in self._jobs.iteritems():
1146 if job:
1147 self._print_queue.put(JobPrinter(job, unlink=True))
1148
1149 # Notify the user that we are exiting
1150 self._Print("Exiting on signal %s" % signum)
David James7358d032011-05-19 10:40:03 -07001151 self._print_queue.put(None)
1152 self._print_worker.join()
David Jamesfcb70ef2011-02-02 16:02:30 -08001153
1154 # Kill child threads, then exit.
David James7358d032011-05-19 10:40:03 -07001155 os.killpg(0, signal.SIGKILL)
David Jamesfcb70ef2011-02-02 16:02:30 -08001156 sys.exit(1)
1157
1158 # Print out job status when we are killed
1159 signal.signal(signal.SIGINT, ExitHandler)
1160 signal.signal(signal.SIGTERM, ExitHandler)
1161
1162 def _Schedule(self, target):
1163 # We maintain a tree of all deps, if this doesn't need
David James8c7e5e32011-06-28 11:26:03 -07001164 # to be installed just free up its children and continue.
David Jamesfcb70ef2011-02-02 16:02:30 -08001165 # It is possible to reinstall deps of deps, without reinstalling
1166 # first level deps, like so:
1167 # chromeos (merge) -> eselect (nomerge) -> python (merge)
David James8c7e5e32011-06-28 11:26:03 -07001168 this_pkg = self._deps_map.get(target)
1169 if this_pkg is None:
David James386ccd12011-05-04 20:17:42 -07001170 pass
David James8c7e5e32011-06-28 11:26:03 -07001171 elif this_pkg["action"] == "nomerge":
David Jamesfcb70ef2011-02-02 16:02:30 -08001172 self._Finish(target)
David Jamesd20a6d92011-04-26 16:11:59 -07001173 elif target not in self._jobs:
David Jamesfcb70ef2011-02-02 16:02:30 -08001174 # Kick off the build if it's marked to be built.
1175 self._jobs[target] = None
1176 self._emerge_queue.put(target)
David James8c7e5e32011-06-28 11:26:03 -07001177 return True
David Jamesfcb70ef2011-02-02 16:02:30 -08001178
David James8c7e5e32011-06-28 11:26:03 -07001179 def _ScheduleLoop(self):
1180 # If the current load exceeds our desired load average, don't schedule
1181 # more than one job.
1182 if self._load_avg and os.getloadavg()[0] > self._load_avg:
1183 needed_jobs = 1
1184 else:
1185 needed_jobs = self._procs
1186
1187 # Schedule more jobs.
1188 while self._ready and len(self._jobs) < needed_jobs:
1189 score, pkg = heapq.heappop(self._ready)
1190 self._Schedule(pkg)
David Jamesfcb70ef2011-02-02 16:02:30 -08001191
1192 def _Print(self, line):
1193 """Print a single line."""
1194 self._print_queue.put(LinePrinter(line))
1195
1196 def _Status(self):
1197 """Print status."""
1198 current_time = time.time()
1199 no_output = True
1200
1201 # Print interim output every minute if --show-output is used. Otherwise,
1202 # print notifications about running packages every 2 minutes, and print
1203 # full output for jobs that have been running for 60 minutes or more.
1204 if self._show_output:
1205 interval = 60
1206 notify_interval = 0
1207 else:
1208 interval = 60 * 60
1209 notify_interval = 60 * 2
1210 for target, job in self._jobs.iteritems():
1211 if job:
1212 last_timestamp = max(job.start_timestamp, job.last_output_timestamp)
1213 if last_timestamp + interval < current_time:
1214 self._print_queue.put(JobPrinter(job))
1215 job.last_output_timestamp = current_time
1216 no_output = False
1217 elif (notify_interval and
1218 job.last_notify_timestamp + notify_interval < current_time):
1219 job_seconds = current_time - job.start_timestamp
1220 args = (job.pkgname, job_seconds / 60, job_seconds % 60, job.filename)
1221 info = "Still building %s (%dm%.1fs). Logs in %s" % args
1222 job.last_notify_timestamp = current_time
1223 self._Print(info)
1224 no_output = False
1225
1226 # If we haven't printed any messages yet, print a general status message
1227 # here.
1228 if no_output:
1229 seconds = current_time - GLOBAL_START
1230 line = ("Pending %s, Ready %s, Running %s, Retrying %s, Total %s "
1231 "[Time %dm%.1fs Load %s]")
David James8c7e5e32011-06-28 11:26:03 -07001232 load = " ".join(str(x) for x in os.getloadavg())
1233 self._Print(line % (len(self._deps_map), len(self._ready),
1234 len(self._jobs), len(self._retry_queue),
1235 self._total_jobs, seconds / 60, seconds % 60, load))
David Jamesfcb70ef2011-02-02 16:02:30 -08001236
1237 def _Finish(self, target):
David James8c7e5e32011-06-28 11:26:03 -07001238 """Mark a target as completed and unblock dependencies."""
1239 this_pkg = self._deps_map[target]
1240 if this_pkg["needs"] and this_pkg["nodeps"]:
1241 # We got installed, but our deps have not been installed yet. Dependent
1242 # packages should only be installed when our needs have been fully met.
1243 this_pkg["action"] = "nomerge"
1244 else:
1245 finish = []
1246 for dep in this_pkg["provides"]:
1247 dep_pkg = self._deps_map[dep]
1248 del dep_pkg["needs"][target]
1249 if not dep_pkg["needs"]:
1250 if dep_pkg["nodeps"] and dep_pkg["action"] == "nomerge":
1251 self._Finish(dep)
1252 else:
1253 score = (-len(dep_pkg["tprovides"]), dep_pkg["binary"],
1254 dep_pkg["idx"])
1255 heapq.heappush(self._ready, (score, dep))
1256 self._deps_map.pop(target)
David Jamesfcb70ef2011-02-02 16:02:30 -08001257
1258 def _Retry(self):
David James8c7e5e32011-06-28 11:26:03 -07001259 while self._retry_queue:
David Jamesfcb70ef2011-02-02 16:02:30 -08001260 target = self._retry_queue.pop(0)
David James8c7e5e32011-06-28 11:26:03 -07001261 if self._Schedule(target):
1262 self._Print("Retrying emerge of %s." % target)
1263 break
David Jamesfcb70ef2011-02-02 16:02:30 -08001264
1265 def _Exit(self):
1266 # Tell emerge workers to exit. They all exit when 'None' is pushed
1267 # to the queue.
1268 self._emerge_queue.put(None)
1269 self._pool.close()
1270 self._pool.join()
1271
1272 # Now that our workers are finished, we can kill the print queue.
1273 self._print_queue.put(None)
1274 self._print_worker.join()
1275
1276 def Run(self):
1277 """Run through the scheduled ebuilds.
1278
1279 Keep running so long as we have uninstalled packages in the
1280 dependency graph to merge.
1281 """
1282 while self._deps_map:
1283 # Check here that we are actually waiting for something.
1284 if (self._emerge_queue.empty() and
1285 self._job_queue.empty() and
1286 not self._jobs and
David James8c7e5e32011-06-28 11:26:03 -07001287 not self._ready and
David Jamesfcb70ef2011-02-02 16:02:30 -08001288 self._deps_map):
1289 # If we have failed on a package, retry it now.
1290 if self._retry_queue:
1291 self._Retry()
1292 else:
1293 # Tell child threads to exit.
1294 self._Exit()
1295
1296 # The dependency map is helpful for debugging failures.
1297 PrintDepsMap(self._deps_map)
1298
1299 # Tell the user why we're exiting.
1300 if self._failed:
1301 print "Packages failed: %s" % " ,".join(self._failed)
1302 else:
1303 print "Deadlock! Circular dependencies!"
1304 sys.exit(1)
1305
1306 try:
1307 job = self._job_queue.get(timeout=5)
1308 except Queue.Empty:
1309 # Print an update.
David James8c7e5e32011-06-28 11:26:03 -07001310 self._ScheduleLoop()
David Jamesfcb70ef2011-02-02 16:02:30 -08001311 self._Status()
1312 continue
1313
1314 target = job.target
1315
1316 if not job.done:
1317 self._jobs[target] = job
1318 self._Print("Started %s (logged in %s)" % (target, job.filename))
1319 continue
1320
1321 # Print output of job
1322 if self._show_output or job.retcode != 0:
1323 self._print_queue.put(JobPrinter(job, unlink=True))
1324 else:
1325 os.unlink(job.filename)
1326 del self._jobs[target]
1327
1328 seconds = time.time() - job.start_timestamp
1329 details = "%s (in %dm%.1fs)" % (target, seconds / 60, seconds % 60)
1330
1331 # Complain if necessary.
1332 if job.retcode != 0:
1333 # Handle job failure.
1334 if target in self._failed:
1335 # If this job has failed previously, give up.
1336 self._Print("Failed %s. Your build has failed." % details)
1337 else:
1338 # Queue up this build to try again after a long while.
1339 self._retry_queue.append(target)
1340 self._failed.add(target)
1341 self._Print("Failed %s, retrying later." % details)
1342 else:
1343 if target in self._failed and self._retry_queue:
1344 # If we have successfully retried a failed package, and there
1345 # are more failed packages, try the next one. We will only have
1346 # one retrying package actively running at a time.
1347 self._Retry()
1348
1349 self._Print("Completed %s" % details)
1350 # Mark as completed and unblock waiting ebuilds.
1351 self._Finish(target)
1352
David James8c7e5e32011-06-28 11:26:03 -07001353 # Schedule pending jobs and print an update.
1354 self._ScheduleLoop()
1355 self._Status()
David Jamesfcb70ef2011-02-02 16:02:30 -08001356
1357 # Tell child threads to exit.
1358 self._Print("Merge complete")
1359 self._Exit()
1360
1361
1362def main():
1363
David James57437532011-05-06 15:51:21 -07001364 parallel_emerge_args = sys.argv[:]
David Jamesfcb70ef2011-02-02 16:02:30 -08001365 deps = DepGraphGenerator()
David James57437532011-05-06 15:51:21 -07001366 deps.Initialize(parallel_emerge_args[1:])
David Jamesfcb70ef2011-02-02 16:02:30 -08001367 emerge = deps.emerge
1368
1369 if emerge.action is not None:
1370 sys.argv = deps.ParseParallelEmergeArgs(sys.argv)
1371 sys.exit(emerge_main())
1372 elif not emerge.cmdline_packages:
1373 Usage()
1374 sys.exit(1)
1375
1376 # Unless we're in pretend mode, there's not much point running without
1377 # root access. We need to be able to install packages.
1378 #
1379 # NOTE: Even if you're running --pretend, it's a good idea to run
1380 # parallel_emerge with root access so that portage can write to the
1381 # dependency cache. This is important for performance.
1382 if "--pretend" not in emerge.opts and portage.secpass < 2:
1383 print "parallel_emerge: superuser access is required."
1384 sys.exit(1)
1385
1386 if "--quiet" not in emerge.opts:
1387 cmdline_packages = " ".join(emerge.cmdline_packages)
David Jamesfcb70ef2011-02-02 16:02:30 -08001388 print "Starting fast-emerge."
1389 print " Building package %s on %s" % (cmdline_packages,
1390 deps.board or "root")
David Jamesfcb70ef2011-02-02 16:02:30 -08001391
David James386ccd12011-05-04 20:17:42 -07001392 deps_tree, deps_info = deps.GenDependencyTree()
David Jamesfcb70ef2011-02-02 16:02:30 -08001393
1394 # You want me to be verbose? I'll give you two trees! Twice as much value.
1395 if "--tree" in emerge.opts and "--verbose" in emerge.opts:
1396 deps.PrintTree(deps_tree)
1397
David James386ccd12011-05-04 20:17:42 -07001398 deps_graph = deps.GenDependencyGraph(deps_tree, deps_info)
David Jamesfcb70ef2011-02-02 16:02:30 -08001399
1400 # OK, time to print out our progress so far.
1401 deps.PrintInstallPlan(deps_graph)
1402 if "--tree" in emerge.opts:
1403 PrintDepsMap(deps_graph)
1404
1405 # Are we upgrading portage? If so, and there are more packages to merge,
1406 # schedule a restart of parallel_emerge to merge the rest. This ensures that
1407 # we pick up all updates to portage settings before merging any more
1408 # packages.
1409 portage_upgrade = False
1410 root = emerge.settings["ROOT"]
1411 final_db = emerge.depgraph._dynamic_config.mydbapi[root]
1412 if root == "/":
1413 for db_pkg in final_db.match_pkgs("sys-apps/portage"):
1414 portage_pkg = deps_graph.get(db_pkg.cpv)
1415 if portage_pkg and len(deps_graph) > 1:
1416 portage_pkg["needs"].clear()
1417 portage_pkg["provides"].clear()
1418 deps_graph = { str(db_pkg.cpv): portage_pkg }
1419 portage_upgrade = True
1420 if "--quiet" not in emerge.opts:
1421 print "Upgrading portage first, then restarting..."
1422
1423 # Run the queued emerges.
1424 scheduler = EmergeQueue(deps_graph, emerge, deps.package_db, deps.show_output)
1425 scheduler.Run()
1426
David Jamesfcb70ef2011-02-02 16:02:30 -08001427 # Update environment (library cache, symlinks, etc.)
1428 if deps.board and "--pretend" not in emerge.opts:
1429 portage.env_update()
1430
1431 # If we already upgraded portage, we don't need to do so again. But we do
1432 # need to upgrade the rest of the packages. So we'll go ahead and do that.
David Jamesebc3ae02011-05-21 20:46:10 -07001433 #
1434 # In order to grant the child permission to run setsid, we need to run sudo
1435 # again. We preserve SUDO_USER here in case an ebuild depends on it.
David Jamesfcb70ef2011-02-02 16:02:30 -08001436 if portage_upgrade:
David Jamesebc3ae02011-05-21 20:46:10 -07001437 sudo = ["sudo", "-E", "SUDO_USER=%s" % os.environ.get("SUDO_USER", "")]
1438 args = sudo + parallel_emerge_args + ["--exclude=sys-apps/portage"]
1439 os.execvp("sudo", args)
David Jamesfcb70ef2011-02-02 16:02:30 -08001440
1441 print "Done"
1442 sys.exit(0)
1443
1444if __name__ == "__main__":
1445 main()