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