blob: 0eff8c832e9a3a0d1425e08d70504dbd16e6195d [file] [log] [blame]
Alex Kleinc05f3d12019-05-29 14:16:21 -06001# -*- 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
8The field handlers are meant to parse information from or do some other generic
9action for a specific field type for the build_api script.
10"""
11
12from __future__ import print_function
13
14import contextlib
Alex Kleinbd6edf82019-07-18 10:30:49 -060015import functools
Alex Kleinc05f3d12019-05-29 14:16:21 -060016import os
17import shutil
Mike Frysingeref94e4c2020-02-10 23:59:54 -050018import sys
Alex Kleinc05f3d12019-05-29 14:16:21 -060019
Mike Frysinger849d6402019-10-17 00:14:16 -040020from google.protobuf import message as protobuf_message
21
Alex Klein38c7d9e2019-05-08 09:31:19 -060022from chromite.api.controller import controller_util
Alex Kleinc05f3d12019-05-29 14:16:21 -060023from chromite.api.gen.chromiumos import common_pb2
Alex Kleinc05f3d12019-05-29 14:16:21 -060024from chromite.lib import cros_logging as logging
25from chromite.lib import osutils
26
27
Mike Frysingeref94e4c2020-02-10 23:59:54 -050028assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
29
30
Alex Kleinbd6edf82019-07-18 10:30:49 -060031class Error(Exception):
32 """Base error class for the module."""
33
34
35class InvalidResultPathError(Error):
36 """Result path is invalid."""
37
38
Alex Kleinc05f3d12019-05-29 14:16:21 -060039class ChrootHandler(object):
40 """Translate a Chroot message to chroot enter arguments and env."""
41
Alex Kleinc7d647f2020-01-06 12:00:48 -070042 def __init__(self, clear_field):
Alex Kleinc05f3d12019-05-29 14:16:21 -060043 self.clear_field = clear_field
44
45 def handle(self, message):
46 """Parse a message for a chroot field."""
47 # Find the Chroot field. Search for the field by type to prevent it being
48 # tied to a naming convention.
49 for descriptor in message.DESCRIPTOR.fields:
50 field = getattr(message, descriptor.name)
51 if isinstance(field, common_pb2.Chroot):
52 chroot = field
53 if self.clear_field:
54 message.ClearField(descriptor.name)
55 return self.parse_chroot(chroot)
56
57 return None
58
59 def parse_chroot(self, chroot_message):
60 """Parse a Chroot message instance."""
Alex Kleinc7d647f2020-01-06 12:00:48 -070061 return controller_util.ParseChroot(chroot_message)
Alex Kleinc05f3d12019-05-29 14:16:21 -060062
63
Alex Kleinc7d647f2020-01-06 12:00:48 -070064def handle_chroot(message, clear_field=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060065 """Find and parse the chroot field, returning the Chroot instance.
66
67 Returns:
68 chroot_lib.Chroot
69 """
Alex Kleinc7d647f2020-01-06 12:00:48 -070070 handler = ChrootHandler(clear_field)
Alex Kleinc05f3d12019-05-29 14:16:21 -060071 chroot = handler.handle(message)
72 if chroot:
73 return chroot
74
75 logging.warning('No chroot message found, falling back to defaults.')
76 return handler.parse_chroot(common_pb2.Chroot())
77
78
Alex Klein9b7331e2019-12-30 14:37:21 -070079def handle_goma(message, chroot_path):
80 """Find and parse the GomaConfig field, returning the Goma instance."""
81 for descriptor in message.DESCRIPTOR.fields:
82 field = getattr(message, descriptor.name)
83 if isinstance(field, common_pb2.GomaConfig):
84 goma_config = field
85 return controller_util.ParseGomaConfig(goma_config, chroot_path)
86
87 return None
88
89
Alex Kleinc05f3d12019-05-29 14:16:21 -060090class PathHandler(object):
91 """Handles copying a file or directory into or out of the chroot."""
92
93 INSIDE = common_pb2.Path.INSIDE
94 OUTSIDE = common_pb2.Path.OUTSIDE
Alex Kleinc05f3d12019-05-29 14:16:21 -060095
Alex Kleinbd6edf82019-07-18 10:30:49 -060096 def __init__(self, field, destination, delete, prefix=None, reset=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060097 """Path handler initialization.
98
99 Args:
100 field (common_pb2.Path): The Path message.
101 destination (str): The destination base path.
102 delete (bool): Whether the copied file(s) should be deleted on cleanup.
103 prefix (str|None): A path prefix to remove from the destination path
Alex Kleinbd6edf82019-07-18 10:30:49 -0600104 when moving files inside the chroot, or to add to the source paths when
105 moving files out of the chroot.
106 reset (bool): Whether to reset the state on cleanup.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600107 """
108 assert isinstance(field, common_pb2.Path)
109 assert field.path
110 assert field.location
111
112 self.field = field
113 self.destination = destination
114 self.prefix = prefix or ''
115 self.delete = delete
116 self.tempdir = None
Alex Kleinbd6edf82019-07-18 10:30:49 -0600117 self.reset = reset
118
Alex Kleinaa705412019-06-04 15:00:30 -0600119 # For resetting the state.
120 self._transferred = False
121 self._original_message = common_pb2.Path()
122 self._original_message.CopyFrom(self.field)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600123
Alex Kleinaae49772019-07-26 10:20:50 -0600124 def transfer(self, direction):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600125 """Copy the file or directory to its destination.
126
127 Args:
128 direction (int): The direction files are being copied (into or out of
129 the chroot). Specifying the direction allows avoiding performing
130 unnecessary copies.
131 """
Alex Kleinaa705412019-06-04 15:00:30 -0600132 if self._transferred:
133 return
134
Alex Kleinaae49772019-07-26 10:20:50 -0600135 assert direction in [self.INSIDE, self.OUTSIDE]
Alex Kleinc05f3d12019-05-29 14:16:21 -0600136
137 if self.field.location == direction:
Alex Kleinaa705412019-06-04 15:00:30 -0600138 # Already in the correct location, nothing to do.
139 return
Alex Kleinc05f3d12019-05-29 14:16:21 -0600140
Alex Kleinaae49772019-07-26 10:20:50 -0600141 # Create a tempdir for the copied file if we're cleaning it up afterwords.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600142 if self.delete:
143 self.tempdir = osutils.TempDir(base_dir=self.destination)
144 destination = self.tempdir.tempdir
145 else:
146 destination = self.destination
147
Alex Kleinbd6edf82019-07-18 10:30:49 -0600148 source = self.field.path
149 if direction == self.OUTSIDE and self.prefix:
Alex Kleinaae49772019-07-26 10:20:50 -0600150 # When we're extracting files, we need /tmp/result to be
151 # /path/to/chroot/tmp/result.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600152 source = os.path.join(self.prefix, source.lstrip(os.sep))
153
154 if os.path.isfile(source):
Alex Kleinaae49772019-07-26 10:20:50 -0600155 # File - use the old file name, just copy it into the destination.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600156 dest_path = os.path.join(destination, os.path.basename(source))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600157 copy_fn = shutil.copy
158 else:
Alex Kleinbd6edf82019-07-18 10:30:49 -0600159 # Directory - just copy everything into the new location.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600160 dest_path = destination
Alex Kleinbd6edf82019-07-18 10:30:49 -0600161 copy_fn = functools.partial(osutils.CopyDirContents, allow_nonempty=True)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600162
Alex Kleinbd6edf82019-07-18 10:30:49 -0600163 logging.debug('Copying %s to %s', source, dest_path)
164 copy_fn(source, dest_path)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600165
166 # Clean up the destination path for returning, if applicable.
167 return_path = dest_path
Alex Kleinbd6edf82019-07-18 10:30:49 -0600168 if direction == self.INSIDE and return_path.startswith(self.prefix):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600169 return_path = return_path[len(self.prefix):]
170
Alex Kleinaa705412019-06-04 15:00:30 -0600171 self.field.path = return_path
172 self.field.location = direction
173 self._transferred = True
Alex Kleinc05f3d12019-05-29 14:16:21 -0600174
175 def cleanup(self):
176 if self.tempdir:
177 self.tempdir.Cleanup()
178 self.tempdir = None
179
Alex Kleinbd6edf82019-07-18 10:30:49 -0600180 if self.reset:
181 self.field.CopyFrom(self._original_message)
Alex Kleinaa705412019-06-04 15:00:30 -0600182
Alex Kleinc05f3d12019-05-29 14:16:21 -0600183
Alex Kleinf0717a62019-12-06 09:45:00 -0700184class SyncedDirHandler(object):
185 """Handler for syncing directories across the chroot boundary."""
186
187 def __init__(self, field, destination, prefix):
188 self.field = field
189 self.prefix = prefix
190
191 self.source = self.field.dir
192 if not self.source.endswith(os.sep):
193 self.source += os.sep
194
195 self.destination = destination
196 if not self.destination.endswith(os.sep):
197 self.destination += os.sep
198
199 # For resetting the message later.
200 self._original_message = common_pb2.SyncedDir()
201 self._original_message.CopyFrom(self.field)
202
203 def _sync(self, src, dest):
Alex Klein915cce92019-12-17 14:19:50 -0700204 logging.info('Syncing %s to %s', src, dest)
Alex Kleinf0717a62019-12-06 09:45:00 -0700205 # TODO: This would probably be more efficient with rsync.
206 osutils.EmptyDir(dest)
207 osutils.CopyDirContents(src, dest)
208
209 def sync_in(self):
210 """Sync files from the source directory to the destination directory."""
211 self._sync(self.source, self.destination)
212 self.field.dir = '/%s' % os.path.relpath(self.destination, self.prefix)
213
214 def sync_out(self):
215 """Sync files from the destination directory to the source directory."""
216 self._sync(self.destination, self.source)
217 self.field.CopyFrom(self._original_message)
218
219
Alex Kleinc05f3d12019-05-29 14:16:21 -0600220@contextlib.contextmanager
Alex Kleinaae49772019-07-26 10:20:50 -0600221def copy_paths_in(message, destination, delete=True, prefix=None):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600222 """Context manager function to transfer and cleanup all Path messages.
223
224 Args:
225 message (Message): A message whose Path messages should be transferred.
Alex Kleinf0717a62019-12-06 09:45:00 -0700226 destination (str): The base destination path.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600227 delete (bool): Whether the file(s) should be deleted.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600228 prefix (str|None): A prefix path to remove from the final destination path
229 in the Path message (i.e. remove the chroot path).
230
231 Returns:
232 list[PathHandler]: The path handlers.
233 """
234 assert destination
Alex Kleinc05f3d12019-05-29 14:16:21 -0600235
Alex Kleinf0717a62019-12-06 09:45:00 -0700236 handlers = _extract_handlers(message, destination, prefix, delete=delete,
237 reset=True)
Alex Kleinaa705412019-06-04 15:00:30 -0600238
239 for handler in handlers:
Alex Kleinaae49772019-07-26 10:20:50 -0600240 handler.transfer(PathHandler.INSIDE)
Alex Kleinaa705412019-06-04 15:00:30 -0600241
242 try:
243 yield handlers
244 finally:
245 for handler in handlers:
246 handler.cleanup()
247
248
Alex Kleinf0717a62019-12-06 09:45:00 -0700249@contextlib.contextmanager
250def sync_dirs(message, destination, prefix):
251 """Context manager function to handle SyncedDir messages.
252
253 The sync semantics are effectively:
254 rsync -r --del source/ destination/
255 * The endpoint runs. *
256 rsync -r --del destination/ source/
257
258 Args:
259 message (Message): A message whose SyncedPath messages should be synced.
260 destination (str): The destination path.
261 prefix (str): A prefix path to remove from the final destination path
262 in the Path message (i.e. remove the chroot path).
263
264 Returns:
265 list[SyncedDirHandler]: The handlers.
266 """
267 assert destination
268
269 handlers = _extract_handlers(message, destination, prefix=prefix,
270 delete=False, reset=True,
271 message_type=common_pb2.SyncedDir)
272
273 for handler in handlers:
274 handler.sync_in()
275
276 try:
277 yield handlers
278 finally:
279 for handler in handlers:
280 handler.sync_out()
281
282
Alex Kleinaae49772019-07-26 10:20:50 -0600283def extract_results(request_message, response_message, chroot):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600284 """Transfer all response Path messages to the request's ResultPath.
285
286 Args:
287 request_message (Message): The request message containing a ResultPath
288 message.
289 response_message (Message): The response message whose Path message(s)
290 are to be transferred.
291 chroot (chroot_lib.Chroot): The chroot the files are being copied out of.
292 """
293 # Find the ResultPath.
294 for descriptor in request_message.DESCRIPTOR.fields:
295 field = getattr(request_message, descriptor.name)
296 if isinstance(field, common_pb2.ResultPath):
297 result_path_message = field
298 break
299 else:
300 # No ResultPath to handle.
301 return
302
303 destination = result_path_message.path.path
Alex Kleinf0717a62019-12-06 09:45:00 -0700304 handlers = _extract_handlers(response_message, destination, chroot.path,
305 delete=False, reset=False)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600306
307 for handler in handlers:
308 handler.transfer(PathHandler.OUTSIDE)
309 handler.cleanup()
310
311
Alex Kleinf0717a62019-12-06 09:45:00 -0700312def _extract_handlers(message, destination, prefix, delete=False, reset=False,
313 field_name=None, message_type=None):
Alex Kleinaa705412019-06-04 15:00:30 -0600314 """Recursive helper for handle_paths to extract Path messages."""
Alex Kleinf0717a62019-12-06 09:45:00 -0700315 message_type = message_type or common_pb2.Path
316 is_path_target = message_type is common_pb2.Path
317 is_synced_target = message_type is common_pb2.SyncedDir
318
Alex Kleinbd6edf82019-07-18 10:30:49 -0600319 is_message = isinstance(message, protobuf_message.Message)
320 is_result_path = isinstance(message, common_pb2.ResultPath)
321 if not is_message or is_result_path:
322 # Base case: Nothing to handle.
323 # There's nothing we can do with scalar values.
324 # Skip ResultPath instances to avoid unnecessary file copying.
325 return []
Alex Kleinf0717a62019-12-06 09:45:00 -0700326 elif is_path_target and isinstance(message, common_pb2.Path):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600327 # Base case: Create handler for this message.
328 if not message.path or not message.location:
329 logging.debug('Skipping %s; incomplete.', field_name or 'message')
330 return []
331
332 handler = PathHandler(message, destination, delete=delete, prefix=prefix,
333 reset=reset)
334 return [handler]
Alex Kleinf0717a62019-12-06 09:45:00 -0700335 elif is_synced_target and isinstance(message, common_pb2.SyncedDir):
336 if not message.dir:
337 logging.debug('Skipping %s; no directory given.', field_name or 'message')
338 return []
339
340 handler = SyncedDirHandler(message, destination, prefix)
341 return [handler]
Alex Kleinbd6edf82019-07-18 10:30:49 -0600342
343 # Iterate through each field and recurse.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600344 handlers = []
345 for descriptor in message.DESCRIPTOR.fields:
346 field = getattr(message, descriptor.name)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600347 if field_name:
348 new_field_name = '%s.%s' % (field_name, descriptor.name)
349 else:
350 new_field_name = descriptor.name
351
352 if isinstance(field, protobuf_message.Message):
353 # Recurse for nested Paths.
354 handlers.extend(
Alex Kleinf0717a62019-12-06 09:45:00 -0700355 _extract_handlers(field, destination, prefix, delete, reset,
356 field_name=new_field_name,
357 message_type=message_type))
Alex Kleinbd6edf82019-07-18 10:30:49 -0600358 else:
359 # If it's iterable it may be a repeated field, try each element.
360 try:
361 iterator = iter(field)
362 except TypeError:
363 # Definitely not a repeated field, just move on.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600364 continue
365
Alex Kleinbd6edf82019-07-18 10:30:49 -0600366 for element in iterator:
367 handlers.extend(
Alex Kleinf0717a62019-12-06 09:45:00 -0700368 _extract_handlers(element, destination, prefix, delete, reset,
369 field_name=new_field_name,
370 message_type=message_type))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600371
Alex Kleinaa705412019-06-04 15:00:30 -0600372 return handlers