blob: 64707a70505c8bca96a09a1db09e6a876ec7a703 [file] [log] [blame]
David Pursell9476bf42015-03-30 13:34:27 -07001# Copyright 2015 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Alex Kleinaaddc932020-01-30 15:02:24 -07005"""Deploy packages onto a target device.
6
7Integration tests for this file can be found at cli/cros/tests/cros_vm_tests.py.
8See that file for more information.
9"""
David Pursell9476bf42015-03-30 13:34:27 -070010
Mike Frysinger93e8ffa2019-07-03 20:24:18 -040011from __future__ import division
David Pursell9476bf42015-03-30 13:34:27 -070012
Xiaochu Liu2726e7c2019-07-18 10:28:10 -070013import bz2
David Pursell9476bf42015-03-30 13:34:27 -070014import fnmatch
Ralph Nathane01ccf12015-04-16 10:40:32 -070015import functools
David Pursell9476bf42015-03-30 13:34:27 -070016import json
Chris McDonald14ac61d2021-07-21 11:49:56 -060017import logging
David Pursell9476bf42015-03-30 13:34:27 -070018import os
Jae Hoon Kim2376e142022-09-03 00:18:58 +000019from pathlib import Path
Xiaochu Liu2726e7c2019-07-18 10:28:10 -070020import tempfile
David Pursell9476bf42015-03-30 13:34:27 -070021
Ralph Nathane01ccf12015-04-16 10:40:32 -070022from chromite.cli import command
Mike Frysinger06a51c82021-04-06 11:39:17 -040023from chromite.lib import build_target_lib
Ram Chandrasekar56152ec2021-11-22 17:10:41 +000024from chromite.lib import constants
David Pursell9476bf42015-03-30 13:34:27 -070025from chromite.lib import cros_build_lib
Alex Klein18a60af2020-06-11 12:08:47 -060026from chromite.lib import dlc_lib
Ralph Nathane01ccf12015-04-16 10:40:32 -070027from chromite.lib import operation
Xiaochu Liu2726e7c2019-07-18 10:28:10 -070028from chromite.lib import osutils
David Pursell9476bf42015-03-30 13:34:27 -070029from chromite.lib import portage_util
David Pursell9476bf42015-03-30 13:34:27 -070030from chromite.lib import remote_access
Kimiyuki Onakaa4ec7f62020-08-25 13:58:48 +090031from chromite.lib import workon_helper
Alex Klein18a60af2020-06-11 12:08:47 -060032from chromite.lib.parser import package_info
33
Chris McDonald14ac61d2021-07-21 11:49:56 -060034
David Pursell9476bf42015-03-30 13:34:27 -070035try:
Alex Klein1699fab2022-09-08 08:46:06 -060036 import portage
David Pursell9476bf42015-03-30 13:34:27 -070037except ImportError:
Alex Klein1699fab2022-09-08 08:46:06 -060038 if cros_build_lib.IsInsideChroot():
39 raise
David Pursell9476bf42015-03-30 13:34:27 -070040
41
Alex Klein1699fab2022-09-08 08:46:06 -060042_DEVICE_BASE_DIR = "/usr/local/tmp/cros-deploy"
David Pursell9476bf42015-03-30 13:34:27 -070043# This is defined in src/platform/dev/builder.py
Alex Klein1699fab2022-09-08 08:46:06 -060044_STRIPPED_PACKAGES_DIR = "stripped-packages"
David Pursell9476bf42015-03-30 13:34:27 -070045
46_MAX_UPDATES_NUM = 10
47_MAX_UPDATES_WARNING = (
Alex Klein1699fab2022-09-08 08:46:06 -060048 "You are about to update a large number of installed packages, which "
49 "might take a long time, fail midway, or leave the target in an "
50 "inconsistent state. It is highly recommended that you flash a new image "
51 "instead."
52)
David Pursell9476bf42015-03-30 13:34:27 -070053
Alex Klein1699fab2022-09-08 08:46:06 -060054_DLC_ID = "DLC_ID"
55_DLC_PACKAGE = "DLC_PACKAGE"
56_DLC_ENABLED = "DLC_ENABLED"
57_ENVIRONMENT_FILENAME = "environment.bz2"
58_DLC_INSTALL_ROOT = "/var/cache/dlc"
Xiaochu Liu2726e7c2019-07-18 10:28:10 -070059
David Pursell9476bf42015-03-30 13:34:27 -070060
61class DeployError(Exception):
Alex Klein1699fab2022-09-08 08:46:06 -060062 """Thrown when an unrecoverable error is encountered during deploy."""
David Pursell9476bf42015-03-30 13:34:27 -070063
64
Ralph Nathane01ccf12015-04-16 10:40:32 -070065class BrilloDeployOperation(operation.ProgressBarOperation):
Alex Klein1699fab2022-09-08 08:46:06 -060066 """ProgressBarOperation specific for brillo deploy."""
Ralph Nathane01ccf12015-04-16 10:40:32 -070067
Alex Klein1699fab2022-09-08 08:46:06 -060068 # These two variables are used to validate the output in the VM integration
69 # tests. Changes to the output must be reflected here.
70 MERGE_EVENTS = (
71 "Preparing local packages",
72 "NOTICE: Copying binpkgs",
73 "NOTICE: Installing",
74 "been installed.",
75 "Please restart any updated",
76 )
77 UNMERGE_EVENTS = (
78 "NOTICE: Unmerging",
79 "been uninstalled.",
80 "Please restart any updated",
81 )
Ralph Nathane01ccf12015-04-16 10:40:32 -070082
Alex Klein1699fab2022-09-08 08:46:06 -060083 def __init__(self, emerge):
84 """Construct BrilloDeployOperation object.
Ralph Nathane01ccf12015-04-16 10:40:32 -070085
Alex Klein1699fab2022-09-08 08:46:06 -060086 Args:
87 emerge: True if emerge, False is unmerge.
88 """
89 super().__init__()
90 if emerge:
91 self._events = self.MERGE_EVENTS
92 else:
93 self._events = self.UNMERGE_EVENTS
94 self._total = len(self._events)
95 self._completed = 0
96
97 def ParseOutput(self, output=None):
98 """Parse the output of brillo deploy to update a progress bar."""
99 stdout = self._stdout.read()
100 stderr = self._stderr.read()
101 output = stdout + stderr
102 for event in self._events:
103 self._completed += output.count(event)
104 self.ProgressBar(self._completed / self._total)
Ralph Nathane01ccf12015-04-16 10:40:32 -0700105
106
David Pursell9476bf42015-03-30 13:34:27 -0700107class _InstallPackageScanner(object):
Alex Klein1699fab2022-09-08 08:46:06 -0600108 """Finds packages that need to be installed on a target device.
David Pursell9476bf42015-03-30 13:34:27 -0700109
Alex Klein1699fab2022-09-08 08:46:06 -0600110 Scans the sysroot bintree, beginning with a user-provided list of packages,
111 to find all packages that need to be installed. If so instructed,
112 transitively scans forward (mandatory) and backward (optional) dependencies
113 as well. A package will be installed if missing on the target (mandatory
114 packages only), or it will be updated if its sysroot version and build time
115 are different from the target. Common usage:
David Pursell9476bf42015-03-30 13:34:27 -0700116
Alex Klein1699fab2022-09-08 08:46:06 -0600117 pkg_scanner = _InstallPackageScanner(sysroot)
118 pkgs = pkg_scanner.Run(...)
119 """
David Pursell9476bf42015-03-30 13:34:27 -0700120
Alex Klein1699fab2022-09-08 08:46:06 -0600121 class VartreeError(Exception):
122 """An error in the processing of the installed packages tree."""
David Pursell9476bf42015-03-30 13:34:27 -0700123
Alex Klein1699fab2022-09-08 08:46:06 -0600124 class BintreeError(Exception):
125 """An error in the processing of the source binpkgs tree."""
David Pursell9476bf42015-03-30 13:34:27 -0700126
Alex Klein1699fab2022-09-08 08:46:06 -0600127 class PkgInfo(object):
128 """A record containing package information."""
David Pursell9476bf42015-03-30 13:34:27 -0700129
Alex Klein1699fab2022-09-08 08:46:06 -0600130 __slots__ = ("cpv", "build_time", "rdeps_raw", "rdeps", "rev_rdeps")
David Pursell9476bf42015-03-30 13:34:27 -0700131
Alex Klein1699fab2022-09-08 08:46:06 -0600132 def __init__(
133 self, cpv, build_time, rdeps_raw, rdeps=None, rev_rdeps=None
134 ):
135 self.cpv = cpv
136 self.build_time = build_time
137 self.rdeps_raw = rdeps_raw
138 self.rdeps = set() if rdeps is None else rdeps
139 self.rev_rdeps = set() if rev_rdeps is None else rev_rdeps
David Pursell9476bf42015-03-30 13:34:27 -0700140
Alex Klein1699fab2022-09-08 08:46:06 -0600141 # Python snippet for dumping vartree info on the target. Instantiate using
142 # _GetVartreeSnippet().
143 _GET_VARTREE = """
David Pursell9476bf42015-03-30 13:34:27 -0700144import json
Gwendal Grignou99e6f532018-10-25 12:16:28 -0700145import os
146import portage
147
148# Normalize the path to match what portage will index.
149target_root = os.path.normpath('%(root)s')
150if not target_root.endswith('/'):
151 target_root += '/'
152trees = portage.create_trees(target_root=target_root, config_root='/')
153vartree = trees[target_root]['vartree']
David Pursell9476bf42015-03-30 13:34:27 -0700154pkg_info = []
155for cpv in vartree.dbapi.cpv_all():
156 slot, rdep_raw, build_time = vartree.dbapi.aux_get(
157 cpv, ('SLOT', 'RDEPEND', 'BUILD_TIME'))
158 pkg_info.append((cpv, slot, rdep_raw, build_time))
159
160print(json.dumps(pkg_info))
161"""
162
Alex Klein1699fab2022-09-08 08:46:06 -0600163 def __init__(self, sysroot):
164 self.sysroot = sysroot
165 # Members containing the sysroot (binpkg) and target (installed) package DB.
166 self.target_db = None
167 self.binpkgs_db = None
168 # Members for managing the dependency resolution work queue.
169 self.queue = None
170 self.seen = None
171 self.listed = None
David Pursell9476bf42015-03-30 13:34:27 -0700172
Alex Klein1699fab2022-09-08 08:46:06 -0600173 @staticmethod
174 def _GetCP(cpv):
175 """Returns the CP value for a given CPV string."""
176 attrs = package_info.SplitCPV(cpv, strict=False)
177 if not attrs.cp:
178 raise ValueError("Cannot get CP value for %s" % cpv)
179 return attrs.cp
David Pursell9476bf42015-03-30 13:34:27 -0700180
Alex Klein1699fab2022-09-08 08:46:06 -0600181 @staticmethod
182 def _InDB(cp, slot, db):
183 """Returns whether CP and slot are found in a database (if provided)."""
184 cp_slots = db.get(cp) if db else None
185 return cp_slots is not None and (not slot or slot in cp_slots)
David Pursell9476bf42015-03-30 13:34:27 -0700186
Alex Klein1699fab2022-09-08 08:46:06 -0600187 @staticmethod
188 def _AtomStr(cp, slot):
189 """Returns 'CP:slot' if slot is non-empty, else just 'CP'."""
190 return "%s:%s" % (cp, slot) if slot else cp
David Pursell9476bf42015-03-30 13:34:27 -0700191
Alex Klein1699fab2022-09-08 08:46:06 -0600192 @classmethod
193 def _GetVartreeSnippet(cls, root="/"):
194 """Returns a code snippet for dumping the vartree on the target.
David Pursell9476bf42015-03-30 13:34:27 -0700195
Alex Klein1699fab2022-09-08 08:46:06 -0600196 Args:
197 root: The installation root.
David Pursell9476bf42015-03-30 13:34:27 -0700198
Alex Klein1699fab2022-09-08 08:46:06 -0600199 Returns:
200 The said code snippet (string) with parameters filled in.
201 """
202 return cls._GET_VARTREE % {"root": root}
David Pursell9476bf42015-03-30 13:34:27 -0700203
Alex Klein1699fab2022-09-08 08:46:06 -0600204 @classmethod
205 def _StripDepAtom(cls, dep_atom, installed_db=None):
206 """Strips a dependency atom and returns a (CP, slot) pair."""
207 # TODO(garnold) This is a gross simplification of ebuild dependency
208 # semantics, stripping and ignoring various qualifiers (versions, slots,
209 # USE flag, negation) and will likely need to be fixed. chromium:447366.
David Pursell9476bf42015-03-30 13:34:27 -0700210
Alex Klein1699fab2022-09-08 08:46:06 -0600211 # Ignore unversioned blockers, leaving them for the user to resolve.
212 if dep_atom[0] == "!" and dep_atom[1] not in "<=>~":
213 return None, None
David Pursell9476bf42015-03-30 13:34:27 -0700214
Alex Klein1699fab2022-09-08 08:46:06 -0600215 cp = dep_atom
216 slot = None
217 require_installed = False
David Pursell9476bf42015-03-30 13:34:27 -0700218
Alex Klein1699fab2022-09-08 08:46:06 -0600219 # Versioned blockers should be updated, but only if already installed.
220 # These are often used for forcing cascaded updates of multiple packages,
221 # so we're treating them as ordinary constraints with hopes that it'll lead
222 # to the desired result.
223 if cp.startswith("!"):
224 cp = cp.lstrip("!")
225 require_installed = True
David Pursell9476bf42015-03-30 13:34:27 -0700226
Alex Klein1699fab2022-09-08 08:46:06 -0600227 # Remove USE flags.
228 if "[" in cp:
229 cp = cp[: cp.index("[")] + cp[cp.index("]") + 1 :]
David Pursell9476bf42015-03-30 13:34:27 -0700230
Alex Klein1699fab2022-09-08 08:46:06 -0600231 # Separate the slot qualifier and strip off subslots.
232 if ":" in cp:
233 cp, slot = cp.split(":")
234 for delim in ("/", "="):
235 slot = slot.split(delim, 1)[0]
David Pursell9476bf42015-03-30 13:34:27 -0700236
Alex Klein1699fab2022-09-08 08:46:06 -0600237 # Strip version wildcards (right), comparators (left).
238 cp = cp.rstrip("*")
239 cp = cp.lstrip("<=>~")
David Pursell9476bf42015-03-30 13:34:27 -0700240
Alex Klein1699fab2022-09-08 08:46:06 -0600241 # Turn into CP form.
242 cp = cls._GetCP(cp)
David Pursell9476bf42015-03-30 13:34:27 -0700243
Alex Klein1699fab2022-09-08 08:46:06 -0600244 if require_installed and not cls._InDB(cp, None, installed_db):
245 return None, None
David Pursell9476bf42015-03-30 13:34:27 -0700246
Alex Klein1699fab2022-09-08 08:46:06 -0600247 return cp, slot
David Pursell9476bf42015-03-30 13:34:27 -0700248
Alex Klein1699fab2022-09-08 08:46:06 -0600249 @classmethod
250 def _ProcessDepStr(cls, dep_str, installed_db, avail_db):
251 """Resolves and returns a list of dependencies from a dependency string.
David Pursell9476bf42015-03-30 13:34:27 -0700252
Alex Klein1699fab2022-09-08 08:46:06 -0600253 This parses a dependency string and returns a list of package names and
254 slots. Other atom qualifiers (version, sub-slot, block) are ignored. When
255 resolving disjunctive deps, we include all choices that are fully present
256 in |installed_db|. If none is present, we choose an arbitrary one that is
257 available.
David Pursell9476bf42015-03-30 13:34:27 -0700258
Alex Klein1699fab2022-09-08 08:46:06 -0600259 Args:
260 dep_str: A raw dependency string.
261 installed_db: A database of installed packages.
262 avail_db: A database of packages available for installation.
David Pursell9476bf42015-03-30 13:34:27 -0700263
Alex Klein1699fab2022-09-08 08:46:06 -0600264 Returns:
265 A list of pairs (CP, slot).
David Pursell9476bf42015-03-30 13:34:27 -0700266
Alex Klein1699fab2022-09-08 08:46:06 -0600267 Raises:
268 ValueError: the dependencies string is malformed.
269 """
David Pursell9476bf42015-03-30 13:34:27 -0700270
Alex Klein1699fab2022-09-08 08:46:06 -0600271 def ProcessSubDeps(dep_exp, disjunct):
272 """Parses and processes a dependency (sub)expression."""
273 deps = set()
274 default_deps = set()
275 sub_disjunct = False
276 for dep_sub_exp in dep_exp:
277 sub_deps = set()
David Pursell9476bf42015-03-30 13:34:27 -0700278
Alex Klein1699fab2022-09-08 08:46:06 -0600279 if isinstance(dep_sub_exp, (list, tuple)):
280 sub_deps = ProcessSubDeps(dep_sub_exp, sub_disjunct)
281 sub_disjunct = False
282 elif sub_disjunct:
283 raise ValueError("Malformed disjunctive operation in deps")
284 elif dep_sub_exp == "||":
285 sub_disjunct = True
286 elif dep_sub_exp.endswith("?"):
287 raise ValueError("Dependencies contain a conditional")
288 else:
289 cp, slot = cls._StripDepAtom(dep_sub_exp, installed_db)
290 if cp:
291 sub_deps = set([(cp, slot)])
292 elif disjunct:
293 raise ValueError("Atom in disjunct ignored")
David Pursell9476bf42015-03-30 13:34:27 -0700294
Alex Klein1699fab2022-09-08 08:46:06 -0600295 # Handle sub-deps of a disjunctive expression.
296 if disjunct:
297 # Make the first available choice the default, for use in case that
298 # no option is installed.
299 if (
300 not default_deps
301 and avail_db is not None
302 and all(
303 cls._InDB(cp, slot, avail_db)
304 for cp, slot in sub_deps
305 )
306 ):
307 default_deps = sub_deps
David Pursell9476bf42015-03-30 13:34:27 -0700308
Alex Klein1699fab2022-09-08 08:46:06 -0600309 # If not all sub-deps are installed, then don't consider them.
310 if not all(
311 cls._InDB(cp, slot, installed_db)
312 for cp, slot in sub_deps
313 ):
314 sub_deps = set()
David Pursell9476bf42015-03-30 13:34:27 -0700315
Alex Klein1699fab2022-09-08 08:46:06 -0600316 deps.update(sub_deps)
David Pursell9476bf42015-03-30 13:34:27 -0700317
Alex Klein1699fab2022-09-08 08:46:06 -0600318 return deps or default_deps
David Pursell9476bf42015-03-30 13:34:27 -0700319
Alex Klein1699fab2022-09-08 08:46:06 -0600320 try:
321 return ProcessSubDeps(portage.dep.paren_reduce(dep_str), False)
322 except portage.exception.InvalidDependString as e:
323 raise ValueError("Invalid dep string: %s" % e)
324 except ValueError as e:
325 raise ValueError("%s: %s" % (e, dep_str))
David Pursell9476bf42015-03-30 13:34:27 -0700326
Alex Klein1699fab2022-09-08 08:46:06 -0600327 def _BuildDB(
328 self, cpv_info, process_rdeps, process_rev_rdeps, installed_db=None
329 ):
330 """Returns a database of packages given a list of CPV info.
David Pursell9476bf42015-03-30 13:34:27 -0700331
Alex Klein1699fab2022-09-08 08:46:06 -0600332 Args:
333 cpv_info: A list of tuples containing package CPV and attributes.
334 process_rdeps: Whether to populate forward dependencies.
335 process_rev_rdeps: Whether to populate reverse dependencies.
336 installed_db: A database of installed packages for filtering disjunctive
337 choices against; if None, using own built database.
David Pursell9476bf42015-03-30 13:34:27 -0700338
Alex Klein1699fab2022-09-08 08:46:06 -0600339 Returns:
340 A map from CP values to another dictionary that maps slots to package
341 attribute tuples. Tuples contain a CPV value (string), build time
342 (string), runtime dependencies (set), and reverse dependencies (set,
343 empty if not populated).
David Pursell9476bf42015-03-30 13:34:27 -0700344
Alex Klein1699fab2022-09-08 08:46:06 -0600345 Raises:
346 ValueError: If more than one CPV occupies a single slot.
347 """
348 db = {}
349 logging.debug("Populating package DB...")
350 for cpv, slot, rdeps_raw, build_time in cpv_info:
351 cp = self._GetCP(cpv)
352 cp_slots = db.setdefault(cp, dict())
353 if slot in cp_slots:
354 raise ValueError(
355 "More than one package found for %s"
356 % self._AtomStr(cp, slot)
357 )
358 logging.debug(
359 " %s -> %s, built %s, raw rdeps: %s",
360 self._AtomStr(cp, slot),
361 cpv,
362 build_time,
363 rdeps_raw,
364 )
365 cp_slots[slot] = self.PkgInfo(cpv, build_time, rdeps_raw)
David Pursell9476bf42015-03-30 13:34:27 -0700366
Alex Klein1699fab2022-09-08 08:46:06 -0600367 avail_db = db
368 if installed_db is None:
369 installed_db = db
370 avail_db = None
David Pursell9476bf42015-03-30 13:34:27 -0700371
Alex Klein1699fab2022-09-08 08:46:06 -0600372 # Add approximate forward dependencies.
David Pursell9476bf42015-03-30 13:34:27 -0700373 if process_rdeps:
Alex Klein1699fab2022-09-08 08:46:06 -0600374 logging.debug("Populating forward dependencies...")
375 for cp, cp_slots in db.items():
376 for slot, pkg_info in cp_slots.items():
377 pkg_info.rdeps.update(
378 self._ProcessDepStr(
379 pkg_info.rdeps_raw, installed_db, avail_db
380 )
381 )
382 logging.debug(
383 " %s (%s) processed rdeps: %s",
384 self._AtomStr(cp, slot),
385 pkg_info.cpv,
386 " ".join(
387 [
388 self._AtomStr(rdep_cp, rdep_slot)
389 for rdep_cp, rdep_slot in pkg_info.rdeps
390 ]
391 ),
392 )
393
394 # Add approximate reverse dependencies (optional).
David Pursell9476bf42015-03-30 13:34:27 -0700395 if process_rev_rdeps:
Alex Klein1699fab2022-09-08 08:46:06 -0600396 logging.debug("Populating reverse dependencies...")
397 for cp, cp_slots in db.items():
398 for slot, pkg_info in cp_slots.items():
399 for rdep_cp, rdep_slot in pkg_info.rdeps:
400 to_slots = db.get(rdep_cp)
401 if not to_slots:
402 continue
David Pursell9476bf42015-03-30 13:34:27 -0700403
Alex Klein1699fab2022-09-08 08:46:06 -0600404 for to_slot, to_pkg_info in to_slots.items():
405 if rdep_slot and to_slot != rdep_slot:
406 continue
407 logging.debug(
408 " %s (%s) added as rev rdep for %s (%s)",
409 self._AtomStr(cp, slot),
410 pkg_info.cpv,
411 self._AtomStr(rdep_cp, to_slot),
412 to_pkg_info.cpv,
413 )
414 to_pkg_info.rev_rdeps.add((cp, slot))
David Pursell9476bf42015-03-30 13:34:27 -0700415
Alex Klein1699fab2022-09-08 08:46:06 -0600416 return db
David Pursell9476bf42015-03-30 13:34:27 -0700417
Alex Klein1699fab2022-09-08 08:46:06 -0600418 def _InitTargetVarDB(self, device, root, process_rdeps, process_rev_rdeps):
419 """Initializes a dictionary of packages installed on |device|."""
420 get_vartree_script = self._GetVartreeSnippet(root)
421 try:
422 result = device.GetAgent().RemoteSh(
423 ["python"], remote_sudo=True, input=get_vartree_script
424 )
425 except cros_build_lib.RunCommandError as e:
426 logging.error("Cannot get target vartree:\n%s", e.stderr)
427 raise
David Pursell9476bf42015-03-30 13:34:27 -0700428
Alex Klein1699fab2022-09-08 08:46:06 -0600429 try:
430 self.target_db = self._BuildDB(
431 json.loads(result.stdout), process_rdeps, process_rev_rdeps
432 )
433 except ValueError as e:
434 raise self.VartreeError(str(e))
David Pursell9476bf42015-03-30 13:34:27 -0700435
Alex Klein1699fab2022-09-08 08:46:06 -0600436 def _InitBinpkgDB(self, process_rdeps):
437 """Initializes a dictionary of binary packages for updating the target."""
438 # Get build root trees; portage indexes require a trailing '/'.
439 build_root = os.path.join(self.sysroot, "")
440 trees = portage.create_trees(
441 target_root=build_root, config_root=build_root
442 )
443 bintree = trees[build_root]["bintree"]
444 binpkgs_info = []
445 for cpv in bintree.dbapi.cpv_all():
446 slot, rdep_raw, build_time = bintree.dbapi.aux_get(
447 cpv, ["SLOT", "RDEPEND", "BUILD_TIME"]
448 )
449 binpkgs_info.append((cpv, slot, rdep_raw, build_time))
David Pursell9476bf42015-03-30 13:34:27 -0700450
Alex Klein1699fab2022-09-08 08:46:06 -0600451 try:
452 self.binpkgs_db = self._BuildDB(
453 binpkgs_info, process_rdeps, False, installed_db=self.target_db
454 )
455 except ValueError as e:
456 raise self.BintreeError(str(e))
David Pursell9476bf42015-03-30 13:34:27 -0700457
Alex Klein1699fab2022-09-08 08:46:06 -0600458 def _InitDepQueue(self):
459 """Initializes the dependency work queue."""
460 self.queue = set()
461 self.seen = {}
462 self.listed = set()
David Pursell9476bf42015-03-30 13:34:27 -0700463
Alex Klein1699fab2022-09-08 08:46:06 -0600464 def _EnqDep(self, dep, listed, optional):
465 """Enqueues a dependency if not seen before or if turned non-optional."""
466 if dep in self.seen and (optional or not self.seen[dep]):
467 return False
David Pursell9476bf42015-03-30 13:34:27 -0700468
Alex Klein1699fab2022-09-08 08:46:06 -0600469 self.queue.add(dep)
470 self.seen[dep] = optional
471 if listed:
472 self.listed.add(dep)
473 return True
David Pursell9476bf42015-03-30 13:34:27 -0700474
Alex Klein1699fab2022-09-08 08:46:06 -0600475 def _DeqDep(self):
476 """Dequeues and returns a dependency, its listed and optional flags.
David Pursell9476bf42015-03-30 13:34:27 -0700477
Alex Klein1699fab2022-09-08 08:46:06 -0600478 This returns listed packages first, if any are present, to ensure that we
479 correctly mark them as such when they are first being processed.
480 """
481 if self.listed:
482 dep = self.listed.pop()
483 self.queue.remove(dep)
484 listed = True
485 else:
486 dep = self.queue.pop()
487 listed = False
David Pursell9476bf42015-03-30 13:34:27 -0700488
Alex Klein1699fab2022-09-08 08:46:06 -0600489 return dep, listed, self.seen[dep]
David Pursell9476bf42015-03-30 13:34:27 -0700490
Alex Klein1699fab2022-09-08 08:46:06 -0600491 def _FindPackageMatches(self, cpv_pattern):
492 """Returns list of binpkg (CP, slot) pairs that match |cpv_pattern|.
David Pursell9476bf42015-03-30 13:34:27 -0700493
Alex Klein1699fab2022-09-08 08:46:06 -0600494 This is breaking |cpv_pattern| into its C, P and V components, each of
495 which may or may not be present or contain wildcards. It then scans the
496 binpkgs database to find all atoms that match these components, returning a
497 list of CP and slot qualifier. When the pattern does not specify a version,
498 or when a CP has only one slot in the binpkgs database, we omit the slot
499 qualifier in the result.
David Pursell9476bf42015-03-30 13:34:27 -0700500
Alex Klein1699fab2022-09-08 08:46:06 -0600501 Args:
502 cpv_pattern: A CPV pattern, potentially partial and/or having wildcards.
David Pursell9476bf42015-03-30 13:34:27 -0700503
Alex Klein1699fab2022-09-08 08:46:06 -0600504 Returns:
505 A list of (CPV, slot) pairs of packages in the binpkgs database that
506 match the pattern.
507 """
508 attrs = package_info.SplitCPV(cpv_pattern, strict=False)
509 cp_pattern = os.path.join(attrs.category or "*", attrs.package or "*")
510 matches = []
511 for cp, cp_slots in self.binpkgs_db.items():
512 if not fnmatch.fnmatchcase(cp, cp_pattern):
513 continue
David Pursell9476bf42015-03-30 13:34:27 -0700514
Alex Klein1699fab2022-09-08 08:46:06 -0600515 # If no version attribute was given or there's only one slot, omit the
516 # slot qualifier.
517 if not attrs.version or len(cp_slots) == 1:
518 matches.append((cp, None))
519 else:
520 cpv_pattern = "%s-%s" % (cp, attrs.version)
521 for slot, pkg_info in cp_slots.items():
522 if fnmatch.fnmatchcase(pkg_info.cpv, cpv_pattern):
523 matches.append((cp, slot))
David Pursell9476bf42015-03-30 13:34:27 -0700524
Alex Klein1699fab2022-09-08 08:46:06 -0600525 return matches
David Pursell9476bf42015-03-30 13:34:27 -0700526
Alex Klein1699fab2022-09-08 08:46:06 -0600527 def _FindPackage(self, pkg):
528 """Returns the (CP, slot) pair for a package matching |pkg|.
David Pursell9476bf42015-03-30 13:34:27 -0700529
Alex Klein1699fab2022-09-08 08:46:06 -0600530 Args:
531 pkg: Path to a binary package or a (partial) package CPV specifier.
David Pursell9476bf42015-03-30 13:34:27 -0700532
Alex Klein1699fab2022-09-08 08:46:06 -0600533 Returns:
534 A (CP, slot) pair for the given package; slot may be None (unspecified).
David Pursell9476bf42015-03-30 13:34:27 -0700535
Alex Klein1699fab2022-09-08 08:46:06 -0600536 Raises:
537 ValueError: if |pkg| is not a binpkg file nor does it match something
538 that's in the bintree.
539 """
540 if pkg.endswith(".tbz2") and os.path.isfile(pkg):
541 package = os.path.basename(os.path.splitext(pkg)[0])
542 category = os.path.basename(os.path.dirname(pkg))
543 return self._GetCP(os.path.join(category, package)), None
David Pursell9476bf42015-03-30 13:34:27 -0700544
Alex Klein1699fab2022-09-08 08:46:06 -0600545 matches = self._FindPackageMatches(pkg)
546 if not matches:
547 raise ValueError("No package found for %s" % pkg)
Xiaochu Liu2726e7c2019-07-18 10:28:10 -0700548
Alex Klein1699fab2022-09-08 08:46:06 -0600549 idx = 0
550 if len(matches) > 1:
551 # Ask user to pick among multiple matches.
552 idx = cros_build_lib.GetChoice(
553 "Multiple matches found for %s: " % pkg,
554 ["%s:%s" % (cp, slot) if slot else cp for cp, slot in matches],
555 )
Xiaochu Liu2726e7c2019-07-18 10:28:10 -0700556
Alex Klein1699fab2022-09-08 08:46:06 -0600557 return matches[idx]
558
559 def _NeedsInstall(self, cpv, slot, build_time, optional):
560 """Returns whether a package needs to be installed on the target.
561
562 Args:
563 cpv: Fully qualified CPV (string) of the package.
564 slot: Slot identifier (string).
565 build_time: The BUILT_TIME value (string) of the binpkg.
566 optional: Whether package is optional on the target.
567
568 Returns:
569 A tuple (install, update) indicating whether to |install| the package and
570 whether it is an |update| to an existing package.
571
572 Raises:
573 ValueError: if slot is not provided.
574 """
575 # If not checking installed packages, always install.
576 if not self.target_db:
577 return True, False
578
579 cp = self._GetCP(cpv)
580 target_pkg_info = self.target_db.get(cp, dict()).get(slot)
581 if target_pkg_info is not None:
582 if cpv != target_pkg_info.cpv:
583 attrs = package_info.SplitCPV(cpv)
584 target_attrs = package_info.SplitCPV(target_pkg_info.cpv)
585 logging.debug(
586 "Updating %s: version (%s) different on target (%s)",
587 cp,
588 attrs.version,
589 target_attrs.version,
590 )
591 return True, True
592
593 if build_time != target_pkg_info.build_time:
594 logging.debug(
595 "Updating %s: build time (%s) different on target (%s)",
596 cpv,
597 build_time,
598 target_pkg_info.build_time,
599 )
600 return True, True
601
602 logging.debug(
603 "Not updating %s: already up-to-date (%s, built %s)",
604 cp,
605 target_pkg_info.cpv,
606 target_pkg_info.build_time,
607 )
608 return False, False
609
610 if optional:
611 logging.debug(
612 "Not installing %s: missing on target but optional", cp
613 )
614 return False, False
615
616 logging.debug(
617 "Installing %s: missing on target and non-optional (%s)", cp, cpv
618 )
619 return True, False
620
621 def _ProcessDeps(self, deps, reverse):
622 """Enqueues dependencies for processing.
623
624 Args:
625 deps: List of dependencies to enqueue.
626 reverse: Whether these are reverse dependencies.
627 """
628 if not deps:
629 return
630
631 logging.debug(
632 "Processing %d %s dep(s)...",
633 len(deps),
634 "reverse" if reverse else "forward",
635 )
636 num_already_seen = 0
637 for dep in deps:
638 if self._EnqDep(dep, False, reverse):
639 logging.debug(" Queued dep %s", dep)
640 else:
641 num_already_seen += 1
642
643 if num_already_seen:
644 logging.debug("%d dep(s) already seen", num_already_seen)
645
646 def _ComputeInstalls(self, process_rdeps, process_rev_rdeps):
647 """Returns a dictionary of packages that need to be installed on the target.
648
649 Args:
650 process_rdeps: Whether to trace forward dependencies.
651 process_rev_rdeps: Whether to trace backward dependencies as well.
652
653 Returns:
654 A dictionary mapping CP values (string) to tuples containing a CPV
655 (string), a slot (string), a boolean indicating whether the package
656 was initially listed in the queue, and a boolean indicating whether this
657 is an update to an existing package.
658 """
659 installs = {}
660 while self.queue:
661 dep, listed, optional = self._DeqDep()
662 cp, required_slot = dep
663 if cp in installs:
664 logging.debug("Already updating %s", cp)
665 continue
666
667 cp_slots = self.binpkgs_db.get(cp, dict())
668 logging.debug(
669 "Checking packages matching %s%s%s...",
670 cp,
671 " (slot: %s)" % required_slot if required_slot else "",
672 " (optional)" if optional else "",
673 )
674 num_processed = 0
675 for slot, pkg_info in cp_slots.items():
676 if required_slot and slot != required_slot:
677 continue
678
679 num_processed += 1
680 logging.debug(" Checking %s...", pkg_info.cpv)
681
682 install, update = self._NeedsInstall(
683 pkg_info.cpv, slot, pkg_info.build_time, optional
684 )
685 if not install:
686 continue
687
688 installs[cp] = (pkg_info.cpv, slot, listed, update)
689
690 # Add forward and backward runtime dependencies to queue.
691 if process_rdeps:
692 self._ProcessDeps(pkg_info.rdeps, False)
693 if process_rev_rdeps:
694 target_pkg_info = self.target_db.get(cp, dict()).get(slot)
695 if target_pkg_info:
696 self._ProcessDeps(target_pkg_info.rev_rdeps, True)
697
698 if num_processed == 0:
699 logging.warning(
700 "No qualified bintree package corresponding to %s", cp
701 )
702
703 return installs
704
705 def _SortInstalls(self, installs):
706 """Returns a sorted list of packages to install.
707
708 Performs a topological sort based on dependencies found in the binary
709 package database.
710
711 Args:
712 installs: Dictionary of packages to install indexed by CP.
713
714 Returns:
715 A list of package CPVs (string).
716
717 Raises:
718 ValueError: If dependency graph contains a cycle.
719 """
720 not_visited = set(installs.keys())
721 curr_path = []
722 sorted_installs = []
723
724 def SortFrom(cp):
725 """Traverses dependencies recursively, emitting nodes in reverse order."""
726 cpv, slot, _, _ = installs[cp]
727 if cpv in curr_path:
728 raise ValueError(
729 "Dependencies contain a cycle: %s -> %s"
730 % (" -> ".join(curr_path[curr_path.index(cpv) :]), cpv)
731 )
732 curr_path.append(cpv)
733 for rdep_cp, _ in self.binpkgs_db[cp][slot].rdeps:
734 if rdep_cp in not_visited:
735 not_visited.remove(rdep_cp)
736 SortFrom(rdep_cp)
737
738 sorted_installs.append(cpv)
739 curr_path.pop()
740
741 # So long as there's more packages, keep expanding dependency paths.
742 while not_visited:
743 SortFrom(not_visited.pop())
744
745 return sorted_installs
746
747 def _EnqListedPkg(self, pkg):
748 """Finds and enqueues a listed package."""
749 cp, slot = self._FindPackage(pkg)
750 if cp not in self.binpkgs_db:
751 raise self.BintreeError(
752 "Package %s not found in binpkgs tree" % pkg
753 )
754 self._EnqDep((cp, slot), True, False)
755
756 def _EnqInstalledPkgs(self):
757 """Enqueues all available binary packages that are already installed."""
758 for cp, cp_slots in self.binpkgs_db.items():
759 target_cp_slots = self.target_db.get(cp)
760 if target_cp_slots:
761 for slot in cp_slots.keys():
762 if slot in target_cp_slots:
763 self._EnqDep((cp, slot), True, False)
764
765 def Run(
766 self,
767 device,
768 root,
769 listed_pkgs,
770 update,
771 process_rdeps,
772 process_rev_rdeps,
773 ):
774 """Computes the list of packages that need to be installed on a target.
775
776 Args:
777 device: Target handler object.
778 root: Package installation root.
779 listed_pkgs: Package names/files listed by the user.
780 update: Whether to read the target's installed package database.
781 process_rdeps: Whether to trace forward dependencies.
782 process_rev_rdeps: Whether to trace backward dependencies as well.
783
784 Returns:
785 A tuple (sorted, listed, num_updates, install_attrs) where |sorted| is a
786 list of package CPVs (string) to install on the target in an order that
787 satisfies their inter-dependencies, |listed| the subset that was
788 requested by the user, and |num_updates| the number of packages being
789 installed over preexisting versions. Note that installation order should
790 be reversed for removal, |install_attrs| is a dictionary mapping a package
791 CPV (string) to some of its extracted environment attributes.
792 """
793 if process_rev_rdeps and not process_rdeps:
794 raise ValueError(
795 "Must processing forward deps when processing rev deps"
796 )
797 if process_rdeps and not update:
798 raise ValueError(
799 "Must check installed packages when processing deps"
800 )
801
802 if update:
803 logging.info("Initializing target intalled packages database...")
804 self._InitTargetVarDB(
805 device, root, process_rdeps, process_rev_rdeps
806 )
807
808 logging.info("Initializing binary packages database...")
809 self._InitBinpkgDB(process_rdeps)
810
811 logging.info("Finding listed package(s)...")
812 self._InitDepQueue()
813 for pkg in listed_pkgs:
814 if pkg == "@installed":
815 if not update:
816 raise ValueError(
817 "Must check installed packages when updating all of them."
818 )
819 self._EnqInstalledPkgs()
820 else:
821 self._EnqListedPkg(pkg)
822
823 logging.info("Computing set of packages to install...")
824 installs = self._ComputeInstalls(process_rdeps, process_rev_rdeps)
825
826 num_updates = 0
827 listed_installs = []
828 for cpv, _, listed, isupdate in installs.values():
829 if listed:
830 listed_installs.append(cpv)
831 if isupdate:
832 num_updates += 1
833
834 logging.info(
835 "Processed %d package(s), %d will be installed, %d are "
836 "updating existing packages",
837 len(self.seen),
838 len(installs),
839 num_updates,
840 )
841
842 sorted_installs = self._SortInstalls(installs)
843
844 install_attrs = {}
845 for pkg in sorted_installs:
846 pkg_path = os.path.join(root, portage_util.VDB_PATH, pkg)
847 dlc_id, dlc_package = _GetDLCInfo(device, pkg_path, from_dut=True)
848 install_attrs[pkg] = {}
849 if dlc_id and dlc_package:
850 install_attrs[pkg][_DLC_ID] = dlc_id
851
852 return sorted_installs, listed_installs, num_updates, install_attrs
David Pursell9476bf42015-03-30 13:34:27 -0700853
854
Mike Frysinger63d35512021-01-26 23:16:13 -0500855def _Emerge(device, pkg_paths, root, extra_args=None):
Alex Klein1699fab2022-09-08 08:46:06 -0600856 """Copies |pkg_paths| to |device| and emerges them.
David Pursell9476bf42015-03-30 13:34:27 -0700857
Alex Klein1699fab2022-09-08 08:46:06 -0600858 Args:
859 device: A ChromiumOSDevice object.
860 pkg_paths: (Local) paths to binary packages.
861 root: Package installation root path.
862 extra_args: Extra arguments to pass to emerge.
David Pursell9476bf42015-03-30 13:34:27 -0700863
Alex Klein1699fab2022-09-08 08:46:06 -0600864 Raises:
865 DeployError: Unrecoverable error during emerge.
866 """
Mike Frysinger63d35512021-01-26 23:16:13 -0500867
Alex Klein1699fab2022-09-08 08:46:06 -0600868 def path_to_name(pkg_path):
869 return os.path.basename(pkg_path)
Mike Frysinger63d35512021-01-26 23:16:13 -0500870
Alex Klein1699fab2022-09-08 08:46:06 -0600871 def path_to_category(pkg_path):
872 return os.path.basename(os.path.dirname(pkg_path))
David Pursell9476bf42015-03-30 13:34:27 -0700873
Alex Klein1699fab2022-09-08 08:46:06 -0600874 pkg_names = ", ".join(path_to_name(x) for x in pkg_paths)
David Pursell9476bf42015-03-30 13:34:27 -0700875
Alex Klein1699fab2022-09-08 08:46:06 -0600876 pkgroot = os.path.join(device.work_dir, "packages")
877 portage_tmpdir = os.path.join(device.work_dir, "portage-tmp")
878 # Clean out the dirs first if we had a previous emerge on the device so as to
879 # free up space for this emerge. The last emerge gets implicitly cleaned up
880 # when the device connection deletes its work_dir.
881 device.run(
882 f"cd {device.work_dir} && "
883 f"rm -rf packages portage-tmp && "
884 f"mkdir -p portage-tmp packages && "
885 f"cd packages && "
886 f'mkdir -p {" ".join(set(path_to_category(x) for x in pkg_paths))}',
887 shell=True,
888 remote_sudo=True,
889 )
Mike Frysinger63d35512021-01-26 23:16:13 -0500890
Alex Klein1699fab2022-09-08 08:46:06 -0600891 logging.info("Use portage temp dir %s", portage_tmpdir)
David Pursell9476bf42015-03-30 13:34:27 -0700892
Mike Frysinger63d35512021-01-26 23:16:13 -0500893 # This message is read by BrilloDeployOperation.
Alex Klein1699fab2022-09-08 08:46:06 -0600894 logging.notice("Copying binpkgs to device.")
895 for pkg_path in pkg_paths:
896 pkg_name = path_to_name(pkg_path)
897 logging.info("Copying %s", pkg_name)
898 pkg_dir = os.path.join(pkgroot, path_to_category(pkg_path))
899 device.CopyToDevice(
900 pkg_path, pkg_dir, mode="rsync", remote_sudo=True, compress=False
901 )
902
903 # This message is read by BrilloDeployOperation.
904 logging.notice("Installing: %s", pkg_names)
905
906 # We set PORTAGE_CONFIGROOT to '/usr/local' because by default all
907 # chromeos-base packages will be skipped due to the configuration
908 # in /etc/protage/make.profile/package.provided. However, there is
909 # a known bug that /usr/local/etc/portage is not setup properly
910 # (crbug.com/312041). This does not affect `cros deploy` because
911 # we do not use the preset PKGDIR.
912 extra_env = {
913 "FEATURES": "-sandbox",
914 "PKGDIR": pkgroot,
915 "PORTAGE_CONFIGROOT": "/usr/local",
916 "PORTAGE_TMPDIR": portage_tmpdir,
917 "PORTDIR": device.work_dir,
918 "CONFIG_PROTECT": "-*",
919 }
920
921 # --ignore-built-slot-operator-deps because we don't rebuild everything.
922 # It can cause errors, but that's expected with cros deploy since it's just a
923 # best effort to prevent developers avoid rebuilding an image every time.
924 cmd = [
925 "emerge",
926 "--usepkg",
927 "--ignore-built-slot-operator-deps=y",
928 "--root",
929 root,
930 ] + [os.path.join(pkgroot, *x.split("/")[-2:]) for x in pkg_paths]
931 if extra_args:
932 cmd.append(extra_args)
933
934 logging.warning(
935 "Ignoring slot dependencies! This may break things! e.g. "
936 "packages built against the old version may not be able to "
937 "load the new .so. This is expected, and you will just need "
938 "to build and flash a new image if you have problems."
939 )
940 try:
941 result = device.run(
942 cmd,
943 extra_env=extra_env,
944 remote_sudo=True,
945 capture_output=True,
946 debug_level=logging.INFO,
947 )
948
949 pattern = (
950 "A requested package will not be merged because "
951 "it is listed in package.provided"
952 )
953 output = result.stderr.replace("\n", " ").replace("\r", "")
954 if pattern in output:
955 error = (
956 "Package failed to emerge: %s\n"
957 "Remove %s from /etc/portage/make.profile/"
958 "package.provided/chromeos-base.packages\n"
959 "(also see crbug.com/920140 for more context)\n"
960 % (pattern, pkg_name)
961 )
962 cros_build_lib.Die(error)
963 except Exception:
964 logging.error("Failed to emerge packages %s", pkg_names)
965 raise
966 else:
967 # This message is read by BrilloDeployOperation.
968 logging.notice("Packages have been installed.")
David Pursell9476bf42015-03-30 13:34:27 -0700969
970
Qijiang Fand5958192019-07-26 12:32:36 +0900971def _RestoreSELinuxContext(device, pkgpath, root):
Alex Klein1699fab2022-09-08 08:46:06 -0600972 """Restore SELinux context for files in a given package.
Qijiang Fan8a945032019-04-25 20:53:29 +0900973
Alex Klein1699fab2022-09-08 08:46:06 -0600974 This reads the tarball from pkgpath, and calls restorecon on device to
975 restore SELinux context for files listed in the tarball, assuming those files
976 are installed to /
Qijiang Fan8a945032019-04-25 20:53:29 +0900977
Alex Klein1699fab2022-09-08 08:46:06 -0600978 Args:
979 device: a ChromiumOSDevice object
980 pkgpath: path to tarball
981 root: Package installation root path.
982 """
983 pkgroot = os.path.join(device.work_dir, "packages")
984 pkg_dirname = os.path.basename(os.path.dirname(pkgpath))
985 pkgpath_device = os.path.join(
986 pkgroot, pkg_dirname, os.path.basename(pkgpath)
987 )
988 # Testing shows restorecon splits on newlines instead of spaces.
989 device.run(
990 [
991 "cd",
992 root,
993 "&&",
994 "tar",
995 "tf",
996 pkgpath_device,
997 "|",
998 "restorecon",
999 "-i",
1000 "-f",
1001 "-",
1002 ],
1003 remote_sudo=True,
1004 )
Qijiang Fan352d0eb2019-02-25 13:10:08 +09001005
1006
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001007def _GetPackagesByCPV(cpvs, strip, sysroot):
Alex Klein1699fab2022-09-08 08:46:06 -06001008 """Returns paths to binary packages corresponding to |cpvs|.
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001009
Alex Klein1699fab2022-09-08 08:46:06 -06001010 Args:
1011 cpvs: List of CPV components given by package_info.SplitCPV().
1012 strip: True to run strip_package.
1013 sysroot: Sysroot path.
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001014
Alex Klein1699fab2022-09-08 08:46:06 -06001015 Returns:
1016 List of paths corresponding to |cpvs|.
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001017
Alex Klein1699fab2022-09-08 08:46:06 -06001018 Raises:
1019 DeployError: If a package is missing.
1020 """
1021 packages_dir = None
1022 if strip:
1023 try:
1024 cros_build_lib.run(
1025 [
1026 os.path.join(
1027 constants.CHROMITE_SCRIPTS_DIR, "strip_package"
1028 ),
1029 "--sysroot",
1030 sysroot,
1031 ]
1032 + [cpv.cpf for cpv in cpvs]
1033 )
1034 packages_dir = _STRIPPED_PACKAGES_DIR
1035 except cros_build_lib.RunCommandError:
1036 logging.error(
1037 "Cannot strip packages %s", " ".join([str(cpv) for cpv in cpvs])
1038 )
1039 raise
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001040
Alex Klein1699fab2022-09-08 08:46:06 -06001041 paths = []
1042 for cpv in cpvs:
1043 path = portage_util.GetBinaryPackagePath(
1044 cpv.category,
1045 cpv.package,
1046 cpv.version,
1047 sysroot=sysroot,
1048 packages_dir=packages_dir,
1049 )
1050 if not path:
1051 raise DeployError("Missing package %s." % cpv)
1052 paths.append(path)
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001053
Alex Klein1699fab2022-09-08 08:46:06 -06001054 return paths
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001055
1056
1057def _GetPackagesPaths(pkgs, strip, sysroot):
Alex Klein1699fab2022-09-08 08:46:06 -06001058 """Returns paths to binary |pkgs|.
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001059
Alex Klein1699fab2022-09-08 08:46:06 -06001060 Args:
1061 pkgs: List of package CPVs string.
1062 strip: Whether or not to run strip_package for CPV packages.
1063 sysroot: The sysroot path.
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001064
Alex Klein1699fab2022-09-08 08:46:06 -06001065 Returns:
1066 List of paths corresponding to |pkgs|.
1067 """
1068 cpvs = [package_info.SplitCPV(p) for p in pkgs]
1069 return _GetPackagesByCPV(cpvs, strip, sysroot)
Gilad Arnold0e1b1da2015-06-10 06:41:05 -07001070
1071
Mike Frysinger22bb5502021-01-29 13:05:46 -05001072def _Unmerge(device, pkgs, root):
Alex Klein1699fab2022-09-08 08:46:06 -06001073 """Unmerges |pkgs| on |device|.
David Pursell9476bf42015-03-30 13:34:27 -07001074
Alex Klein1699fab2022-09-08 08:46:06 -06001075 Args:
1076 device: A RemoteDevice object.
1077 pkgs: Package names.
1078 root: Package installation root path.
1079 """
1080 pkg_names = ", ".join(os.path.basename(x) for x in pkgs)
Mike Frysinger22bb5502021-01-29 13:05:46 -05001081 # This message is read by BrilloDeployOperation.
Alex Klein1699fab2022-09-08 08:46:06 -06001082 logging.notice("Unmerging %s.", pkg_names)
1083 cmd = ["qmerge", "--yes"]
1084 # Check if qmerge is available on the device. If not, use emerge.
1085 if device.run(["qmerge", "--version"], check=False).returncode != 0:
1086 cmd = ["emerge"]
1087
1088 cmd += ["--unmerge", "--root", root]
1089 cmd.extend("f={x}" for x in pkgs)
1090 try:
1091 # Always showing the emerge output for clarity.
1092 device.run(
1093 cmd,
1094 capture_output=False,
1095 remote_sudo=True,
1096 debug_level=logging.INFO,
1097 )
1098 except Exception:
1099 logging.error("Failed to unmerge packages %s", pkg_names)
1100 raise
1101 else:
1102 # This message is read by BrilloDeployOperation.
1103 logging.notice("Packages have been uninstalled.")
David Pursell9476bf42015-03-30 13:34:27 -07001104
1105
1106def _ConfirmDeploy(num_updates):
Alex Klein1699fab2022-09-08 08:46:06 -06001107 """Returns whether we can continue deployment."""
1108 if num_updates > _MAX_UPDATES_NUM:
1109 logging.warning(_MAX_UPDATES_WARNING)
1110 return cros_build_lib.BooleanPrompt(default=False)
David Pursell9476bf42015-03-30 13:34:27 -07001111
Alex Klein1699fab2022-09-08 08:46:06 -06001112 return True
David Pursell9476bf42015-03-30 13:34:27 -07001113
1114
Andrew06a5f812020-01-23 08:08:32 -08001115def _EmergePackages(pkgs, device, strip, sysroot, root, board, emerge_args):
Alex Klein1699fab2022-09-08 08:46:06 -06001116 """Call _Emerge for each package in pkgs."""
Ben Pastene5f03b052019-08-12 18:03:24 -07001117 if device.IsSELinuxAvailable():
Alex Klein1699fab2022-09-08 08:46:06 -06001118 enforced = device.IsSELinuxEnforced()
1119 if enforced:
1120 device.run(["setenforce", "0"])
1121 else:
1122 enforced = False
Andrewc7e1c6b2020-02-27 16:03:53 -08001123
Alex Klein1699fab2022-09-08 08:46:06 -06001124 dlc_deployed = False
1125 # This message is read by BrilloDeployOperation.
1126 logging.info("Preparing local packages for transfer.")
1127 pkg_paths = _GetPackagesPaths(pkgs, strip, sysroot)
1128 # Install all the packages in one pass so inter-package blockers work.
1129 _Emerge(device, pkg_paths, root, extra_args=emerge_args)
1130 logging.info("Updating SELinux settings & DLC images.")
1131 for pkg_path in pkg_paths:
1132 if device.IsSELinuxAvailable():
1133 _RestoreSELinuxContext(device, pkg_path, root)
Mike Frysinger5f4c2742021-02-08 14:37:23 -05001134
Alex Klein1699fab2022-09-08 08:46:06 -06001135 dlc_id, dlc_package = _GetDLCInfo(device, pkg_path, from_dut=False)
1136 if dlc_id and dlc_package:
1137 _DeployDLCImage(device, sysroot, board, dlc_id, dlc_package)
1138 dlc_deployed = True
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001139
Alex Klein1699fab2022-09-08 08:46:06 -06001140 if dlc_deployed:
1141 # Clean up empty directories created by emerging DLCs.
1142 device.run(
1143 [
1144 "test",
1145 "-d",
1146 "/build/rootfs",
1147 "&&",
1148 "rmdir",
1149 "--ignore-fail-on-non-empty",
1150 "/build/rootfs",
1151 "/build",
1152 ],
1153 check=False,
1154 )
Mike Frysinger4eb5f4e2021-01-26 21:48:37 -05001155
Alex Klein1699fab2022-09-08 08:46:06 -06001156 if enforced:
1157 device.run(["setenforce", "1"])
1158
1159 # Restart dlcservice so it picks up the newly installed DLC modules (in case
1160 # we installed new DLC images).
1161 if dlc_deployed:
1162 device.run(["restart", "dlcservice"])
Ralph Nathane01ccf12015-04-16 10:40:32 -07001163
1164
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001165def _UnmergePackages(pkgs, device, root, pkgs_attrs):
Alex Klein1699fab2022-09-08 08:46:06 -06001166 """Call _Unmege for each package in pkgs."""
1167 dlc_uninstalled = False
1168 _Unmerge(device, pkgs, root)
1169 logging.info("Cleaning up DLC images.")
1170 for pkg in pkgs:
1171 if _UninstallDLCImage(device, pkgs_attrs[pkg]):
1172 dlc_uninstalled = True
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001173
Alex Klein1699fab2022-09-08 08:46:06 -06001174 # Restart dlcservice so it picks up the uninstalled DLC modules (in case we
1175 # uninstalled DLC images).
1176 if dlc_uninstalled:
1177 device.run(["restart", "dlcservice"])
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001178
1179
1180def _UninstallDLCImage(device, pkg_attrs):
Alex Klein1699fab2022-09-08 08:46:06 -06001181 """Uninstall a DLC image."""
1182 if _DLC_ID in pkg_attrs:
1183 dlc_id = pkg_attrs[_DLC_ID]
1184 logging.notice("Uninstalling DLC image for %s", dlc_id)
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001185
Alex Klein1699fab2022-09-08 08:46:06 -06001186 device.run(["dlcservice_util", "--uninstall", "--id=%s" % dlc_id])
1187 return True
1188 else:
1189 logging.debug("DLC_ID not found in package")
1190 return False
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001191
1192
Andrew06a5f812020-01-23 08:08:32 -08001193def _DeployDLCImage(device, sysroot, board, dlc_id, dlc_package):
Alex Klein1699fab2022-09-08 08:46:06 -06001194 """Deploy (install and mount) a DLC image.
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001195
Alex Klein1699fab2022-09-08 08:46:06 -06001196 Args:
1197 device: A device object.
1198 sysroot: The sysroot path.
1199 board: Board to use.
1200 dlc_id: The DLC ID.
1201 dlc_package: The DLC package name.
1202 """
1203 # Requires `sudo_rm` because installations of files are running with sudo.
1204 with osutils.TempDir(sudo_rm=True) as tempdir:
1205 temp_rootfs = Path(tempdir)
1206 # Build the DLC image if the image is outdated or doesn't exist.
1207 dlc_lib.InstallDlcImages(
1208 sysroot=sysroot, rootfs=temp_rootfs, dlc_id=dlc_id, board=board
1209 )
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001210
Alex Klein1699fab2022-09-08 08:46:06 -06001211 logging.debug("Uninstall DLC %s if it is installed.", dlc_id)
1212 try:
1213 device.run(["dlcservice_util", "--uninstall", "--id=%s" % dlc_id])
1214 except cros_build_lib.RunCommandError as e:
1215 logging.info(
1216 "Failed to uninstall DLC:%s. Continue anyway.", e.stderr
1217 )
1218 except Exception:
1219 logging.error("Failed to uninstall DLC.")
1220 raise
Andrewc7e1c6b2020-02-27 16:03:53 -08001221
Alex Klein1699fab2022-09-08 08:46:06 -06001222 # TODO(andrewlassalle): Copy the DLC image to the preload location instead
1223 # of to dlc_a and dlc_b, and let dlcserive install the images to their final
1224 # location.
1225 logging.notice("Deploy the DLC image for %s", dlc_id)
1226 dlc_img_path_src = os.path.join(
1227 sysroot,
1228 dlc_lib.DLC_BUILD_DIR,
1229 dlc_id,
1230 dlc_package,
1231 dlc_lib.DLC_IMAGE,
1232 )
1233 dlc_img_path = os.path.join(_DLC_INSTALL_ROOT, dlc_id, dlc_package)
1234 dlc_img_path_a = os.path.join(dlc_img_path, "dlc_a")
1235 dlc_img_path_b = os.path.join(dlc_img_path, "dlc_b")
1236 # Create directories for DLC images.
1237 device.run(["mkdir", "-p", dlc_img_path_a, dlc_img_path_b])
1238 # Copy images to the destination directories.
1239 device.CopyToDevice(
1240 dlc_img_path_src,
1241 os.path.join(dlc_img_path_a, dlc_lib.DLC_IMAGE),
1242 mode="rsync",
1243 )
1244 device.run(
1245 [
1246 "cp",
1247 os.path.join(dlc_img_path_a, dlc_lib.DLC_IMAGE),
1248 os.path.join(dlc_img_path_b, dlc_lib.DLC_IMAGE),
1249 ]
1250 )
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001251
Alex Klein1699fab2022-09-08 08:46:06 -06001252 # Set the proper perms and ownership so dlcservice can access the image.
1253 device.run(["chmod", "-R", "u+rwX,go+rX,go-w", _DLC_INSTALL_ROOT])
1254 device.run(["chown", "-R", "dlcservice:dlcservice", _DLC_INSTALL_ROOT])
Jae Hoon Kim2376e142022-09-03 00:18:58 +00001255
Alex Klein1699fab2022-09-08 08:46:06 -06001256 # Copy metadata to device.
1257 dest_meta_dir = Path("/") / dlc_lib.DLC_META_DIR / dlc_id / dlc_package
1258 device.run(["mkdir", "-p", dest_meta_dir])
1259 src_meta_dir = os.path.join(
1260 sysroot,
1261 dlc_lib.DLC_BUILD_DIR,
1262 dlc_id,
1263 dlc_package,
1264 dlc_lib.DLC_TMP_META_DIR,
1265 )
1266 device.CopyToDevice(
1267 src_meta_dir + "/",
1268 dest_meta_dir,
1269 mode="rsync",
1270 recursive=True,
1271 remote_sudo=True,
1272 )
Jae Hoon Kim2376e142022-09-03 00:18:58 +00001273
Alex Klein1699fab2022-09-08 08:46:06 -06001274 # TODO(kimjae): Make this generic so it recomputes all the DLCs + copies
1275 # over a fresh list of dm-verity digests instead of appending and keeping
1276 # the stale digests when developers are testing.
Jae Hoon Kim2376e142022-09-03 00:18:58 +00001277
Alex Klein1699fab2022-09-08 08:46:06 -06001278 # Copy the LoadPin dm-verity digests to device.
1279 loadpin = dlc_lib.DLC_LOADPIN_TRUSTED_VERITY_DIGESTS
1280 dst_loadpin = Path("/") / dlc_lib.DLC_META_DIR / loadpin
1281 src_loadpin = temp_rootfs / dlc_lib.DLC_META_DIR / loadpin
1282 if src_loadpin.exists():
1283 digests = set(osutils.ReadFile(src_loadpin).split())
1284 try:
1285 digests.update(device.CatFile(dst_loadpin).split())
1286 except remote_access.CatFileError:
1287 pass
Jae Hoon Kim2376e142022-09-03 00:18:58 +00001288
Alex Klein1699fab2022-09-08 08:46:06 -06001289 with tempfile.NamedTemporaryFile(dir=temp_rootfs) as f:
1290 osutils.WriteFile(f.name, "\n".join(digests))
1291 device.CopyToDevice(
1292 f.name, dst_loadpin, mode="rsync", remote_sudo=True
1293 )
Andrew67b5fa72020-02-05 14:14:48 -08001294
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001295
1296def _GetDLCInfo(device, pkg_path, from_dut):
Alex Klein1699fab2022-09-08 08:46:06 -06001297 """Returns information of a DLC given its package path.
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001298
Alex Klein1699fab2022-09-08 08:46:06 -06001299 Args:
1300 device: commandline.Device object; None to use the default device.
1301 pkg_path: path to the package.
1302 from_dut: True if extracting DLC info from DUT, False if extracting DLC
1303 info from host.
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001304
Alex Klein1699fab2022-09-08 08:46:06 -06001305 Returns:
1306 A tuple (dlc_id, dlc_package).
1307 """
1308 environment_content = ""
1309 if from_dut:
1310 # On DUT, |pkg_path| is the directory which contains environment file.
1311 environment_path = os.path.join(pkg_path, _ENVIRONMENT_FILENAME)
1312 try:
1313 environment_data = device.CatFile(
1314 environment_path, max_size=None, encoding=None
1315 )
1316 except remote_access.CatFileError:
1317 # The package is not installed on DUT yet. Skip extracting info.
1318 return None, None
1319 else:
1320 # On host, pkg_path is tbz2 file which contains environment file.
1321 # Extract the metadata of the package file.
1322 data = portage.xpak.tbz2(pkg_path).get_data()
1323 environment_data = data[_ENVIRONMENT_FILENAME.encode("utf-8")]
1324
1325 # Extract the environment metadata.
1326 environment_content = bz2.decompress(environment_data)
1327
1328 with tempfile.NamedTemporaryFile() as f:
1329 # Dumps content into a file so we can use osutils.SourceEnvironment.
1330 path = os.path.realpath(f.name)
1331 osutils.WriteFile(path, environment_content, mode="wb")
1332 content = osutils.SourceEnvironment(
1333 path, (_DLC_ID, _DLC_PACKAGE, _DLC_ENABLED)
1334 )
1335
1336 dlc_enabled = content.get(_DLC_ENABLED)
1337 if dlc_enabled is not None and (
1338 dlc_enabled is False or str(dlc_enabled) == "false"
1339 ):
1340 logging.info("Installing DLC in rootfs.")
1341 return None, None
1342 return content.get(_DLC_ID), content.get(_DLC_PACKAGE)
1343
1344
1345def Deploy(
1346 device,
1347 packages,
1348 board=None,
1349 emerge=True,
1350 update=False,
1351 deep=False,
1352 deep_rev=False,
1353 clean_binpkg=True,
1354 root="/",
1355 strip=True,
1356 emerge_args=None,
1357 ssh_private_key=None,
1358 ping=True,
1359 force=False,
1360 dry_run=False,
1361):
1362 """Deploys packages to a device.
1363
1364 Args:
1365 device: commandline.Device object; None to use the default device.
1366 packages: List of packages (strings) to deploy to device.
1367 board: Board to use; None to automatically detect.
1368 emerge: True to emerge package, False to unmerge.
1369 update: Check installed version on device.
1370 deep: Install dependencies also. Implies |update|.
1371 deep_rev: Install reverse dependencies. Implies |deep|.
1372 clean_binpkg: Clean outdated binary packages.
1373 root: Package installation root path.
1374 strip: Run strip_package to filter out preset paths in the package.
1375 emerge_args: Extra arguments to pass to emerge.
1376 ssh_private_key: Path to an SSH private key file; None to use test keys.
1377 ping: True to ping the device before trying to connect.
1378 force: Ignore confidence checks and prompts.
1379 dry_run: Print deployment plan but do not deploy anything.
1380
1381 Raises:
1382 ValueError: Invalid parameter or parameter combination.
1383 DeployError: Unrecoverable failure during deploy.
1384 """
1385 if deep_rev:
1386 deep = True
1387 if deep:
1388 update = True
1389
1390 if not packages:
1391 raise DeployError("No packages provided, nothing to deploy.")
1392
1393 if update and not emerge:
1394 raise ValueError("Cannot update and unmerge.")
1395
1396 if device:
1397 hostname, username, port = device.hostname, device.username, device.port
1398 else:
1399 hostname, username, port = None, None, None
1400
1401 lsb_release = None
1402 sysroot = None
Mike Frysingeracd06cd2021-01-27 13:33:52 -05001403 try:
Alex Klein1699fab2022-09-08 08:46:06 -06001404 # Somewhat confusing to clobber, but here we are.
1405 # pylint: disable=redefined-argument-from-local
1406 with remote_access.ChromiumOSDeviceHandler(
1407 hostname,
1408 port=port,
1409 username=username,
1410 private_key=ssh_private_key,
1411 base_dir=_DEVICE_BASE_DIR,
1412 ping=ping,
1413 ) as device:
1414 lsb_release = device.lsb_release
Mike Frysingeracd06cd2021-01-27 13:33:52 -05001415
Alex Klein1699fab2022-09-08 08:46:06 -06001416 board = cros_build_lib.GetBoard(
1417 device_board=device.board, override_board=board
1418 )
1419 if not force and board != device.board:
1420 raise DeployError(
1421 "Device (%s) is incompatible with board %s. Use "
1422 "--force to deploy anyway." % (device.board, board)
1423 )
Xiaochu Liu2726e7c2019-07-18 10:28:10 -07001424
Alex Klein1699fab2022-09-08 08:46:06 -06001425 sysroot = build_target_lib.get_default_sysroot_path(board)
Andrew67b5fa72020-02-05 14:14:48 -08001426
Alex Klein1699fab2022-09-08 08:46:06 -06001427 # Don't bother trying to clean for unmerges. We won't use the local db,
1428 # and it just slows things down for the user.
1429 if emerge and clean_binpkg:
1430 logging.notice(
1431 "Cleaning outdated binary packages from %s", sysroot
1432 )
1433 portage_util.CleanOutdatedBinaryPackages(sysroot)
Ralph Nathane01ccf12015-04-16 10:40:32 -07001434
Alex Klein1699fab2022-09-08 08:46:06 -06001435 # Remount rootfs as writable if necessary.
1436 if not device.MountRootfsReadWrite():
1437 raise DeployError(
1438 "Cannot remount rootfs as read-write. Exiting."
1439 )
Ralph Nathane01ccf12015-04-16 10:40:32 -07001440
Alex Klein1699fab2022-09-08 08:46:06 -06001441 # Obtain list of packages to upgrade/remove.
1442 pkg_scanner = _InstallPackageScanner(sysroot)
1443 pkgs, listed, num_updates, pkgs_attrs = pkg_scanner.Run(
1444 device, root, packages, update, deep, deep_rev
1445 )
1446 if emerge:
1447 action_str = "emerge"
1448 else:
1449 pkgs.reverse()
1450 action_str = "unmerge"
David Pursell9476bf42015-03-30 13:34:27 -07001451
Alex Klein1699fab2022-09-08 08:46:06 -06001452 if not pkgs:
1453 logging.notice("No packages to %s", action_str)
1454 return
David Pursell9476bf42015-03-30 13:34:27 -07001455
Alex Klein1699fab2022-09-08 08:46:06 -06001456 # Warn when the user installs & didn't `cros workon start`.
1457 if emerge:
1458 all_workon = workon_helper.WorkonHelper(sysroot).ListAtoms(
1459 use_all=True
1460 )
1461 worked_on_cps = workon_helper.WorkonHelper(sysroot).ListAtoms()
1462 for package in listed:
1463 cp = package_info.SplitCPV(package).cp
1464 if cp in all_workon and cp not in worked_on_cps:
1465 logging.warning(
1466 "Are you intentionally deploying unmodified packages, or did "
1467 "you forget to run `cros workon --board=$BOARD start %s`?",
1468 cp,
1469 )
David Pursell9476bf42015-03-30 13:34:27 -07001470
Alex Klein1699fab2022-09-08 08:46:06 -06001471 logging.notice("These are the packages to %s:", action_str)
1472 for i, pkg in enumerate(pkgs):
1473 logging.notice(
1474 "%s %d) %s", "*" if pkg in listed else " ", i + 1, pkg
1475 )
Gilad Arnolda0a98062015-07-07 08:34:27 -07001476
Alex Klein1699fab2022-09-08 08:46:06 -06001477 if dry_run or not _ConfirmDeploy(num_updates):
1478 return
David Pursell9476bf42015-03-30 13:34:27 -07001479
Alex Klein1699fab2022-09-08 08:46:06 -06001480 # Select function (emerge or unmerge) and bind args.
1481 if emerge:
1482 func = functools.partial(
1483 _EmergePackages,
1484 pkgs,
1485 device,
1486 strip,
1487 sysroot,
1488 root,
1489 board,
1490 emerge_args,
1491 )
1492 else:
1493 func = functools.partial(
1494 _UnmergePackages, pkgs, device, root, pkgs_attrs
1495 )
David Pursell2e773382015-04-03 14:30:47 -07001496
Alex Klein1699fab2022-09-08 08:46:06 -06001497 # Call the function with the progress bar or with normal output.
1498 if command.UseProgressBar():
1499 op = BrilloDeployOperation(emerge)
1500 op.Run(func, log_level=logging.DEBUG)
1501 else:
1502 func()
David Pursell9476bf42015-03-30 13:34:27 -07001503
Alex Klein1699fab2022-09-08 08:46:06 -06001504 if device.IsSELinuxAvailable():
1505 if sum(x.count("selinux-policy") for x in pkgs):
1506 logging.warning(
1507 "Deploying SELinux policy will not take effect until reboot. "
1508 "SELinux policy is loaded by init. Also, changing the security "
1509 "contexts (labels) of a file will require building a new image "
1510 "and flashing the image onto the device."
1511 )
Bertrand SIMONNET60c94492015-04-30 17:46:28 -07001512
Alex Klein1699fab2022-09-08 08:46:06 -06001513 # This message is read by BrilloDeployOperation.
Mike Frysinger5c7b9512020-12-04 02:30:56 -05001514 logging.warning(
Alex Klein1699fab2022-09-08 08:46:06 -06001515 "Please restart any updated services on the device, "
1516 "or just reboot it."
1517 )
1518 except Exception:
1519 if lsb_release:
1520 lsb_entries = sorted(lsb_release.items())
1521 logging.info(
1522 "Following are the LSB version details of the device:\n%s",
1523 "\n".join("%s=%s" % (k, v) for k, v in lsb_entries),
1524 )
1525 raise