Mike Frysinger | 9f7e4ee | 2013-03-13 15:43:03 -0400 | [diff] [blame] | 1 | #!/usr/bin/python |
Mike Frysinger | 0a647fc | 2012-08-06 14:36:05 -0400 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 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 | |
| 8 | Usage: |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 9 | ./parallel_emerge [--board=BOARD] [--workon=PKGS] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 10 | [--force-remote-binary=PKGS] [emerge args] package |
| 11 | |
David James | 78b6cd9 | 2012-04-02 21:36:12 -0700 | [diff] [blame] | 12 | This script runs multiple emerge processes in parallel, using appropriate |
| 13 | Portage APIs. It is faster than standard emerge because it has a |
| 14 | multiprocess model instead of an asynchronous model. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 15 | """ |
| 16 | |
| 17 | import codecs |
| 18 | import copy |
| 19 | import errno |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 20 | import gc |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 21 | import heapq |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 22 | import multiprocessing |
| 23 | import os |
| 24 | import Queue |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 25 | import signal |
| 26 | import sys |
| 27 | import tempfile |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 28 | import threading |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 29 | import time |
| 30 | import traceback |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 31 | |
| 32 | # If PORTAGE_USERNAME isn't specified, scrape it from the $HOME variable. On |
| 33 | # Chromium OS, the default "portage" user doesn't have the necessary |
| 34 | # permissions. It'd be easier if we could default to $USERNAME, but $USERNAME |
| 35 | # is "root" here because we get called through sudo. |
| 36 | # |
| 37 | # We need to set this before importing any portage modules, because portage |
| 38 | # looks up "PORTAGE_USERNAME" at import time. |
| 39 | # |
| 40 | # NOTE: .bashrc sets PORTAGE_USERNAME = $USERNAME, so most people won't |
| 41 | # encounter this case unless they have an old chroot or blow away the |
| 42 | # environment by running sudo without the -E specifier. |
| 43 | if "PORTAGE_USERNAME" not in os.environ: |
| 44 | homedir = os.environ.get("HOME") |
| 45 | if homedir: |
| 46 | os.environ["PORTAGE_USERNAME"] = os.path.basename(homedir) |
| 47 | |
| 48 | # Portage doesn't expose dependency trees in its public API, so we have to |
| 49 | # make use of some private APIs here. These modules are found under |
| 50 | # /usr/lib/portage/pym/. |
| 51 | # |
| 52 | # TODO(davidjames): Update Portage to expose public APIs for these features. |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 53 | # pylint: disable=W0212 |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 54 | from _emerge.actions import adjust_configs |
| 55 | from _emerge.actions import load_emerge_config |
| 56 | from _emerge.create_depgraph_params import create_depgraph_params |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 57 | from _emerge.depgraph import backtrack_depgraph |
Mike Frysinger | 901eaad | 2012-10-10 18:18:03 -0400 | [diff] [blame] | 58 | try: |
| 59 | from _emerge.main import clean_logs |
| 60 | except ImportError: |
| 61 | # Older portage versions did not provide clean_logs, so stub it. |
| 62 | # We need this if running in an older chroot that hasn't yet upgraded |
| 63 | # the portage version. |
| 64 | clean_logs = lambda x: None |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 65 | from _emerge.main import emerge_main |
| 66 | from _emerge.main import parse_opts |
| 67 | from _emerge.Package import Package |
| 68 | from _emerge.Scheduler import Scheduler |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 69 | from _emerge.stdout_spinner import stdout_spinner |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 70 | from portage._global_updates import _global_updates |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 71 | import portage |
| 72 | import portage.debug |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 73 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 74 | def Usage(): |
| 75 | """Print usage.""" |
| 76 | print "Usage:" |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 77 | print " ./parallel_emerge [--board=BOARD] [--workon=PKGS]" |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 78 | print " [--rebuild] [emerge args] package" |
| 79 | print |
| 80 | print "Packages specified as workon packages are always built from source." |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 81 | print |
| 82 | print "The --workon argument is mainly useful when you want to build and" |
| 83 | print "install packages that you are working on unconditionally, but do not" |
| 84 | print "to have to rev the package to indicate you want to build it from" |
| 85 | print "source. The build_packages script will automatically supply the" |
| 86 | print "workon argument to emerge, ensuring that packages selected using" |
| 87 | print "cros-workon are rebuilt." |
| 88 | print |
| 89 | print "The --rebuild option rebuilds packages whenever their dependencies" |
| 90 | print "are changed. This ensures that your build is correct." |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 91 | |
| 92 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 93 | # Global start time |
| 94 | GLOBAL_START = time.time() |
| 95 | |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 96 | # Whether process has been killed by a signal. |
| 97 | KILLED = multiprocessing.Event() |
| 98 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 99 | |
| 100 | class EmergeData(object): |
| 101 | """This simple struct holds various emerge variables. |
| 102 | |
| 103 | This struct helps us easily pass emerge variables around as a unit. |
| 104 | These variables are used for calculating dependencies and installing |
| 105 | packages. |
| 106 | """ |
| 107 | |
David James | bf1e344 | 2011-05-28 07:44:20 -0700 | [diff] [blame] | 108 | __slots__ = ["action", "cmdline_packages", "depgraph", "favorites", |
| 109 | "mtimedb", "opts", "root_config", "scheduler_graph", |
| 110 | "settings", "spinner", "trees"] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 111 | |
| 112 | def __init__(self): |
| 113 | # The action the user requested. If the user is installing packages, this |
| 114 | # is None. If the user is doing anything other than installing packages, |
| 115 | # this will contain the action name, which will map exactly to the |
| 116 | # long-form name of the associated emerge option. |
| 117 | # |
| 118 | # Example: If you call parallel_emerge --unmerge package, the action name |
| 119 | # will be "unmerge" |
| 120 | self.action = None |
| 121 | |
| 122 | # The list of packages the user passed on the command-line. |
| 123 | self.cmdline_packages = None |
| 124 | |
| 125 | # The emerge dependency graph. It'll contain all the packages involved in |
| 126 | # this merge, along with their versions. |
| 127 | self.depgraph = None |
| 128 | |
David James | bf1e344 | 2011-05-28 07:44:20 -0700 | [diff] [blame] | 129 | # The list of candidates to add to the world file. |
| 130 | self.favorites = None |
| 131 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 132 | # A dict of the options passed to emerge. This dict has been cleaned up |
| 133 | # a bit by parse_opts, so that it's a bit easier for the emerge code to |
| 134 | # look at the options. |
| 135 | # |
| 136 | # Emerge takes a few shortcuts in its cleanup process to make parsing of |
| 137 | # the options dict easier. For example, if you pass in "--usepkg=n", the |
| 138 | # "--usepkg" flag is just left out of the dictionary altogether. Because |
| 139 | # --usepkg=n is the default, this makes parsing easier, because emerge |
| 140 | # can just assume that if "--usepkg" is in the dictionary, it's enabled. |
| 141 | # |
| 142 | # These cleanup processes aren't applied to all options. For example, the |
| 143 | # --with-bdeps flag is passed in as-is. For a full list of the cleanups |
| 144 | # applied by emerge, see the parse_opts function in the _emerge.main |
| 145 | # package. |
| 146 | self.opts = None |
| 147 | |
| 148 | # A dictionary used by portage to maintain global state. This state is |
| 149 | # loaded from disk when portage starts up, and saved to disk whenever we |
| 150 | # call mtimedb.commit(). |
| 151 | # |
| 152 | # This database contains information about global updates (i.e., what |
| 153 | # version of portage we have) and what we're currently doing. Portage |
| 154 | # saves what it is currently doing in this database so that it can be |
| 155 | # resumed when you call it with the --resume option. |
| 156 | # |
| 157 | # parallel_emerge does not save what it is currently doing in the mtimedb, |
| 158 | # so we do not support the --resume option. |
| 159 | self.mtimedb = None |
| 160 | |
| 161 | # The portage configuration for our current root. This contains the portage |
| 162 | # settings (see below) and the three portage trees for our current root. |
| 163 | # (The three portage trees are explained below, in the documentation for |
| 164 | # the "trees" member.) |
| 165 | self.root_config = None |
| 166 | |
| 167 | # The scheduler graph is used by emerge to calculate what packages to |
| 168 | # install. We don't actually install any deps, so this isn't really used, |
| 169 | # but we pass it in to the Scheduler object anyway. |
| 170 | self.scheduler_graph = None |
| 171 | |
| 172 | # Portage settings for our current session. Most of these settings are set |
| 173 | # in make.conf inside our current install root. |
| 174 | self.settings = None |
| 175 | |
| 176 | # The spinner, which spews stuff to stdout to indicate that portage is |
| 177 | # doing something. We maintain our own spinner, so we set the portage |
| 178 | # spinner to "silent" mode. |
| 179 | self.spinner = None |
| 180 | |
| 181 | # The portage trees. There are separate portage trees for each root. To get |
| 182 | # the portage tree for the current root, you can look in self.trees[root], |
| 183 | # where root = self.settings["ROOT"]. |
| 184 | # |
| 185 | # In each root, there are three trees: vartree, porttree, and bintree. |
| 186 | # - vartree: A database of the currently-installed packages. |
| 187 | # - porttree: A database of ebuilds, that can be used to build packages. |
| 188 | # - bintree: A database of binary packages. |
| 189 | self.trees = None |
| 190 | |
| 191 | |
| 192 | class DepGraphGenerator(object): |
| 193 | """Grab dependency information about packages from portage. |
| 194 | |
| 195 | Typical usage: |
| 196 | deps = DepGraphGenerator() |
| 197 | deps.Initialize(sys.argv[1:]) |
| 198 | deps_tree, deps_info = deps.GenDependencyTree() |
| 199 | deps_graph = deps.GenDependencyGraph(deps_tree, deps_info) |
| 200 | deps.PrintTree(deps_tree) |
| 201 | PrintDepsMap(deps_graph) |
| 202 | """ |
| 203 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 204 | __slots__ = ["board", "emerge", "package_db", "show_output"] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 205 | |
| 206 | def __init__(self): |
| 207 | self.board = None |
| 208 | self.emerge = EmergeData() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 209 | self.package_db = {} |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 210 | self.show_output = False |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 211 | |
| 212 | def ParseParallelEmergeArgs(self, argv): |
| 213 | """Read the parallel emerge arguments from the command-line. |
| 214 | |
| 215 | We need to be compatible with emerge arg format. We scrape arguments that |
| 216 | are specific to parallel_emerge, and pass through the rest directly to |
| 217 | emerge. |
| 218 | Args: |
| 219 | argv: arguments list |
| 220 | Returns: |
| 221 | Arguments that don't belong to parallel_emerge |
| 222 | """ |
| 223 | emerge_args = [] |
| 224 | for arg in argv: |
| 225 | # Specifically match arguments that are specific to parallel_emerge, and |
| 226 | # pass through the rest. |
| 227 | if arg.startswith("--board="): |
| 228 | self.board = arg.replace("--board=", "") |
| 229 | elif arg.startswith("--workon="): |
| 230 | workon_str = arg.replace("--workon=", "") |
David James | 7a1ea4b | 2011-10-13 15:06:41 -0700 | [diff] [blame] | 231 | emerge_args.append("--reinstall-atoms=%s" % workon_str) |
| 232 | emerge_args.append("--usepkg-exclude=%s" % workon_str) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 233 | elif arg.startswith("--force-remote-binary="): |
| 234 | force_remote_binary = arg.replace("--force-remote-binary=", "") |
David James | 7a1ea4b | 2011-10-13 15:06:41 -0700 | [diff] [blame] | 235 | emerge_args.append("--useoldpkg-atoms=%s" % force_remote_binary) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 236 | elif arg == "--show-output": |
| 237 | self.show_output = True |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 238 | elif arg == "--rebuild": |
David James | 7a1ea4b | 2011-10-13 15:06:41 -0700 | [diff] [blame] | 239 | emerge_args.append("--rebuild-if-unbuilt") |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 240 | else: |
| 241 | # Not one of our options, so pass through to emerge. |
| 242 | emerge_args.append(arg) |
| 243 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 244 | # These packages take a really long time to build, so, for expediency, we |
| 245 | # are blacklisting them from automatic rebuilds because one of their |
| 246 | # dependencies needs to be recompiled. |
| 247 | for pkg in ("chromeos-base/chromeos-chrome", "media-plugins/o3d", |
| 248 | "dev-java/icedtea"): |
David James | 7a1ea4b | 2011-10-13 15:06:41 -0700 | [diff] [blame] | 249 | emerge_args.append("--rebuild-exclude=%s" % pkg) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 250 | |
| 251 | return emerge_args |
| 252 | |
| 253 | def Initialize(self, args): |
| 254 | """Initializer. Parses arguments and sets up portage state.""" |
| 255 | |
| 256 | # Parse and strip out args that are just intended for parallel_emerge. |
| 257 | emerge_args = self.ParseParallelEmergeArgs(args) |
| 258 | |
| 259 | # Setup various environment variables based on our current board. These |
| 260 | # variables are normally setup inside emerge-${BOARD}, but since we don't |
| 261 | # call that script, we have to set it up here. These variables serve to |
| 262 | # point our tools at /build/BOARD and to setup cross compiles to the |
| 263 | # appropriate board as configured in toolchain.conf. |
| 264 | if self.board: |
| 265 | os.environ["PORTAGE_CONFIGROOT"] = "/build/" + self.board |
| 266 | os.environ["PORTAGE_SYSROOT"] = "/build/" + self.board |
| 267 | os.environ["SYSROOT"] = "/build/" + self.board |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 268 | |
| 269 | # Although CHROMEOS_ROOT isn't specific to boards, it's normally setup |
| 270 | # inside emerge-${BOARD}, so we set it up here for compatibility. It |
| 271 | # will be going away soon as we migrate to CROS_WORKON_SRCROOT. |
| 272 | os.environ.setdefault("CHROMEOS_ROOT", os.environ["HOME"] + "/trunk") |
| 273 | |
| 274 | # Turn off interactive delays |
| 275 | os.environ["EBEEP_IGNORE"] = "1" |
| 276 | os.environ["EPAUSE_IGNORE"] = "1" |
Mike Frysinger | 0a647fc | 2012-08-06 14:36:05 -0400 | [diff] [blame] | 277 | os.environ["CLEAN_DELAY"] = "0" |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 278 | |
| 279 | # Parse the emerge options. |
David James | ea3ca33 | 2011-05-26 11:48:29 -0700 | [diff] [blame] | 280 | action, opts, cmdline_packages = parse_opts(emerge_args, silent=True) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 281 | |
| 282 | # Set environment variables based on options. Portage normally sets these |
| 283 | # environment variables in emerge_main, but we can't use that function, |
| 284 | # because it also does a bunch of other stuff that we don't want. |
| 285 | # TODO(davidjames): Patch portage to move this logic into a function we can |
| 286 | # reuse here. |
| 287 | if "--debug" in opts: |
| 288 | os.environ["PORTAGE_DEBUG"] = "1" |
| 289 | if "--config-root" in opts: |
| 290 | os.environ["PORTAGE_CONFIGROOT"] = opts["--config-root"] |
| 291 | if "--root" in opts: |
| 292 | os.environ["ROOT"] = opts["--root"] |
| 293 | if "--accept-properties" in opts: |
| 294 | os.environ["ACCEPT_PROPERTIES"] = opts["--accept-properties"] |
| 295 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 296 | # If we're installing packages to the board, and we're not using the |
David James | 927a56d | 2012-04-03 11:26:39 -0700 | [diff] [blame] | 297 | # official flag, we can disable vardb locks. This is safe because we |
| 298 | # only run up to one instance of parallel_emerge in parallel. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 299 | if self.board and os.environ.get("CHROMEOS_OFFICIAL") != "1": |
| 300 | os.environ.setdefault("PORTAGE_LOCKS", "false") |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 301 | |
| 302 | # Now that we've setup the necessary environment variables, we can load the |
| 303 | # emerge config from disk. |
| 304 | settings, trees, mtimedb = load_emerge_config() |
| 305 | |
David James | ea3ca33 | 2011-05-26 11:48:29 -0700 | [diff] [blame] | 306 | # Add in EMERGE_DEFAULT_OPTS, if specified. |
| 307 | tmpcmdline = [] |
| 308 | if "--ignore-default-opts" not in opts: |
| 309 | tmpcmdline.extend(settings["EMERGE_DEFAULT_OPTS"].split()) |
| 310 | tmpcmdline.extend(emerge_args) |
| 311 | action, opts, cmdline_packages = parse_opts(tmpcmdline) |
| 312 | |
| 313 | # If we're installing to the board, we want the --root-deps option so that |
| 314 | # portage will install the build dependencies to that location as well. |
| 315 | if self.board: |
| 316 | opts.setdefault("--root-deps", True) |
| 317 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 318 | # Check whether our portage tree is out of date. Typically, this happens |
| 319 | # when you're setting up a new portage tree, such as in setup_board and |
| 320 | # make_chroot. In that case, portage applies a bunch of global updates |
| 321 | # here. Once the updates are finished, we need to commit any changes |
| 322 | # that the global update made to our mtimedb, and reload the config. |
| 323 | # |
| 324 | # Portage normally handles this logic in emerge_main, but again, we can't |
| 325 | # use that function here. |
| 326 | if _global_updates(trees, mtimedb["updates"]): |
| 327 | mtimedb.commit() |
| 328 | settings, trees, mtimedb = load_emerge_config(trees=trees) |
| 329 | |
| 330 | # Setup implied options. Portage normally handles this logic in |
| 331 | # emerge_main. |
| 332 | if "--buildpkgonly" in opts or "buildpkg" in settings.features: |
| 333 | opts.setdefault("--buildpkg", True) |
| 334 | if "--getbinpkgonly" in opts: |
| 335 | opts.setdefault("--usepkgonly", True) |
| 336 | opts.setdefault("--getbinpkg", True) |
| 337 | if "getbinpkg" in settings.features: |
| 338 | # Per emerge_main, FEATURES=getbinpkg overrides --getbinpkg=n |
| 339 | opts["--getbinpkg"] = True |
| 340 | if "--getbinpkg" in opts or "--usepkgonly" in opts: |
| 341 | opts.setdefault("--usepkg", True) |
| 342 | if "--fetch-all-uri" in opts: |
| 343 | opts.setdefault("--fetchonly", True) |
| 344 | if "--skipfirst" in opts: |
| 345 | opts.setdefault("--resume", True) |
| 346 | if "--buildpkgonly" in opts: |
| 347 | # --buildpkgonly will not merge anything, so it overrides all binary |
| 348 | # package options. |
| 349 | for opt in ("--getbinpkg", "--getbinpkgonly", |
| 350 | "--usepkg", "--usepkgonly"): |
| 351 | opts.pop(opt, None) |
| 352 | if (settings.get("PORTAGE_DEBUG", "") == "1" and |
| 353 | "python-trace" in settings.features): |
| 354 | portage.debug.set_trace(True) |
| 355 | |
| 356 | # Complain about unsupported options |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 357 | for opt in ("--ask", "--ask-enter-invalid", "--resume", "--skipfirst"): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 358 | if opt in opts: |
| 359 | print "%s is not supported by parallel_emerge" % opt |
| 360 | sys.exit(1) |
| 361 | |
| 362 | # Make emerge specific adjustments to the config (e.g. colors!) |
| 363 | adjust_configs(opts, trees) |
| 364 | |
| 365 | # Save our configuration so far in the emerge object |
| 366 | emerge = self.emerge |
| 367 | emerge.action, emerge.opts = action, opts |
| 368 | emerge.settings, emerge.trees, emerge.mtimedb = settings, trees, mtimedb |
| 369 | emerge.cmdline_packages = cmdline_packages |
| 370 | root = settings["ROOT"] |
| 371 | emerge.root_config = trees[root]["root_config"] |
| 372 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 373 | if "--usepkg" in opts: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 374 | emerge.trees[root]["bintree"].populate("--getbinpkg" in opts) |
| 375 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 376 | def CreateDepgraph(self, emerge, packages): |
| 377 | """Create an emerge depgraph object.""" |
| 378 | # Setup emerge options. |
| 379 | emerge_opts = emerge.opts.copy() |
| 380 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 381 | # Ask portage to build a dependency graph. with the options we specified |
| 382 | # above. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 383 | params = create_depgraph_params(emerge_opts, emerge.action) |
David James | bf1e344 | 2011-05-28 07:44:20 -0700 | [diff] [blame] | 384 | success, depgraph, favorites = backtrack_depgraph( |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 385 | emerge.settings, emerge.trees, emerge_opts, params, emerge.action, |
| 386 | packages, emerge.spinner) |
| 387 | emerge.depgraph = depgraph |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 388 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 389 | # Is it impossible to honor the user's request? Bail! |
| 390 | if not success: |
| 391 | depgraph.display_problems() |
| 392 | sys.exit(1) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 393 | |
| 394 | emerge.depgraph = depgraph |
David James | bf1e344 | 2011-05-28 07:44:20 -0700 | [diff] [blame] | 395 | emerge.favorites = favorites |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 396 | |
David James | deebd69 | 2011-05-09 17:02:52 -0700 | [diff] [blame] | 397 | # Prime and flush emerge caches. |
| 398 | root = emerge.settings["ROOT"] |
| 399 | vardb = emerge.trees[root]["vartree"].dbapi |
David James | 0bdc5de | 2011-05-12 16:22:26 -0700 | [diff] [blame] | 400 | if "--pretend" not in emerge.opts: |
| 401 | vardb.counter_tick() |
David James | deebd69 | 2011-05-09 17:02:52 -0700 | [diff] [blame] | 402 | vardb.flush_cache() |
| 403 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 404 | def GenDependencyTree(self): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 405 | """Get dependency tree info from emerge. |
| 406 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 407 | Returns: |
| 408 | Dependency tree |
| 409 | """ |
| 410 | start = time.time() |
| 411 | |
| 412 | emerge = self.emerge |
| 413 | |
| 414 | # Create a list of packages to merge |
| 415 | packages = set(emerge.cmdline_packages[:]) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 416 | |
| 417 | # Tell emerge to be quiet. We print plenty of info ourselves so we don't |
| 418 | # need any extra output from portage. |
| 419 | portage.util.noiselimit = -1 |
| 420 | |
| 421 | # My favorite feature: The silent spinner. It doesn't spin. Ever. |
| 422 | # I'd disable the colors by default too, but they look kind of cool. |
| 423 | emerge.spinner = stdout_spinner() |
| 424 | emerge.spinner.update = emerge.spinner.update_quiet |
| 425 | |
| 426 | if "--quiet" not in emerge.opts: |
| 427 | print "Calculating deps..." |
| 428 | |
| 429 | self.CreateDepgraph(emerge, packages) |
| 430 | depgraph = emerge.depgraph |
| 431 | |
| 432 | # Build our own tree from the emerge digraph. |
| 433 | deps_tree = {} |
| 434 | digraph = depgraph._dynamic_config.digraph |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 435 | root = emerge.settings["ROOT"] |
| 436 | final_db = depgraph._dynamic_config.mydbapi[root] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 437 | for node, node_deps in digraph.nodes.items(): |
| 438 | # Calculate dependency packages that need to be installed first. Each |
| 439 | # child on the digraph is a dependency. The "operation" field specifies |
| 440 | # what we're doing (e.g. merge, uninstall, etc.). The "priorities" array |
| 441 | # contains the type of dependency (e.g. build, runtime, runtime_post, |
| 442 | # etc.) |
| 443 | # |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 444 | # Portage refers to the identifiers for packages as a CPV. This acronym |
| 445 | # stands for Component/Path/Version. |
| 446 | # |
| 447 | # Here's an example CPV: chromeos-base/power_manager-0.0.1-r1 |
| 448 | # Split up, this CPV would be: |
| 449 | # C -- Component: chromeos-base |
| 450 | # P -- Path: power_manager |
| 451 | # V -- Version: 0.0.1-r1 |
| 452 | # |
| 453 | # We just refer to CPVs as packages here because it's easier. |
| 454 | deps = {} |
| 455 | for child, priorities in node_deps[0].items(): |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 456 | if isinstance(child, Package) and child.root == root: |
| 457 | cpv = str(child.cpv) |
| 458 | action = str(child.operation) |
| 459 | |
| 460 | # If we're uninstalling a package, check whether Portage is |
| 461 | # installing a replacement. If so, just depend on the installation |
| 462 | # of the new package, because the old package will automatically |
| 463 | # be uninstalled at that time. |
| 464 | if action == "uninstall": |
| 465 | for pkg in final_db.match_pkgs(child.slot_atom): |
| 466 | cpv = str(pkg.cpv) |
| 467 | action = "merge" |
| 468 | break |
| 469 | |
| 470 | deps[cpv] = dict(action=action, |
| 471 | deptypes=[str(x) for x in priorities], |
| 472 | deps={}) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 473 | |
| 474 | # We've built our list of deps, so we can add our package to the tree. |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 475 | if isinstance(node, Package) and node.root == root: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 476 | deps_tree[str(node.cpv)] = dict(action=str(node.operation), |
| 477 | deps=deps) |
| 478 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 479 | # Ask portage for its install plan, so that we can only throw out |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 480 | # dependencies that portage throws out. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 481 | deps_info = {} |
| 482 | for pkg in depgraph.altlist(): |
| 483 | if isinstance(pkg, Package): |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 484 | assert pkg.root == root |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 485 | self.package_db[pkg.cpv] = pkg |
| 486 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 487 | # Save off info about the package |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 488 | deps_info[str(pkg.cpv)] = {"idx": len(deps_info)} |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 489 | |
| 490 | seconds = time.time() - start |
| 491 | if "--quiet" not in emerge.opts: |
| 492 | print "Deps calculated in %dm%.1fs" % (seconds / 60, seconds % 60) |
| 493 | |
| 494 | return deps_tree, deps_info |
| 495 | |
| 496 | def PrintTree(self, deps, depth=""): |
| 497 | """Print the deps we have seen in the emerge output. |
| 498 | |
| 499 | Args: |
| 500 | deps: Dependency tree structure. |
| 501 | depth: Allows printing the tree recursively, with indentation. |
| 502 | """ |
| 503 | for entry in sorted(deps): |
| 504 | action = deps[entry]["action"] |
| 505 | print "%s %s (%s)" % (depth, entry, action) |
| 506 | self.PrintTree(deps[entry]["deps"], depth=depth + " ") |
| 507 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 508 | def GenDependencyGraph(self, deps_tree, deps_info): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 509 | """Generate a doubly linked dependency graph. |
| 510 | |
| 511 | Args: |
| 512 | deps_tree: Dependency tree structure. |
| 513 | deps_info: More details on the dependencies. |
| 514 | Returns: |
| 515 | Deps graph in the form of a dict of packages, with each package |
| 516 | specifying a "needs" list and "provides" list. |
| 517 | """ |
| 518 | emerge = self.emerge |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 519 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 520 | # deps_map is the actual dependency graph. |
| 521 | # |
| 522 | # Each package specifies a "needs" list and a "provides" list. The "needs" |
| 523 | # list indicates which packages we depend on. The "provides" list |
| 524 | # indicates the reverse dependencies -- what packages need us. |
| 525 | # |
| 526 | # We also provide some other information in the dependency graph: |
| 527 | # - action: What we're planning on doing with this package. Generally, |
| 528 | # "merge", "nomerge", or "uninstall" |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 529 | deps_map = {} |
| 530 | |
| 531 | def ReverseTree(packages): |
| 532 | """Convert tree to digraph. |
| 533 | |
| 534 | Take the tree of package -> requirements and reverse it to a digraph of |
| 535 | buildable packages -> packages they unblock. |
| 536 | Args: |
| 537 | packages: Tree(s) of dependencies. |
| 538 | Returns: |
| 539 | Unsanitized digraph. |
| 540 | """ |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 541 | binpkg_phases = set(["setup", "preinst", "postinst"]) |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 542 | needed_dep_types = set(["blocker", "buildtime", "runtime"]) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 543 | for pkg in packages: |
| 544 | |
| 545 | # Create an entry for the package |
| 546 | action = packages[pkg]["action"] |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 547 | default_pkg = {"needs": {}, "provides": set(), "action": action, |
| 548 | "nodeps": False, "binary": False} |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 549 | this_pkg = deps_map.setdefault(pkg, default_pkg) |
| 550 | |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 551 | if pkg in deps_info: |
| 552 | this_pkg["idx"] = deps_info[pkg]["idx"] |
| 553 | |
| 554 | # If a package doesn't have any defined phases that might use the |
| 555 | # dependent packages (i.e. pkg_setup, pkg_preinst, or pkg_postinst), |
| 556 | # we can install this package before its deps are ready. |
| 557 | emerge_pkg = self.package_db.get(pkg) |
| 558 | if emerge_pkg and emerge_pkg.type_name == "binary": |
| 559 | this_pkg["binary"] = True |
| 560 | defined_phases = emerge_pkg.metadata.defined_phases |
| 561 | defined_binpkg_phases = binpkg_phases.intersection(defined_phases) |
| 562 | if not defined_binpkg_phases: |
| 563 | this_pkg["nodeps"] = True |
| 564 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 565 | # Create entries for dependencies of this package first. |
| 566 | ReverseTree(packages[pkg]["deps"]) |
| 567 | |
| 568 | # Add dependencies to this package. |
| 569 | for dep, dep_item in packages[pkg]["deps"].iteritems(): |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 570 | # We only need to enforce strict ordering of dependencies if the |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 571 | # dependency is a blocker, or is a buildtime or runtime dependency. |
| 572 | # (I.e., ignored, optional, and runtime_post dependencies don't |
| 573 | # depend on ordering.) |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 574 | dep_types = dep_item["deptypes"] |
| 575 | if needed_dep_types.intersection(dep_types): |
| 576 | deps_map[dep]["provides"].add(pkg) |
| 577 | this_pkg["needs"][dep] = "/".join(dep_types) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 578 | |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 579 | # If there's a blocker, Portage may need to move files from one |
| 580 | # package to another, which requires editing the CONTENTS files of |
| 581 | # both packages. To avoid race conditions while editing this file, |
| 582 | # the two packages must not be installed in parallel, so we can't |
| 583 | # safely ignore dependencies. See http://crosbug.com/19328 |
| 584 | if "blocker" in dep_types: |
| 585 | this_pkg["nodeps"] = False |
| 586 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 587 | def FindCycles(): |
| 588 | """Find cycles in the dependency tree. |
| 589 | |
| 590 | Returns: |
| 591 | A dict mapping cyclic packages to a dict of the deps that cause |
| 592 | cycles. For each dep that causes cycles, it returns an example |
| 593 | traversal of the graph that shows the cycle. |
| 594 | """ |
| 595 | |
| 596 | def FindCyclesAtNode(pkg, cycles, unresolved, resolved): |
| 597 | """Find cycles in cyclic dependencies starting at specified package. |
| 598 | |
| 599 | Args: |
| 600 | pkg: Package identifier. |
| 601 | cycles: A dict mapping cyclic packages to a dict of the deps that |
| 602 | cause cycles. For each dep that causes cycles, it returns an |
| 603 | example traversal of the graph that shows the cycle. |
| 604 | unresolved: Nodes that have been visited but are not fully processed. |
| 605 | resolved: Nodes that have been visited and are fully processed. |
| 606 | """ |
| 607 | pkg_cycles = cycles.get(pkg) |
| 608 | if pkg in resolved and not pkg_cycles: |
| 609 | # If we already looked at this package, and found no cyclic |
| 610 | # dependencies, we can stop now. |
| 611 | return |
| 612 | unresolved.append(pkg) |
| 613 | for dep in deps_map[pkg]["needs"]: |
| 614 | if dep in unresolved: |
| 615 | idx = unresolved.index(dep) |
| 616 | mycycle = unresolved[idx:] + [dep] |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 617 | for i in xrange(len(mycycle) - 1): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 618 | pkg1, pkg2 = mycycle[i], mycycle[i+1] |
| 619 | cycles.setdefault(pkg1, {}).setdefault(pkg2, mycycle) |
| 620 | elif not pkg_cycles or dep not in pkg_cycles: |
| 621 | # Looks like we haven't seen this edge before. |
| 622 | FindCyclesAtNode(dep, cycles, unresolved, resolved) |
| 623 | unresolved.pop() |
| 624 | resolved.add(pkg) |
| 625 | |
| 626 | cycles, unresolved, resolved = {}, [], set() |
| 627 | for pkg in deps_map: |
| 628 | FindCyclesAtNode(pkg, cycles, unresolved, resolved) |
| 629 | return cycles |
| 630 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 631 | def RemoveUnusedPackages(): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 632 | """Remove installed packages, propagating dependencies.""" |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 633 | # Schedule packages that aren't on the install list for removal |
| 634 | rm_pkgs = set(deps_map.keys()) - set(deps_info.keys()) |
| 635 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 636 | # Remove the packages we don't want, simplifying the graph and making |
| 637 | # it easier for us to crack cycles. |
| 638 | for pkg in sorted(rm_pkgs): |
| 639 | this_pkg = deps_map[pkg] |
| 640 | needs = this_pkg["needs"] |
| 641 | provides = this_pkg["provides"] |
| 642 | for dep in needs: |
| 643 | dep_provides = deps_map[dep]["provides"] |
| 644 | dep_provides.update(provides) |
| 645 | dep_provides.discard(pkg) |
| 646 | dep_provides.discard(dep) |
| 647 | for target in provides: |
| 648 | target_needs = deps_map[target]["needs"] |
| 649 | target_needs.update(needs) |
| 650 | target_needs.pop(pkg, None) |
| 651 | target_needs.pop(target, None) |
| 652 | del deps_map[pkg] |
| 653 | |
| 654 | def PrintCycleBreak(basedep, dep, mycycle): |
| 655 | """Print details about a cycle that we are planning on breaking. |
| 656 | |
| 657 | We are breaking a cycle where dep needs basedep. mycycle is an |
| 658 | example cycle which contains dep -> basedep.""" |
| 659 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 660 | needs = deps_map[dep]["needs"] |
| 661 | depinfo = needs.get(basedep, "deleted") |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 662 | |
David James | 3f77880 | 2011-08-25 19:31:45 -0700 | [diff] [blame] | 663 | # It's OK to swap install order for blockers, as long as the two |
| 664 | # packages aren't installed in parallel. If there is a cycle, then |
| 665 | # we know the packages depend on each other already, so we can drop the |
| 666 | # blocker safely without printing a warning. |
| 667 | if depinfo == "blocker": |
| 668 | return |
| 669 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 670 | # Notify the user that we're breaking a cycle. |
| 671 | print "Breaking %s -> %s (%s)" % (dep, basedep, depinfo) |
| 672 | |
| 673 | # Show cycle. |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 674 | for i in xrange(len(mycycle) - 1): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 675 | pkg1, pkg2 = mycycle[i], mycycle[i+1] |
| 676 | needs = deps_map[pkg1]["needs"] |
| 677 | depinfo = needs.get(pkg2, "deleted") |
| 678 | if pkg1 == dep and pkg2 == basedep: |
| 679 | depinfo = depinfo + ", deleting" |
| 680 | print " %s -> %s (%s)" % (pkg1, pkg2, depinfo) |
| 681 | |
| 682 | def SanitizeTree(): |
| 683 | """Remove circular dependencies. |
| 684 | |
| 685 | We prune all dependencies involved in cycles that go against the emerge |
| 686 | ordering. This has a nice property: we're guaranteed to merge |
| 687 | dependencies in the same order that portage does. |
| 688 | |
| 689 | Because we don't treat any dependencies as "soft" unless they're killed |
| 690 | by a cycle, we pay attention to a larger number of dependencies when |
| 691 | merging. This hurts performance a bit, but helps reliability. |
| 692 | """ |
| 693 | start = time.time() |
| 694 | cycles = FindCycles() |
| 695 | while cycles: |
| 696 | for dep, mycycles in cycles.iteritems(): |
| 697 | for basedep, mycycle in mycycles.iteritems(): |
| 698 | if deps_info[basedep]["idx"] >= deps_info[dep]["idx"]: |
Matt Tennant | 0879730 | 2011-10-17 16:18:45 -0700 | [diff] [blame] | 699 | if "--quiet" not in emerge.opts: |
| 700 | PrintCycleBreak(basedep, dep, mycycle) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 701 | del deps_map[dep]["needs"][basedep] |
| 702 | deps_map[basedep]["provides"].remove(dep) |
| 703 | cycles = FindCycles() |
| 704 | seconds = time.time() - start |
| 705 | if "--quiet" not in emerge.opts and seconds >= 0.1: |
| 706 | print "Tree sanitized in %dm%.1fs" % (seconds / 60, seconds % 60) |
| 707 | |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 708 | def FindRecursiveProvides(pkg, seen): |
| 709 | """Find all nodes that require a particular package. |
| 710 | |
| 711 | Assumes that graph is acyclic. |
| 712 | |
| 713 | Args: |
| 714 | pkg: Package identifier. |
| 715 | seen: Nodes that have been visited so far. |
| 716 | """ |
| 717 | if pkg in seen: |
| 718 | return |
| 719 | seen.add(pkg) |
| 720 | info = deps_map[pkg] |
| 721 | info["tprovides"] = info["provides"].copy() |
| 722 | for dep in info["provides"]: |
| 723 | FindRecursiveProvides(dep, seen) |
| 724 | info["tprovides"].update(deps_map[dep]["tprovides"]) |
| 725 | |
David James | a22906f | 2011-05-04 19:53:26 -0700 | [diff] [blame] | 726 | ReverseTree(deps_tree) |
David James | a22906f | 2011-05-04 19:53:26 -0700 | [diff] [blame] | 727 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 728 | # We need to remove unused packages so that we can use the dependency |
| 729 | # ordering of the install process to show us what cycles to crack. |
| 730 | RemoveUnusedPackages() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 731 | SanitizeTree() |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 732 | seen = set() |
| 733 | for pkg in deps_map: |
| 734 | FindRecursiveProvides(pkg, seen) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 735 | return deps_map |
| 736 | |
| 737 | def PrintInstallPlan(self, deps_map): |
| 738 | """Print an emerge-style install plan. |
| 739 | |
| 740 | The install plan lists what packages we're installing, in order. |
| 741 | It's useful for understanding what parallel_emerge is doing. |
| 742 | |
| 743 | Args: |
| 744 | deps_map: The dependency graph. |
| 745 | """ |
| 746 | |
| 747 | def InstallPlanAtNode(target, deps_map): |
| 748 | nodes = [] |
| 749 | nodes.append(target) |
| 750 | for dep in deps_map[target]["provides"]: |
| 751 | del deps_map[dep]["needs"][target] |
| 752 | if not deps_map[dep]["needs"]: |
| 753 | nodes.extend(InstallPlanAtNode(dep, deps_map)) |
| 754 | return nodes |
| 755 | |
| 756 | deps_map = copy.deepcopy(deps_map) |
| 757 | install_plan = [] |
| 758 | plan = set() |
| 759 | for target, info in deps_map.iteritems(): |
| 760 | if not info["needs"] and target not in plan: |
| 761 | for item in InstallPlanAtNode(target, deps_map): |
| 762 | plan.add(item) |
| 763 | install_plan.append(self.package_db[item]) |
| 764 | |
| 765 | for pkg in plan: |
| 766 | del deps_map[pkg] |
| 767 | |
| 768 | if deps_map: |
| 769 | print "Cyclic dependencies:", " ".join(deps_map) |
| 770 | PrintDepsMap(deps_map) |
| 771 | sys.exit(1) |
| 772 | |
| 773 | self.emerge.depgraph.display(install_plan) |
| 774 | |
| 775 | |
| 776 | def PrintDepsMap(deps_map): |
| 777 | """Print dependency graph, for each package list it's prerequisites.""" |
| 778 | for i in sorted(deps_map): |
| 779 | print "%s: (%s) needs" % (i, deps_map[i]["action"]) |
| 780 | needs = deps_map[i]["needs"] |
| 781 | for j in sorted(needs): |
| 782 | print " %s" % (j) |
| 783 | if not needs: |
| 784 | print " no dependencies" |
| 785 | |
| 786 | |
| 787 | class EmergeJobState(object): |
| 788 | __slots__ = ["done", "filename", "last_notify_timestamp", "last_output_seek", |
| 789 | "last_output_timestamp", "pkgname", "retcode", "start_timestamp", |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 790 | "target", "fetch_only"] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 791 | |
| 792 | def __init__(self, target, pkgname, done, filename, start_timestamp, |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 793 | retcode=None, fetch_only=False): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 794 | |
| 795 | # The full name of the target we're building (e.g. |
| 796 | # chromeos-base/chromeos-0.0.1-r60) |
| 797 | self.target = target |
| 798 | |
| 799 | # The short name of the target we're building (e.g. chromeos-0.0.1-r60) |
| 800 | self.pkgname = pkgname |
| 801 | |
| 802 | # Whether the job is done. (True if the job is done; false otherwise.) |
| 803 | self.done = done |
| 804 | |
| 805 | # The filename where output is currently stored. |
| 806 | self.filename = filename |
| 807 | |
| 808 | # The timestamp of the last time we printed the name of the log file. We |
| 809 | # print this at the beginning of the job, so this starts at |
| 810 | # start_timestamp. |
| 811 | self.last_notify_timestamp = start_timestamp |
| 812 | |
| 813 | # The location (in bytes) of the end of the last complete line we printed. |
| 814 | # This starts off at zero. We use this to jump to the right place when we |
| 815 | # print output from the same ebuild multiple times. |
| 816 | self.last_output_seek = 0 |
| 817 | |
| 818 | # The timestamp of the last time we printed output. Since we haven't |
| 819 | # printed output yet, this starts at zero. |
| 820 | self.last_output_timestamp = 0 |
| 821 | |
| 822 | # The return code of our job, if the job is actually finished. |
| 823 | self.retcode = retcode |
| 824 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 825 | # Was this just a fetch job? |
| 826 | self.fetch_only = fetch_only |
| 827 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 828 | # The timestamp when our job started. |
| 829 | self.start_timestamp = start_timestamp |
| 830 | |
| 831 | |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 832 | def KillHandler(_signum, _frame): |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 833 | # Kill self and all subprocesses. |
| 834 | os.killpg(0, signal.SIGKILL) |
| 835 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 836 | def SetupWorkerSignals(): |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 837 | def ExitHandler(_signum, _frame): |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 838 | # Set KILLED flag. |
| 839 | KILLED.set() |
David James | 13cead4 | 2011-05-18 16:22:01 -0700 | [diff] [blame] | 840 | |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 841 | # Remove our signal handlers so we don't get called recursively. |
| 842 | signal.signal(signal.SIGINT, KillHandler) |
| 843 | signal.signal(signal.SIGTERM, KillHandler) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 844 | |
| 845 | # Ensure that we exit quietly and cleanly, if possible, when we receive |
| 846 | # SIGTERM or SIGINT signals. By default, when the user hits CTRL-C, all |
| 847 | # of the child processes will print details about KeyboardInterrupt |
| 848 | # exceptions, which isn't very helpful. |
| 849 | signal.signal(signal.SIGINT, ExitHandler) |
| 850 | signal.signal(signal.SIGTERM, ExitHandler) |
| 851 | |
David James | 6b29d05 | 2012-11-02 10:27:27 -0700 | [diff] [blame] | 852 | def EmergeProcess(output, *args, **kwargs): |
David James | 1ed3e25 | 2011-10-05 20:26:15 -0700 | [diff] [blame] | 853 | """Merge a package in a subprocess. |
| 854 | |
| 855 | Args: |
David James | 1ed3e25 | 2011-10-05 20:26:15 -0700 | [diff] [blame] | 856 | output: Temporary file to write output. |
David James | 6b29d05 | 2012-11-02 10:27:27 -0700 | [diff] [blame] | 857 | *args: Arguments to pass to Scheduler constructor. |
| 858 | **kwargs: Keyword arguments to pass to Scheduler constructor. |
David James | 1ed3e25 | 2011-10-05 20:26:15 -0700 | [diff] [blame] | 859 | |
| 860 | Returns: |
| 861 | The exit code returned by the subprocess. |
| 862 | """ |
| 863 | pid = os.fork() |
| 864 | if pid == 0: |
| 865 | try: |
| 866 | # Sanity checks. |
| 867 | if sys.stdout.fileno() != 1: raise Exception("sys.stdout.fileno() != 1") |
| 868 | if sys.stderr.fileno() != 2: raise Exception("sys.stderr.fileno() != 2") |
| 869 | |
| 870 | # - Redirect 1 (stdout) and 2 (stderr) at our temporary file. |
| 871 | # - Redirect 0 to point at sys.stdin. In this case, sys.stdin |
| 872 | # points at a file reading os.devnull, because multiprocessing mucks |
| 873 | # with sys.stdin. |
| 874 | # - Leave the sys.stdin and output filehandles alone. |
| 875 | fd_pipes = {0: sys.stdin.fileno(), |
| 876 | 1: output.fileno(), |
| 877 | 2: output.fileno(), |
| 878 | sys.stdin.fileno(): sys.stdin.fileno(), |
| 879 | output.fileno(): output.fileno()} |
| 880 | portage.process._setup_pipes(fd_pipes) |
| 881 | |
| 882 | # Portage doesn't like when sys.stdin.fileno() != 0, so point sys.stdin |
| 883 | # at the filehandle we just created in _setup_pipes. |
| 884 | if sys.stdin.fileno() != 0: |
David James | 6b29d05 | 2012-11-02 10:27:27 -0700 | [diff] [blame] | 885 | sys.__stdin__ = sys.stdin = os.fdopen(0, "r") |
| 886 | |
| 887 | scheduler = Scheduler(*args, **kwargs) |
| 888 | |
| 889 | # Enable blocker handling even though we're in --nodeps mode. This |
| 890 | # allows us to unmerge the blocker after we've merged the replacement. |
| 891 | scheduler._opts_ignore_blockers = frozenset() |
David James | 1ed3e25 | 2011-10-05 20:26:15 -0700 | [diff] [blame] | 892 | |
| 893 | # Actually do the merge. |
| 894 | retval = scheduler.merge() |
| 895 | |
| 896 | # We catch all exceptions here (including SystemExit, KeyboardInterrupt, |
| 897 | # etc) so as to ensure that we don't confuse the multiprocessing module, |
| 898 | # which expects that all forked children exit with os._exit(). |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 899 | # pylint: disable=W0702 |
David James | 1ed3e25 | 2011-10-05 20:26:15 -0700 | [diff] [blame] | 900 | except: |
| 901 | traceback.print_exc(file=output) |
| 902 | retval = 1 |
| 903 | sys.stdout.flush() |
| 904 | sys.stderr.flush() |
| 905 | output.flush() |
| 906 | os._exit(retval) |
| 907 | else: |
| 908 | # Return the exit code of the subprocess. |
| 909 | return os.waitpid(pid, 0)[1] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 910 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 911 | def EmergeWorker(task_queue, job_queue, emerge, package_db, fetch_only=False): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 912 | """This worker emerges any packages given to it on the task_queue. |
| 913 | |
| 914 | Args: |
| 915 | task_queue: The queue of tasks for this worker to do. |
| 916 | job_queue: The queue of results from the worker. |
| 917 | emerge: An EmergeData() object. |
| 918 | package_db: A dict, mapping package ids to portage Package objects. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 919 | fetch_only: A bool, indicating if we should just fetch the target. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 920 | |
| 921 | It expects package identifiers to be passed to it via task_queue. When |
| 922 | a task is started, it pushes the (target, filename) to the started_queue. |
| 923 | The output is stored in filename. When a merge starts or finishes, we push |
| 924 | EmergeJobState objects to the job_queue. |
| 925 | """ |
| 926 | |
| 927 | SetupWorkerSignals() |
| 928 | settings, trees, mtimedb = emerge.settings, emerge.trees, emerge.mtimedb |
David James | deebd69 | 2011-05-09 17:02:52 -0700 | [diff] [blame] | 929 | |
| 930 | # Disable flushing of caches to save on I/O. |
David James | 7a1ea4b | 2011-10-13 15:06:41 -0700 | [diff] [blame] | 931 | root = emerge.settings["ROOT"] |
| 932 | vardb = emerge.trees[root]["vartree"].dbapi |
| 933 | vardb._flush_cache_enabled = False |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 934 | bindb = emerge.trees[root]["bintree"].dbapi |
| 935 | # Might be a set, might be a list, might be None; no clue, just use shallow |
| 936 | # copy to ensure we can roll it back. |
| 937 | original_remotepkgs = copy.copy(bindb.bintree._remotepkgs) |
David James | deebd69 | 2011-05-09 17:02:52 -0700 | [diff] [blame] | 938 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 939 | opts, spinner = emerge.opts, emerge.spinner |
| 940 | opts["--nodeps"] = True |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 941 | if fetch_only: |
| 942 | opts["--fetchonly"] = True |
| 943 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 944 | while True: |
| 945 | # Wait for a new item to show up on the queue. This is a blocking wait, |
| 946 | # so if there's nothing to do, we just sit here. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 947 | pkg_state = task_queue.get() |
| 948 | if pkg_state is None: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 949 | # If target is None, this means that the main thread wants us to quit. |
| 950 | # The other workers need to exit too, so we'll push the message back on |
| 951 | # to the queue so they'll get it too. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 952 | task_queue.put(None) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 953 | return |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 954 | if KILLED.is_set(): |
| 955 | return |
| 956 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 957 | target = pkg_state.target |
| 958 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 959 | db_pkg = package_db[target] |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 960 | |
| 961 | if db_pkg.type_name == "binary": |
| 962 | if not fetch_only and pkg_state.fetched_successfully: |
| 963 | # Ensure portage doesn't think our pkg is remote- else it'll force |
| 964 | # a redownload of it (even if the on-disk file is fine). In-memory |
| 965 | # caching basically, implemented dumbly. |
| 966 | bindb.bintree._remotepkgs = None |
| 967 | else: |
| 968 | bindb.bintree_remotepkgs = original_remotepkgs |
| 969 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 970 | db_pkg.root_config = emerge.root_config |
| 971 | install_list = [db_pkg] |
| 972 | pkgname = db_pkg.pf |
| 973 | output = tempfile.NamedTemporaryFile(prefix=pkgname + "-", delete=False) |
David James | 01b1e0f | 2012-06-07 17:18:05 -0700 | [diff] [blame] | 974 | os.chmod(output.name, 644) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 975 | start_timestamp = time.time() |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 976 | job = EmergeJobState(target, pkgname, False, output.name, start_timestamp, |
| 977 | fetch_only=fetch_only) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 978 | job_queue.put(job) |
| 979 | if "--pretend" in opts: |
| 980 | retcode = 0 |
| 981 | else: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 982 | try: |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 983 | emerge.scheduler_graph.mergelist = install_list |
David James | 6b29d05 | 2012-11-02 10:27:27 -0700 | [diff] [blame] | 984 | retcode = EmergeProcess(output, settings, trees, mtimedb, opts, |
| 985 | spinner, favorites=emerge.favorites, |
| 986 | graph_config=emerge.scheduler_graph) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 987 | except Exception: |
| 988 | traceback.print_exc(file=output) |
| 989 | retcode = 1 |
David James | 1ed3e25 | 2011-10-05 20:26:15 -0700 | [diff] [blame] | 990 | output.close() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 991 | |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 992 | if KILLED.is_set(): |
| 993 | return |
| 994 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 995 | job = EmergeJobState(target, pkgname, True, output.name, start_timestamp, |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 996 | retcode, fetch_only=fetch_only) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 997 | job_queue.put(job) |
| 998 | |
| 999 | |
| 1000 | class LinePrinter(object): |
| 1001 | """Helper object to print a single line.""" |
| 1002 | |
| 1003 | def __init__(self, line): |
| 1004 | self.line = line |
| 1005 | |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1006 | def Print(self, _seek_locations): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1007 | print self.line |
| 1008 | |
| 1009 | |
| 1010 | class JobPrinter(object): |
| 1011 | """Helper object to print output of a job.""" |
| 1012 | |
| 1013 | def __init__(self, job, unlink=False): |
| 1014 | """Print output of job. |
| 1015 | |
| 1016 | If unlink is True, unlink the job output file when done.""" |
| 1017 | self.current_time = time.time() |
| 1018 | self.job = job |
| 1019 | self.unlink = unlink |
| 1020 | |
| 1021 | def Print(self, seek_locations): |
| 1022 | |
| 1023 | job = self.job |
| 1024 | |
| 1025 | # Calculate how long the job has been running. |
| 1026 | seconds = self.current_time - job.start_timestamp |
| 1027 | |
| 1028 | # Note that we've printed out the job so far. |
| 1029 | job.last_output_timestamp = self.current_time |
| 1030 | |
| 1031 | # Note that we're starting the job |
| 1032 | info = "job %s (%dm%.1fs)" % (job.pkgname, seconds / 60, seconds % 60) |
| 1033 | last_output_seek = seek_locations.get(job.filename, 0) |
| 1034 | if last_output_seek: |
| 1035 | print "=== Continue output for %s ===" % info |
| 1036 | else: |
| 1037 | print "=== Start output for %s ===" % info |
| 1038 | |
| 1039 | # Print actual output from job |
| 1040 | f = codecs.open(job.filename, encoding='utf-8', errors='replace') |
| 1041 | f.seek(last_output_seek) |
| 1042 | prefix = job.pkgname + ":" |
| 1043 | for line in f: |
| 1044 | |
| 1045 | # Save off our position in the file |
| 1046 | if line and line[-1] == "\n": |
| 1047 | last_output_seek = f.tell() |
| 1048 | line = line[:-1] |
| 1049 | |
| 1050 | # Print our line |
| 1051 | print prefix, line.encode('utf-8', 'replace') |
| 1052 | f.close() |
| 1053 | |
| 1054 | # Save our last spot in the file so that we don't print out the same |
| 1055 | # location twice. |
| 1056 | seek_locations[job.filename] = last_output_seek |
| 1057 | |
| 1058 | # Note end of output section |
| 1059 | if job.done: |
| 1060 | print "=== Complete: %s ===" % info |
| 1061 | else: |
| 1062 | print "=== Still running: %s ===" % info |
| 1063 | |
| 1064 | if self.unlink: |
| 1065 | os.unlink(job.filename) |
| 1066 | |
| 1067 | |
| 1068 | def PrintWorker(queue): |
| 1069 | """A worker that prints stuff to the screen as requested.""" |
| 1070 | |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1071 | def ExitHandler(_signum, _frame): |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1072 | # Set KILLED flag. |
| 1073 | KILLED.set() |
| 1074 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1075 | # Switch to default signal handlers so that we'll die after two signals. |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1076 | signal.signal(signal.SIGINT, KillHandler) |
| 1077 | signal.signal(signal.SIGTERM, KillHandler) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1078 | |
| 1079 | # Don't exit on the first SIGINT / SIGTERM, because the parent worker will |
| 1080 | # handle it and tell us when we need to exit. |
| 1081 | signal.signal(signal.SIGINT, ExitHandler) |
| 1082 | signal.signal(signal.SIGTERM, ExitHandler) |
| 1083 | |
| 1084 | # seek_locations is a map indicating the position we are at in each file. |
| 1085 | # It starts off empty, but is set by the various Print jobs as we go along |
| 1086 | # to indicate where we left off in each file. |
| 1087 | seek_locations = {} |
| 1088 | while True: |
| 1089 | try: |
| 1090 | job = queue.get() |
| 1091 | if job: |
| 1092 | job.Print(seek_locations) |
David James | bccf8eb | 2011-07-27 14:06:06 -0700 | [diff] [blame] | 1093 | sys.stdout.flush() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1094 | else: |
| 1095 | break |
| 1096 | except IOError as ex: |
| 1097 | if ex.errno == errno.EINTR: |
| 1098 | # Looks like we received a signal. Keep printing. |
| 1099 | continue |
| 1100 | raise |
| 1101 | |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1102 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1103 | class TargetState(object): |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1104 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1105 | __slots__ = ("target", "info", "score", "prefetched", "fetched_successfully") |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1106 | |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1107 | def __init__(self, target, info): |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1108 | self.target, self.info = target, info |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1109 | self.fetched_successfully = False |
| 1110 | self.prefetched = False |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1111 | self.score = None |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1112 | self.update_score() |
| 1113 | |
| 1114 | def __cmp__(self, other): |
| 1115 | return cmp(self.score, other.score) |
| 1116 | |
| 1117 | def update_score(self): |
| 1118 | self.score = ( |
| 1119 | -len(self.info["tprovides"]), |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1120 | len(self.info["needs"]), |
Brian Harring | 11c5eeb | 2012-03-18 11:02:39 -0700 | [diff] [blame] | 1121 | not self.info["binary"], |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1122 | -len(self.info["provides"]), |
| 1123 | self.info["idx"], |
| 1124 | self.target, |
| 1125 | ) |
| 1126 | |
| 1127 | |
| 1128 | class ScoredHeap(object): |
| 1129 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1130 | __slots__ = ("heap", "_heap_set") |
| 1131 | |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1132 | def __init__(self, initial=()): |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1133 | self.heap = list() |
| 1134 | self._heap_set = set() |
| 1135 | if initial: |
| 1136 | self.multi_put(initial) |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1137 | |
| 1138 | def get(self): |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1139 | item = heapq.heappop(self.heap) |
| 1140 | self._heap_set.remove(item.target) |
| 1141 | return item |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1142 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1143 | def put(self, item): |
| 1144 | if not isinstance(item, TargetState): |
| 1145 | raise ValueError("Item %r isn't a TargetState" % (item,)) |
| 1146 | heapq.heappush(self.heap, item) |
| 1147 | self._heap_set.add(item.target) |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1148 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1149 | def multi_put(self, sequence): |
| 1150 | sequence = list(sequence) |
| 1151 | self.heap.extend(sequence) |
| 1152 | self._heap_set.update(x.target for x in sequence) |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1153 | self.sort() |
| 1154 | |
David James | 5c9996d | 2012-03-24 10:50:46 -0700 | [diff] [blame] | 1155 | def sort(self): |
| 1156 | heapq.heapify(self.heap) |
| 1157 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1158 | def __contains__(self, target): |
| 1159 | return target in self._heap_set |
| 1160 | |
| 1161 | def __nonzero__(self): |
| 1162 | return bool(self.heap) |
| 1163 | |
Brian Harring | 867e236 | 2012-03-17 04:05:17 -0700 | [diff] [blame] | 1164 | def __len__(self): |
| 1165 | return len(self.heap) |
| 1166 | |
| 1167 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1168 | class EmergeQueue(object): |
| 1169 | """Class to schedule emerge jobs according to a dependency graph.""" |
| 1170 | |
| 1171 | def __init__(self, deps_map, emerge, package_db, show_output): |
| 1172 | # Store the dependency graph. |
| 1173 | self._deps_map = deps_map |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1174 | self._state_map = {} |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1175 | # Initialize the running queue to empty |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1176 | self._build_jobs = {} |
| 1177 | self._build_ready = ScoredHeap() |
| 1178 | self._fetch_jobs = {} |
| 1179 | self._fetch_ready = ScoredHeap() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1180 | # List of total package installs represented in deps_map. |
| 1181 | install_jobs = [x for x in deps_map if deps_map[x]["action"] == "merge"] |
| 1182 | self._total_jobs = len(install_jobs) |
| 1183 | self._show_output = show_output |
| 1184 | |
| 1185 | if "--pretend" in emerge.opts: |
| 1186 | print "Skipping merge because of --pretend mode." |
| 1187 | sys.exit(0) |
| 1188 | |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1189 | # Set a process group so we can easily terminate all children. |
| 1190 | os.setsid() |
| 1191 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1192 | # Setup scheduler graph object. This is used by the child processes |
| 1193 | # to help schedule jobs. |
| 1194 | emerge.scheduler_graph = emerge.depgraph.schedulerGraph() |
| 1195 | |
| 1196 | # Calculate how many jobs we can run in parallel. We don't want to pass |
| 1197 | # the --jobs flag over to emerge itself, because that'll tell emerge to |
| 1198 | # hide its output, and said output is quite useful for debugging hung |
| 1199 | # jobs. |
| 1200 | procs = min(self._total_jobs, |
| 1201 | emerge.opts.pop("--jobs", multiprocessing.cpu_count())) |
David James | 7746e11 | 2013-02-24 19:32:50 -0800 | [diff] [blame] | 1202 | self._build_procs = self._fetch_procs = max(1, procs) |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1203 | self._load_avg = emerge.opts.pop("--load-average", None) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1204 | self._job_queue = multiprocessing.Queue() |
| 1205 | self._print_queue = multiprocessing.Queue() |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1206 | |
| 1207 | self._fetch_queue = multiprocessing.Queue() |
| 1208 | args = (self._fetch_queue, self._job_queue, emerge, package_db, True) |
| 1209 | self._fetch_pool = multiprocessing.Pool(self._fetch_procs, EmergeWorker, |
| 1210 | args) |
| 1211 | |
| 1212 | self._build_queue = multiprocessing.Queue() |
| 1213 | args = (self._build_queue, self._job_queue, emerge, package_db) |
| 1214 | self._build_pool = multiprocessing.Pool(self._build_procs, EmergeWorker, |
| 1215 | args) |
| 1216 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1217 | self._print_worker = multiprocessing.Process(target=PrintWorker, |
| 1218 | args=[self._print_queue]) |
| 1219 | self._print_worker.start() |
| 1220 | |
| 1221 | # Initialize the failed queue to empty. |
| 1222 | self._retry_queue = [] |
| 1223 | self._failed = set() |
| 1224 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1225 | # Setup an exit handler so that we print nice messages if we are |
| 1226 | # terminated. |
| 1227 | self._SetupExitHandler() |
| 1228 | |
| 1229 | # Schedule our jobs. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1230 | self._state_map.update( |
| 1231 | (pkg, TargetState(pkg, data)) for pkg, data in deps_map.iteritems()) |
| 1232 | self._fetch_ready.multi_put(self._state_map.itervalues()) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1233 | |
| 1234 | def _SetupExitHandler(self): |
| 1235 | |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1236 | def ExitHandler(signum, _frame): |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1237 | # Set KILLED flag. |
| 1238 | KILLED.set() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1239 | |
| 1240 | # Kill our signal handlers so we don't get called recursively |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1241 | signal.signal(signal.SIGINT, KillHandler) |
| 1242 | signal.signal(signal.SIGTERM, KillHandler) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1243 | |
| 1244 | # Print our current job status |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1245 | for job in self._build_jobs.itervalues(): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1246 | if job: |
| 1247 | self._print_queue.put(JobPrinter(job, unlink=True)) |
| 1248 | |
| 1249 | # Notify the user that we are exiting |
| 1250 | self._Print("Exiting on signal %s" % signum) |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1251 | self._print_queue.put(None) |
| 1252 | self._print_worker.join() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1253 | |
| 1254 | # Kill child threads, then exit. |
David James | 7358d03 | 2011-05-19 10:40:03 -0700 | [diff] [blame] | 1255 | os.killpg(0, signal.SIGKILL) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1256 | sys.exit(1) |
| 1257 | |
| 1258 | # Print out job status when we are killed |
| 1259 | signal.signal(signal.SIGINT, ExitHandler) |
| 1260 | signal.signal(signal.SIGTERM, ExitHandler) |
| 1261 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1262 | def _Schedule(self, pkg_state): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1263 | # We maintain a tree of all deps, if this doesn't need |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1264 | # to be installed just free up its children and continue. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1265 | # It is possible to reinstall deps of deps, without reinstalling |
| 1266 | # first level deps, like so: |
| 1267 | # chromeos (merge) -> eselect (nomerge) -> python (merge) |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1268 | this_pkg = pkg_state.info |
| 1269 | target = pkg_state.target |
| 1270 | if pkg_state.info is not None: |
| 1271 | if this_pkg["action"] == "nomerge": |
| 1272 | self._Finish(target) |
| 1273 | elif target not in self._build_jobs: |
| 1274 | # Kick off the build if it's marked to be built. |
| 1275 | self._build_jobs[target] = None |
| 1276 | self._build_queue.put(pkg_state) |
| 1277 | return True |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1278 | |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1279 | def _ScheduleLoop(self): |
| 1280 | # If the current load exceeds our desired load average, don't schedule |
| 1281 | # more than one job. |
| 1282 | if self._load_avg and os.getloadavg()[0] > self._load_avg: |
| 1283 | needed_jobs = 1 |
| 1284 | else: |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1285 | needed_jobs = self._build_procs |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1286 | |
| 1287 | # Schedule more jobs. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1288 | while self._build_ready and len(self._build_jobs) < needed_jobs: |
| 1289 | state = self._build_ready.get() |
| 1290 | if state.target not in self._failed: |
| 1291 | self._Schedule(state) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1292 | |
| 1293 | def _Print(self, line): |
| 1294 | """Print a single line.""" |
| 1295 | self._print_queue.put(LinePrinter(line)) |
| 1296 | |
| 1297 | def _Status(self): |
| 1298 | """Print status.""" |
| 1299 | current_time = time.time() |
| 1300 | no_output = True |
| 1301 | |
| 1302 | # Print interim output every minute if --show-output is used. Otherwise, |
| 1303 | # print notifications about running packages every 2 minutes, and print |
| 1304 | # full output for jobs that have been running for 60 minutes or more. |
| 1305 | if self._show_output: |
| 1306 | interval = 60 |
| 1307 | notify_interval = 0 |
| 1308 | else: |
| 1309 | interval = 60 * 60 |
| 1310 | notify_interval = 60 * 2 |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1311 | for job in self._build_jobs.itervalues(): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1312 | if job: |
| 1313 | last_timestamp = max(job.start_timestamp, job.last_output_timestamp) |
| 1314 | if last_timestamp + interval < current_time: |
| 1315 | self._print_queue.put(JobPrinter(job)) |
| 1316 | job.last_output_timestamp = current_time |
| 1317 | no_output = False |
| 1318 | elif (notify_interval and |
| 1319 | job.last_notify_timestamp + notify_interval < current_time): |
| 1320 | job_seconds = current_time - job.start_timestamp |
| 1321 | args = (job.pkgname, job_seconds / 60, job_seconds % 60, job.filename) |
| 1322 | info = "Still building %s (%dm%.1fs). Logs in %s" % args |
| 1323 | job.last_notify_timestamp = current_time |
| 1324 | self._Print(info) |
| 1325 | no_output = False |
| 1326 | |
| 1327 | # If we haven't printed any messages yet, print a general status message |
| 1328 | # here. |
| 1329 | if no_output: |
| 1330 | seconds = current_time - GLOBAL_START |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1331 | fjobs, fready = len(self._fetch_jobs), len(self._fetch_ready) |
| 1332 | bjobs, bready = len(self._build_jobs), len(self._build_ready) |
| 1333 | retries = len(self._retry_queue) |
| 1334 | pending = max(0, len(self._deps_map) - fjobs - bjobs) |
| 1335 | line = "Pending %s/%s, " % (pending, self._total_jobs) |
| 1336 | if fjobs or fready: |
| 1337 | line += "Fetching %s/%s, " % (fjobs, fready + fjobs) |
| 1338 | if bjobs or bready or retries: |
| 1339 | line += "Building %s/%s, " % (bjobs, bready + bjobs) |
| 1340 | if retries: |
| 1341 | line += "Retrying %s, " % (retries,) |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1342 | load = " ".join(str(x) for x in os.getloadavg()) |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1343 | line += ("[Time %dm%.1fs Load %s]" % (seconds/60, seconds %60, load)) |
| 1344 | self._Print(line) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1345 | |
| 1346 | def _Finish(self, target): |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1347 | """Mark a target as completed and unblock dependencies.""" |
| 1348 | this_pkg = self._deps_map[target] |
| 1349 | if this_pkg["needs"] and this_pkg["nodeps"]: |
| 1350 | # We got installed, but our deps have not been installed yet. Dependent |
| 1351 | # packages should only be installed when our needs have been fully met. |
| 1352 | this_pkg["action"] = "nomerge" |
| 1353 | else: |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1354 | for dep in this_pkg["provides"]: |
| 1355 | dep_pkg = self._deps_map[dep] |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1356 | state = self._state_map[dep] |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1357 | del dep_pkg["needs"][target] |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1358 | state.update_score() |
| 1359 | if not state.prefetched: |
| 1360 | if dep in self._fetch_ready: |
| 1361 | # If it's not currently being fetched, update the prioritization |
| 1362 | self._fetch_ready.sort() |
| 1363 | elif not dep_pkg["needs"]: |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1364 | if dep_pkg["nodeps"] and dep_pkg["action"] == "nomerge": |
| 1365 | self._Finish(dep) |
| 1366 | else: |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1367 | self._build_ready.put(self._state_map[dep]) |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1368 | self._deps_map.pop(target) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1369 | |
| 1370 | def _Retry(self): |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1371 | while self._retry_queue: |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1372 | state = self._retry_queue.pop(0) |
| 1373 | if self._Schedule(state): |
| 1374 | self._Print("Retrying emerge of %s." % state.target) |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1375 | break |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1376 | |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1377 | def _Shutdown(self): |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1378 | # Tell emerge workers to exit. They all exit when 'None' is pushed |
| 1379 | # to the queue. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1380 | |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1381 | # Shutdown the workers first; then jobs (which is how they feed things back) |
| 1382 | # then finally the print queue. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1383 | |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1384 | def _stop(queue, pool): |
| 1385 | if pool is None: |
| 1386 | return |
| 1387 | try: |
| 1388 | queue.put(None) |
| 1389 | pool.close() |
| 1390 | pool.join() |
| 1391 | finally: |
| 1392 | pool.terminate() |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1393 | |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1394 | _stop(self._fetch_queue, self._fetch_pool) |
| 1395 | self._fetch_queue = self._fetch_pool = None |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1396 | |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1397 | _stop(self._build_queue, self._build_pool) |
| 1398 | self._build_queue = self._build_pool = None |
| 1399 | |
| 1400 | if self._job_queue is not None: |
| 1401 | self._job_queue.close() |
| 1402 | self._job_queue = None |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1403 | |
| 1404 | # Now that our workers are finished, we can kill the print queue. |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1405 | if self._print_worker is not None: |
| 1406 | try: |
| 1407 | self._print_queue.put(None) |
| 1408 | self._print_queue.close() |
| 1409 | self._print_worker.join() |
| 1410 | finally: |
| 1411 | self._print_worker.terminate() |
| 1412 | self._print_queue = self._print_worker = None |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1413 | |
| 1414 | def Run(self): |
| 1415 | """Run through the scheduled ebuilds. |
| 1416 | |
| 1417 | Keep running so long as we have uninstalled packages in the |
| 1418 | dependency graph to merge. |
| 1419 | """ |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1420 | if not self._deps_map: |
| 1421 | return |
| 1422 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1423 | # Start the fetchers. |
| 1424 | for _ in xrange(min(self._fetch_procs, len(self._fetch_ready))): |
| 1425 | state = self._fetch_ready.get() |
| 1426 | self._fetch_jobs[state.target] = None |
| 1427 | self._fetch_queue.put(state) |
| 1428 | |
| 1429 | # Print an update, then get going. |
| 1430 | self._Status() |
| 1431 | |
David James | e703d0f | 2012-01-12 16:27:45 -0800 | [diff] [blame] | 1432 | retried = set() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1433 | while self._deps_map: |
| 1434 | # Check here that we are actually waiting for something. |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1435 | if (self._build_queue.empty() and |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1436 | self._job_queue.empty() and |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1437 | not self._fetch_jobs and |
| 1438 | not self._fetch_ready and |
| 1439 | not self._build_jobs and |
| 1440 | not self._build_ready and |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1441 | self._deps_map): |
| 1442 | # If we have failed on a package, retry it now. |
| 1443 | if self._retry_queue: |
| 1444 | self._Retry() |
| 1445 | else: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1446 | # Tell the user why we're exiting. |
| 1447 | if self._failed: |
Mike Frysinger | f2ff917 | 2012-11-01 18:47:41 -0400 | [diff] [blame] | 1448 | print 'Packages failed:\n\t%s' % '\n\t'.join(self._failed) |
David James | 0eae23e | 2012-07-03 15:04:25 -0700 | [diff] [blame] | 1449 | status_file = os.environ.get("PARALLEL_EMERGE_STATUS_FILE") |
| 1450 | if status_file: |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1451 | failed_pkgs = set(portage.versions.cpv_getkey(x) |
| 1452 | for x in self._failed) |
David James | 0eae23e | 2012-07-03 15:04:25 -0700 | [diff] [blame] | 1453 | with open(status_file, "a") as f: |
| 1454 | f.write("%s\n" % " ".join(failed_pkgs)) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1455 | else: |
| 1456 | print "Deadlock! Circular dependencies!" |
| 1457 | sys.exit(1) |
| 1458 | |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1459 | for _ in xrange(12): |
David James | a74289a | 2011-08-12 10:41:24 -0700 | [diff] [blame] | 1460 | try: |
| 1461 | job = self._job_queue.get(timeout=5) |
| 1462 | break |
| 1463 | except Queue.Empty: |
| 1464 | # Check if any more jobs can be scheduled. |
| 1465 | self._ScheduleLoop() |
| 1466 | else: |
Brian Harring | 706747c | 2012-03-16 03:04:31 -0700 | [diff] [blame] | 1467 | # Print an update every 60 seconds. |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1468 | self._Status() |
| 1469 | continue |
| 1470 | |
| 1471 | target = job.target |
| 1472 | |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1473 | if job.fetch_only: |
| 1474 | if not job.done: |
| 1475 | self._fetch_jobs[job.target] = job |
| 1476 | else: |
| 1477 | state = self._state_map[job.target] |
| 1478 | state.prefetched = True |
| 1479 | state.fetched_successfully = (job.retcode == 0) |
| 1480 | del self._fetch_jobs[job.target] |
| 1481 | self._Print("Fetched %s in %2.2fs" |
| 1482 | % (target, time.time() - job.start_timestamp)) |
| 1483 | |
| 1484 | if self._show_output or job.retcode != 0: |
| 1485 | self._print_queue.put(JobPrinter(job, unlink=True)) |
| 1486 | else: |
| 1487 | os.unlink(job.filename) |
| 1488 | # Failure or not, let build work with it next. |
| 1489 | if not self._deps_map[job.target]["needs"]: |
| 1490 | self._build_ready.put(state) |
| 1491 | self._ScheduleLoop() |
| 1492 | |
| 1493 | if self._fetch_ready: |
| 1494 | state = self._fetch_ready.get() |
| 1495 | self._fetch_queue.put(state) |
| 1496 | self._fetch_jobs[state.target] = None |
| 1497 | else: |
| 1498 | # Minor optimization; shut down fetchers early since we know |
| 1499 | # the queue is empty. |
| 1500 | self._fetch_queue.put(None) |
| 1501 | continue |
| 1502 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1503 | if not job.done: |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1504 | self._build_jobs[target] = job |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1505 | self._Print("Started %s (logged in %s)" % (target, job.filename)) |
| 1506 | continue |
| 1507 | |
| 1508 | # Print output of job |
| 1509 | if self._show_output or job.retcode != 0: |
| 1510 | self._print_queue.put(JobPrinter(job, unlink=True)) |
| 1511 | else: |
| 1512 | os.unlink(job.filename) |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1513 | del self._build_jobs[target] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1514 | |
| 1515 | seconds = time.time() - job.start_timestamp |
| 1516 | details = "%s (in %dm%.1fs)" % (target, seconds / 60, seconds % 60) |
David James | 32420cc | 2011-08-25 21:32:46 -0700 | [diff] [blame] | 1517 | previously_failed = target in self._failed |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1518 | |
| 1519 | # Complain if necessary. |
| 1520 | if job.retcode != 0: |
| 1521 | # Handle job failure. |
David James | 32420cc | 2011-08-25 21:32:46 -0700 | [diff] [blame] | 1522 | if previously_failed: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1523 | # If this job has failed previously, give up. |
| 1524 | self._Print("Failed %s. Your build has failed." % details) |
| 1525 | else: |
| 1526 | # Queue up this build to try again after a long while. |
David James | e703d0f | 2012-01-12 16:27:45 -0800 | [diff] [blame] | 1527 | retried.add(target) |
Brian Harring | 0be85c6 | 2012-03-17 19:52:12 -0700 | [diff] [blame] | 1528 | self._retry_queue.append(self._state_map[target]) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1529 | self._failed.add(target) |
| 1530 | self._Print("Failed %s, retrying later." % details) |
| 1531 | else: |
David James | 32420cc | 2011-08-25 21:32:46 -0700 | [diff] [blame] | 1532 | if previously_failed: |
| 1533 | # Remove target from list of failed packages. |
| 1534 | self._failed.remove(target) |
| 1535 | |
| 1536 | self._Print("Completed %s" % details) |
| 1537 | |
| 1538 | # Mark as completed and unblock waiting ebuilds. |
| 1539 | self._Finish(target) |
| 1540 | |
| 1541 | if previously_failed and self._retry_queue: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1542 | # If we have successfully retried a failed package, and there |
| 1543 | # are more failed packages, try the next one. We will only have |
| 1544 | # one retrying package actively running at a time. |
| 1545 | self._Retry() |
| 1546 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1547 | |
David James | 8c7e5e3 | 2011-06-28 11:26:03 -0700 | [diff] [blame] | 1548 | # Schedule pending jobs and print an update. |
| 1549 | self._ScheduleLoop() |
| 1550 | self._Status() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1551 | |
David James | e703d0f | 2012-01-12 16:27:45 -0800 | [diff] [blame] | 1552 | # If packages were retried, output a warning. |
| 1553 | if retried: |
| 1554 | self._Print("") |
| 1555 | self._Print("WARNING: The following packages failed the first time,") |
| 1556 | self._Print("but succeeded upon retry. This might indicate incorrect") |
| 1557 | self._Print("dependencies.") |
| 1558 | for pkg in retried: |
| 1559 | self._Print(" %s" % pkg) |
| 1560 | self._Print("@@@STEP_WARNINGS@@@") |
| 1561 | self._Print("") |
| 1562 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1563 | # Tell child threads to exit. |
| 1564 | self._Print("Merge complete") |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1565 | |
| 1566 | |
Brian Harring | 3067505 | 2012-02-29 12:18:22 -0800 | [diff] [blame] | 1567 | def main(argv): |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 1568 | try: |
| 1569 | return real_main(argv) |
| 1570 | finally: |
| 1571 | # Work around multiprocessing sucking and not cleaning up after itself. |
| 1572 | # http://bugs.python.org/issue4106; |
| 1573 | # Step one; ensure GC is ran *prior* to the VM starting shutdown. |
| 1574 | gc.collect() |
| 1575 | # Step two; go looking for those threads and try to manually reap |
| 1576 | # them if we can. |
| 1577 | for x in threading.enumerate(): |
| 1578 | # Filter on the name, and ident; if ident is None, the thread |
| 1579 | # wasn't started. |
| 1580 | if x.name == 'QueueFeederThread' and x.ident is not None: |
| 1581 | x.join(1) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1582 | |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 1583 | |
| 1584 | def real_main(argv): |
Brian Harring | 3067505 | 2012-02-29 12:18:22 -0800 | [diff] [blame] | 1585 | parallel_emerge_args = argv[:] |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1586 | deps = DepGraphGenerator() |
Brian Harring | 3067505 | 2012-02-29 12:18:22 -0800 | [diff] [blame] | 1587 | deps.Initialize(parallel_emerge_args) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1588 | emerge = deps.emerge |
| 1589 | |
| 1590 | if emerge.action is not None: |
Brian Harring | 3067505 | 2012-02-29 12:18:22 -0800 | [diff] [blame] | 1591 | argv = deps.ParseParallelEmergeArgs(argv) |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 1592 | return emerge_main(argv) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1593 | elif not emerge.cmdline_packages: |
| 1594 | Usage() |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 1595 | return 1 |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1596 | |
| 1597 | # Unless we're in pretend mode, there's not much point running without |
| 1598 | # root access. We need to be able to install packages. |
| 1599 | # |
| 1600 | # NOTE: Even if you're running --pretend, it's a good idea to run |
| 1601 | # parallel_emerge with root access so that portage can write to the |
| 1602 | # dependency cache. This is important for performance. |
David James | 321490a | 2012-12-17 12:05:56 -0800 | [diff] [blame] | 1603 | if "--pretend" not in emerge.opts and portage.data.secpass < 2: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1604 | print "parallel_emerge: superuser access is required." |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 1605 | return 1 |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1606 | |
| 1607 | if "--quiet" not in emerge.opts: |
| 1608 | cmdline_packages = " ".join(emerge.cmdline_packages) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1609 | print "Starting fast-emerge." |
| 1610 | print " Building package %s on %s" % (cmdline_packages, |
| 1611 | deps.board or "root") |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1612 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 1613 | deps_tree, deps_info = deps.GenDependencyTree() |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1614 | |
| 1615 | # You want me to be verbose? I'll give you two trees! Twice as much value. |
| 1616 | if "--tree" in emerge.opts and "--verbose" in emerge.opts: |
| 1617 | deps.PrintTree(deps_tree) |
| 1618 | |
David James | 386ccd1 | 2011-05-04 20:17:42 -0700 | [diff] [blame] | 1619 | deps_graph = deps.GenDependencyGraph(deps_tree, deps_info) |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1620 | |
| 1621 | # OK, time to print out our progress so far. |
| 1622 | deps.PrintInstallPlan(deps_graph) |
| 1623 | if "--tree" in emerge.opts: |
| 1624 | PrintDepsMap(deps_graph) |
| 1625 | |
| 1626 | # Are we upgrading portage? If so, and there are more packages to merge, |
| 1627 | # schedule a restart of parallel_emerge to merge the rest. This ensures that |
| 1628 | # we pick up all updates to portage settings before merging any more |
| 1629 | # packages. |
| 1630 | portage_upgrade = False |
| 1631 | root = emerge.settings["ROOT"] |
| 1632 | final_db = emerge.depgraph._dynamic_config.mydbapi[root] |
| 1633 | if root == "/": |
| 1634 | for db_pkg in final_db.match_pkgs("sys-apps/portage"): |
| 1635 | portage_pkg = deps_graph.get(db_pkg.cpv) |
David James | 0ff16f2 | 2012-11-02 14:18:07 -0700 | [diff] [blame] | 1636 | if portage_pkg: |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1637 | portage_upgrade = True |
| 1638 | if "--quiet" not in emerge.opts: |
| 1639 | print "Upgrading portage first, then restarting..." |
| 1640 | |
David James | 0ff16f2 | 2012-11-02 14:18:07 -0700 | [diff] [blame] | 1641 | # Upgrade Portage first, then the rest of the packages. |
| 1642 | # |
| 1643 | # In order to grant the child permission to run setsid, we need to run sudo |
| 1644 | # again. We preserve SUDO_USER here in case an ebuild depends on it. |
| 1645 | if portage_upgrade: |
| 1646 | # Calculate what arguments to use when re-invoking. |
| 1647 | args = ["sudo", "-E", "SUDO_USER=%s" % os.environ.get("SUDO_USER", "")] |
| 1648 | args += [os.path.abspath(sys.argv[0])] + parallel_emerge_args |
| 1649 | args += ["--exclude=sys-apps/portage"] |
| 1650 | |
| 1651 | # First upgrade Portage. |
| 1652 | passthrough_args = ("--quiet", "--pretend", "--verbose") |
| 1653 | emerge_args = [k for k in emerge.opts if k in passthrough_args] |
| 1654 | ret = emerge_main(emerge_args + ["portage"]) |
| 1655 | if ret != 0: |
| 1656 | return ret |
| 1657 | |
| 1658 | # Now upgrade the rest. |
| 1659 | os.execvp(args[0], args) |
| 1660 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1661 | # Run the queued emerges. |
| 1662 | scheduler = EmergeQueue(deps_graph, emerge, deps.package_db, deps.show_output) |
Brian Harring | a43f595 | 2012-04-12 01:19:34 -0700 | [diff] [blame] | 1663 | try: |
| 1664 | scheduler.Run() |
| 1665 | finally: |
| 1666 | scheduler._Shutdown() |
David James | 97ce890 | 2011-08-16 09:51:05 -0700 | [diff] [blame] | 1667 | scheduler = None |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1668 | |
Mike Frysinger | d20a6e2 | 2012-10-04 19:01:10 -0400 | [diff] [blame] | 1669 | clean_logs(emerge.settings) |
| 1670 | |
David James | fcb70ef | 2011-02-02 16:02:30 -0800 | [diff] [blame] | 1671 | print "Done" |
Brian Harring | 8294d65 | 2012-05-23 02:20:52 -0700 | [diff] [blame] | 1672 | return 0 |