Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2019 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """Field handler classes. |
| 7 | |
| 8 | The field handlers are meant to parse information from or do some other generic |
| 9 | action for a specific field type for the build_api script. |
| 10 | """ |
| 11 | |
| 12 | from __future__ import print_function |
| 13 | |
| 14 | import contextlib |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 15 | import functools |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 16 | import os |
| 17 | import shutil |
| 18 | |
Mike Frysinger | 849d640 | 2019-10-17 00:14:16 -0400 | [diff] [blame] | 19 | from google.protobuf import message as protobuf_message |
| 20 | |
Alex Klein | 38c7d9e | 2019-05-08 09:31:19 -0600 | [diff] [blame] | 21 | from chromite.api.controller import controller_util |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 22 | from chromite.api.gen.chromiumos import common_pb2 |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 23 | from chromite.lib import cros_logging as logging |
| 24 | from chromite.lib import osutils |
| 25 | |
| 26 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 27 | class Error(Exception): |
| 28 | """Base error class for the module.""" |
| 29 | |
| 30 | |
| 31 | class InvalidResultPathError(Error): |
| 32 | """Result path is invalid.""" |
| 33 | |
| 34 | |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 35 | class ChrootHandler(object): |
| 36 | """Translate a Chroot message to chroot enter arguments and env.""" |
| 37 | |
Alex Klein | 915cce9 | 2019-12-17 14:19:50 -0700 | [diff] [blame] | 38 | def __init__(self, clear_field, parse_goma): |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 39 | self.clear_field = clear_field |
Alex Klein | 915cce9 | 2019-12-17 14:19:50 -0700 | [diff] [blame] | 40 | self.parse_goma = parse_goma |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 41 | |
| 42 | def handle(self, message): |
| 43 | """Parse a message for a chroot field.""" |
| 44 | # Find the Chroot field. Search for the field by type to prevent it being |
| 45 | # tied to a naming convention. |
| 46 | for descriptor in message.DESCRIPTOR.fields: |
| 47 | field = getattr(message, descriptor.name) |
| 48 | if isinstance(field, common_pb2.Chroot): |
| 49 | chroot = field |
| 50 | if self.clear_field: |
| 51 | message.ClearField(descriptor.name) |
| 52 | return self.parse_chroot(chroot) |
| 53 | |
| 54 | return None |
| 55 | |
| 56 | def parse_chroot(self, chroot_message): |
| 57 | """Parse a Chroot message instance.""" |
Alex Klein | 915cce9 | 2019-12-17 14:19:50 -0700 | [diff] [blame] | 58 | return controller_util.ParseChroot(chroot_message, |
| 59 | parse_goma=self.parse_goma) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 60 | |
| 61 | |
Alex Klein | 915cce9 | 2019-12-17 14:19:50 -0700 | [diff] [blame] | 62 | def handle_chroot(message, clear_field=True, parse_goma=True): |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 63 | """Find and parse the chroot field, returning the Chroot instance. |
| 64 | |
| 65 | Returns: |
| 66 | chroot_lib.Chroot |
| 67 | """ |
Alex Klein | 915cce9 | 2019-12-17 14:19:50 -0700 | [diff] [blame] | 68 | handler = ChrootHandler(clear_field, parse_goma) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 69 | chroot = handler.handle(message) |
| 70 | if chroot: |
| 71 | return chroot |
| 72 | |
| 73 | logging.warning('No chroot message found, falling back to defaults.') |
| 74 | return handler.parse_chroot(common_pb2.Chroot()) |
| 75 | |
| 76 | |
| 77 | class PathHandler(object): |
| 78 | """Handles copying a file or directory into or out of the chroot.""" |
| 79 | |
| 80 | INSIDE = common_pb2.Path.INSIDE |
| 81 | OUTSIDE = common_pb2.Path.OUTSIDE |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 82 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 83 | def __init__(self, field, destination, delete, prefix=None, reset=True): |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 84 | """Path handler initialization. |
| 85 | |
| 86 | Args: |
| 87 | field (common_pb2.Path): The Path message. |
| 88 | destination (str): The destination base path. |
| 89 | delete (bool): Whether the copied file(s) should be deleted on cleanup. |
| 90 | prefix (str|None): A path prefix to remove from the destination path |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 91 | when moving files inside the chroot, or to add to the source paths when |
| 92 | moving files out of the chroot. |
| 93 | reset (bool): Whether to reset the state on cleanup. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 94 | """ |
| 95 | assert isinstance(field, common_pb2.Path) |
| 96 | assert field.path |
| 97 | assert field.location |
| 98 | |
| 99 | self.field = field |
| 100 | self.destination = destination |
| 101 | self.prefix = prefix or '' |
| 102 | self.delete = delete |
| 103 | self.tempdir = None |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 104 | self.reset = reset |
| 105 | |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 106 | # For resetting the state. |
| 107 | self._transferred = False |
| 108 | self._original_message = common_pb2.Path() |
| 109 | self._original_message.CopyFrom(self.field) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 110 | |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 111 | def transfer(self, direction): |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 112 | """Copy the file or directory to its destination. |
| 113 | |
| 114 | Args: |
| 115 | direction (int): The direction files are being copied (into or out of |
| 116 | the chroot). Specifying the direction allows avoiding performing |
| 117 | unnecessary copies. |
| 118 | """ |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 119 | if self._transferred: |
| 120 | return |
| 121 | |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 122 | assert direction in [self.INSIDE, self.OUTSIDE] |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 123 | |
| 124 | if self.field.location == direction: |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 125 | # Already in the correct location, nothing to do. |
| 126 | return |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 127 | |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 128 | # Create a tempdir for the copied file if we're cleaning it up afterwords. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 129 | if self.delete: |
| 130 | self.tempdir = osutils.TempDir(base_dir=self.destination) |
| 131 | destination = self.tempdir.tempdir |
| 132 | else: |
| 133 | destination = self.destination |
| 134 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 135 | source = self.field.path |
| 136 | if direction == self.OUTSIDE and self.prefix: |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 137 | # When we're extracting files, we need /tmp/result to be |
| 138 | # /path/to/chroot/tmp/result. |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 139 | source = os.path.join(self.prefix, source.lstrip(os.sep)) |
| 140 | |
| 141 | if os.path.isfile(source): |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 142 | # File - use the old file name, just copy it into the destination. |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 143 | dest_path = os.path.join(destination, os.path.basename(source)) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 144 | copy_fn = shutil.copy |
| 145 | else: |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 146 | # Directory - just copy everything into the new location. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 147 | dest_path = destination |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 148 | copy_fn = functools.partial(osutils.CopyDirContents, allow_nonempty=True) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 149 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 150 | logging.debug('Copying %s to %s', source, dest_path) |
| 151 | copy_fn(source, dest_path) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 152 | |
| 153 | # Clean up the destination path for returning, if applicable. |
| 154 | return_path = dest_path |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 155 | if direction == self.INSIDE and return_path.startswith(self.prefix): |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 156 | return_path = return_path[len(self.prefix):] |
| 157 | |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 158 | self.field.path = return_path |
| 159 | self.field.location = direction |
| 160 | self._transferred = True |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 161 | |
| 162 | def cleanup(self): |
| 163 | if self.tempdir: |
| 164 | self.tempdir.Cleanup() |
| 165 | self.tempdir = None |
| 166 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 167 | if self.reset: |
| 168 | self.field.CopyFrom(self._original_message) |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 169 | |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 170 | |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 171 | class SyncedDirHandler(object): |
| 172 | """Handler for syncing directories across the chroot boundary.""" |
| 173 | |
| 174 | def __init__(self, field, destination, prefix): |
| 175 | self.field = field |
| 176 | self.prefix = prefix |
| 177 | |
| 178 | self.source = self.field.dir |
| 179 | if not self.source.endswith(os.sep): |
| 180 | self.source += os.sep |
| 181 | |
| 182 | self.destination = destination |
| 183 | if not self.destination.endswith(os.sep): |
| 184 | self.destination += os.sep |
| 185 | |
| 186 | # For resetting the message later. |
| 187 | self._original_message = common_pb2.SyncedDir() |
| 188 | self._original_message.CopyFrom(self.field) |
| 189 | |
| 190 | def _sync(self, src, dest): |
Alex Klein | 915cce9 | 2019-12-17 14:19:50 -0700 | [diff] [blame] | 191 | logging.info('Syncing %s to %s', src, dest) |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 192 | # TODO: This would probably be more efficient with rsync. |
| 193 | osutils.EmptyDir(dest) |
| 194 | osutils.CopyDirContents(src, dest) |
| 195 | |
| 196 | def sync_in(self): |
| 197 | """Sync files from the source directory to the destination directory.""" |
| 198 | self._sync(self.source, self.destination) |
| 199 | self.field.dir = '/%s' % os.path.relpath(self.destination, self.prefix) |
| 200 | |
| 201 | def sync_out(self): |
| 202 | """Sync files from the destination directory to the source directory.""" |
| 203 | self._sync(self.destination, self.source) |
| 204 | self.field.CopyFrom(self._original_message) |
| 205 | |
| 206 | |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 207 | @contextlib.contextmanager |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 208 | def copy_paths_in(message, destination, delete=True, prefix=None): |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 209 | """Context manager function to transfer and cleanup all Path messages. |
| 210 | |
| 211 | Args: |
| 212 | message (Message): A message whose Path messages should be transferred. |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 213 | destination (str): The base destination path. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 214 | delete (bool): Whether the file(s) should be deleted. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 215 | prefix (str|None): A prefix path to remove from the final destination path |
| 216 | in the Path message (i.e. remove the chroot path). |
| 217 | |
| 218 | Returns: |
| 219 | list[PathHandler]: The path handlers. |
| 220 | """ |
| 221 | assert destination |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 222 | |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 223 | handlers = _extract_handlers(message, destination, prefix, delete=delete, |
| 224 | reset=True) |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 225 | |
| 226 | for handler in handlers: |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 227 | handler.transfer(PathHandler.INSIDE) |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 228 | |
| 229 | try: |
| 230 | yield handlers |
| 231 | finally: |
| 232 | for handler in handlers: |
| 233 | handler.cleanup() |
| 234 | |
| 235 | |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 236 | @contextlib.contextmanager |
| 237 | def sync_dirs(message, destination, prefix): |
| 238 | """Context manager function to handle SyncedDir messages. |
| 239 | |
| 240 | The sync semantics are effectively: |
| 241 | rsync -r --del source/ destination/ |
| 242 | * The endpoint runs. * |
| 243 | rsync -r --del destination/ source/ |
| 244 | |
| 245 | Args: |
| 246 | message (Message): A message whose SyncedPath messages should be synced. |
| 247 | destination (str): The destination path. |
| 248 | prefix (str): A prefix path to remove from the final destination path |
| 249 | in the Path message (i.e. remove the chroot path). |
| 250 | |
| 251 | Returns: |
| 252 | list[SyncedDirHandler]: The handlers. |
| 253 | """ |
| 254 | assert destination |
| 255 | |
| 256 | handlers = _extract_handlers(message, destination, prefix=prefix, |
| 257 | delete=False, reset=True, |
| 258 | message_type=common_pb2.SyncedDir) |
| 259 | |
| 260 | for handler in handlers: |
| 261 | handler.sync_in() |
| 262 | |
| 263 | try: |
| 264 | yield handlers |
| 265 | finally: |
| 266 | for handler in handlers: |
| 267 | handler.sync_out() |
| 268 | |
| 269 | |
Alex Klein | aae4977 | 2019-07-26 10:20:50 -0600 | [diff] [blame] | 270 | def extract_results(request_message, response_message, chroot): |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 271 | """Transfer all response Path messages to the request's ResultPath. |
| 272 | |
| 273 | Args: |
| 274 | request_message (Message): The request message containing a ResultPath |
| 275 | message. |
| 276 | response_message (Message): The response message whose Path message(s) |
| 277 | are to be transferred. |
| 278 | chroot (chroot_lib.Chroot): The chroot the files are being copied out of. |
| 279 | """ |
| 280 | # Find the ResultPath. |
| 281 | for descriptor in request_message.DESCRIPTOR.fields: |
| 282 | field = getattr(request_message, descriptor.name) |
| 283 | if isinstance(field, common_pb2.ResultPath): |
| 284 | result_path_message = field |
| 285 | break |
| 286 | else: |
| 287 | # No ResultPath to handle. |
| 288 | return |
| 289 | |
| 290 | destination = result_path_message.path.path |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 291 | handlers = _extract_handlers(response_message, destination, chroot.path, |
| 292 | delete=False, reset=False) |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 293 | |
| 294 | for handler in handlers: |
| 295 | handler.transfer(PathHandler.OUTSIDE) |
| 296 | handler.cleanup() |
| 297 | |
| 298 | |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 299 | def _extract_handlers(message, destination, prefix, delete=False, reset=False, |
| 300 | field_name=None, message_type=None): |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 301 | """Recursive helper for handle_paths to extract Path messages.""" |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 302 | message_type = message_type or common_pb2.Path |
| 303 | is_path_target = message_type is common_pb2.Path |
| 304 | is_synced_target = message_type is common_pb2.SyncedDir |
| 305 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 306 | is_message = isinstance(message, protobuf_message.Message) |
| 307 | is_result_path = isinstance(message, common_pb2.ResultPath) |
| 308 | if not is_message or is_result_path: |
| 309 | # Base case: Nothing to handle. |
| 310 | # There's nothing we can do with scalar values. |
| 311 | # Skip ResultPath instances to avoid unnecessary file copying. |
| 312 | return [] |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 313 | elif is_path_target and isinstance(message, common_pb2.Path): |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 314 | # Base case: Create handler for this message. |
| 315 | if not message.path or not message.location: |
| 316 | logging.debug('Skipping %s; incomplete.', field_name or 'message') |
| 317 | return [] |
| 318 | |
| 319 | handler = PathHandler(message, destination, delete=delete, prefix=prefix, |
| 320 | reset=reset) |
| 321 | return [handler] |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 322 | elif is_synced_target and isinstance(message, common_pb2.SyncedDir): |
| 323 | if not message.dir: |
| 324 | logging.debug('Skipping %s; no directory given.', field_name or 'message') |
| 325 | return [] |
| 326 | |
| 327 | handler = SyncedDirHandler(message, destination, prefix) |
| 328 | return [handler] |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 329 | |
| 330 | # Iterate through each field and recurse. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 331 | handlers = [] |
| 332 | for descriptor in message.DESCRIPTOR.fields: |
| 333 | field = getattr(message, descriptor.name) |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 334 | if field_name: |
| 335 | new_field_name = '%s.%s' % (field_name, descriptor.name) |
| 336 | else: |
| 337 | new_field_name = descriptor.name |
| 338 | |
| 339 | if isinstance(field, protobuf_message.Message): |
| 340 | # Recurse for nested Paths. |
| 341 | handlers.extend( |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 342 | _extract_handlers(field, destination, prefix, delete, reset, |
| 343 | field_name=new_field_name, |
| 344 | message_type=message_type)) |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 345 | else: |
| 346 | # If it's iterable it may be a repeated field, try each element. |
| 347 | try: |
| 348 | iterator = iter(field) |
| 349 | except TypeError: |
| 350 | # Definitely not a repeated field, just move on. |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 351 | continue |
| 352 | |
Alex Klein | bd6edf8 | 2019-07-18 10:30:49 -0600 | [diff] [blame] | 353 | for element in iterator: |
| 354 | handlers.extend( |
Alex Klein | f0717a6 | 2019-12-06 09:45:00 -0700 | [diff] [blame] | 355 | _extract_handlers(element, destination, prefix, delete, reset, |
| 356 | field_name=new_field_name, |
| 357 | message_type=message_type)) |
Alex Klein | c05f3d1 | 2019-05-29 14:16:21 -0600 | [diff] [blame] | 358 | |
Alex Klein | aa70541 | 2019-06-04 15:00:30 -0600 | [diff] [blame] | 359 | return handlers |