blob: 2a70c1f4cdc447c77d3c086323f775d6392f3816 [file] [log] [blame]
Alex Kleinc05f3d12019-05-29 14:16:21 -06001# Copyright 2019 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
5"""Field handler classes.
6
7The field handlers are meant to parse information from or do some other generic
8action for a specific field type for the build_api script.
9"""
10
Alex Kleinc05f3d12019-05-29 14:16:21 -060011import contextlib
Alex Kleinbd6edf82019-07-18 10:30:49 -060012import functools
Alex Kleinc05f3d12019-05-29 14:16:21 -060013import os
14import shutil
15
Mike Frysinger849d6402019-10-17 00:14:16 -040016from google.protobuf import message as protobuf_message
17
Alex Klein38c7d9e2019-05-08 09:31:19 -060018from chromite.api.controller import controller_util
Alex Kleinc05f3d12019-05-29 14:16:21 -060019from chromite.api.gen.chromiumos import common_pb2
Alex Kleinc05f3d12019-05-29 14:16:21 -060020from chromite.lib import cros_logging as logging
21from chromite.lib import osutils
22
23
Alex Kleinbd6edf82019-07-18 10:30:49 -060024class Error(Exception):
25 """Base error class for the module."""
26
27
28class InvalidResultPathError(Error):
29 """Result path is invalid."""
30
31
Alex Kleinc05f3d12019-05-29 14:16:21 -060032class ChrootHandler(object):
33 """Translate a Chroot message to chroot enter arguments and env."""
34
Alex Kleinc7d647f2020-01-06 12:00:48 -070035 def __init__(self, clear_field):
Alex Kleinc05f3d12019-05-29 14:16:21 -060036 self.clear_field = clear_field
37
Alex Klein6becabc2020-09-11 14:03:05 -060038 def handle(self, message, recurse=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060039 """Parse a message for a chroot field."""
40 # Find the Chroot field. Search for the field by type to prevent it being
41 # tied to a naming convention.
42 for descriptor in message.DESCRIPTOR.fields:
43 field = getattr(message, descriptor.name)
44 if isinstance(field, common_pb2.Chroot):
45 chroot = field
46 if self.clear_field:
47 message.ClearField(descriptor.name)
48 return self.parse_chroot(chroot)
49
Alex Klein6becabc2020-09-11 14:03:05 -060050 # Recurse down one level. This is handy for meta-endpoints that use another
51 # endpoint's request to produce data for or about the second endpoint.
52 # e.g. PackageService/NeedsChromeSource.
53 if recurse:
54 for descriptor in message.DESCRIPTOR.fields:
55 field = getattr(message, descriptor.name)
56 if isinstance(field, protobuf_message.Message):
57 chroot = self.handle(field, recurse=False)
58 if chroot:
59 return chroot
60
Alex Kleinc05f3d12019-05-29 14:16:21 -060061 return None
62
63 def parse_chroot(self, chroot_message):
64 """Parse a Chroot message instance."""
Alex Kleinc7d647f2020-01-06 12:00:48 -070065 return controller_util.ParseChroot(chroot_message)
Alex Kleinc05f3d12019-05-29 14:16:21 -060066
67
Alex Kleinc7d647f2020-01-06 12:00:48 -070068def handle_chroot(message, clear_field=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060069 """Find and parse the chroot field, returning the Chroot instance.
70
71 Returns:
72 chroot_lib.Chroot
73 """
Alex Kleinc7d647f2020-01-06 12:00:48 -070074 handler = ChrootHandler(clear_field)
Alex Kleinc05f3d12019-05-29 14:16:21 -060075 chroot = handler.handle(message)
76 if chroot:
77 return chroot
78
79 logging.warning('No chroot message found, falling back to defaults.')
80 return handler.parse_chroot(common_pb2.Chroot())
81
82
Alex Klein9b7331e2019-12-30 14:37:21 -070083def handle_goma(message, chroot_path):
84 """Find and parse the GomaConfig field, returning the Goma instance."""
85 for descriptor in message.DESCRIPTOR.fields:
86 field = getattr(message, descriptor.name)
87 if isinstance(field, common_pb2.GomaConfig):
88 goma_config = field
89 return controller_util.ParseGomaConfig(goma_config, chroot_path)
90
91 return None
92
93
Alex Kleinc05f3d12019-05-29 14:16:21 -060094class PathHandler(object):
95 """Handles copying a file or directory into or out of the chroot."""
96
97 INSIDE = common_pb2.Path.INSIDE
98 OUTSIDE = common_pb2.Path.OUTSIDE
Alex Kleinc05f3d12019-05-29 14:16:21 -060099
Alex Kleinbd6edf82019-07-18 10:30:49 -0600100 def __init__(self, field, destination, delete, prefix=None, reset=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600101 """Path handler initialization.
102
103 Args:
104 field (common_pb2.Path): The Path message.
105 destination (str): The destination base path.
106 delete (bool): Whether the copied file(s) should be deleted on cleanup.
107 prefix (str|None): A path prefix to remove from the destination path
Alex Kleinbd6edf82019-07-18 10:30:49 -0600108 when moving files inside the chroot, or to add to the source paths when
109 moving files out of the chroot.
110 reset (bool): Whether to reset the state on cleanup.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600111 """
112 assert isinstance(field, common_pb2.Path)
113 assert field.path
114 assert field.location
115
116 self.field = field
117 self.destination = destination
118 self.prefix = prefix or ''
119 self.delete = delete
120 self.tempdir = None
Alex Kleinbd6edf82019-07-18 10:30:49 -0600121 self.reset = reset
122
Alex Kleinaa705412019-06-04 15:00:30 -0600123 # For resetting the state.
124 self._transferred = False
125 self._original_message = common_pb2.Path()
126 self._original_message.CopyFrom(self.field)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600127
Alex Kleinaae49772019-07-26 10:20:50 -0600128 def transfer(self, direction):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600129 """Copy the file or directory to its destination.
130
131 Args:
132 direction (int): The direction files are being copied (into or out of
133 the chroot). Specifying the direction allows avoiding performing
134 unnecessary copies.
135 """
Alex Kleinaa705412019-06-04 15:00:30 -0600136 if self._transferred:
137 return
138
Alex Kleinaae49772019-07-26 10:20:50 -0600139 assert direction in [self.INSIDE, self.OUTSIDE]
Alex Kleinc05f3d12019-05-29 14:16:21 -0600140
141 if self.field.location == direction:
Alex Kleinaa705412019-06-04 15:00:30 -0600142 # Already in the correct location, nothing to do.
143 return
Alex Kleinc05f3d12019-05-29 14:16:21 -0600144
Alex Kleinaae49772019-07-26 10:20:50 -0600145 # Create a tempdir for the copied file if we're cleaning it up afterwords.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600146 if self.delete:
147 self.tempdir = osutils.TempDir(base_dir=self.destination)
148 destination = self.tempdir.tempdir
149 else:
150 destination = self.destination
151
Alex Kleinbd6edf82019-07-18 10:30:49 -0600152 source = self.field.path
153 if direction == self.OUTSIDE and self.prefix:
Alex Kleinaae49772019-07-26 10:20:50 -0600154 # When we're extracting files, we need /tmp/result to be
155 # /path/to/chroot/tmp/result.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600156 source = os.path.join(self.prefix, source.lstrip(os.sep))
157
158 if os.path.isfile(source):
Alex Kleinaae49772019-07-26 10:20:50 -0600159 # File - use the old file name, just copy it into the destination.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600160 dest_path = os.path.join(destination, os.path.basename(source))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600161 copy_fn = shutil.copy
162 else:
Alex Kleinbd6edf82019-07-18 10:30:49 -0600163 # Directory - just copy everything into the new location.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600164 dest_path = destination
Alex Kleinbd6edf82019-07-18 10:30:49 -0600165 copy_fn = functools.partial(osutils.CopyDirContents, allow_nonempty=True)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600166
Alex Kleinbd6edf82019-07-18 10:30:49 -0600167 logging.debug('Copying %s to %s', source, dest_path)
168 copy_fn(source, dest_path)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600169
170 # Clean up the destination path for returning, if applicable.
171 return_path = dest_path
Alex Kleinbd6edf82019-07-18 10:30:49 -0600172 if direction == self.INSIDE and return_path.startswith(self.prefix):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600173 return_path = return_path[len(self.prefix):]
174
Alex Kleinaa705412019-06-04 15:00:30 -0600175 self.field.path = return_path
176 self.field.location = direction
177 self._transferred = True
Alex Kleinc05f3d12019-05-29 14:16:21 -0600178
179 def cleanup(self):
180 if self.tempdir:
181 self.tempdir.Cleanup()
182 self.tempdir = None
183
Alex Kleinbd6edf82019-07-18 10:30:49 -0600184 if self.reset:
185 self.field.CopyFrom(self._original_message)
Alex Kleinaa705412019-06-04 15:00:30 -0600186
Alex Kleinc05f3d12019-05-29 14:16:21 -0600187
Alex Kleinf0717a62019-12-06 09:45:00 -0700188class SyncedDirHandler(object):
189 """Handler for syncing directories across the chroot boundary."""
190
191 def __init__(self, field, destination, prefix):
192 self.field = field
193 self.prefix = prefix
194
195 self.source = self.field.dir
196 if not self.source.endswith(os.sep):
197 self.source += os.sep
198
199 self.destination = destination
200 if not self.destination.endswith(os.sep):
201 self.destination += os.sep
202
203 # For resetting the message later.
204 self._original_message = common_pb2.SyncedDir()
205 self._original_message.CopyFrom(self.field)
206
207 def _sync(self, src, dest):
Alex Klein915cce92019-12-17 14:19:50 -0700208 logging.info('Syncing %s to %s', src, dest)
Alex Kleinf0717a62019-12-06 09:45:00 -0700209 # TODO: This would probably be more efficient with rsync.
210 osutils.EmptyDir(dest)
211 osutils.CopyDirContents(src, dest)
212
213 def sync_in(self):
214 """Sync files from the source directory to the destination directory."""
215 self._sync(self.source, self.destination)
216 self.field.dir = '/%s' % os.path.relpath(self.destination, self.prefix)
217
218 def sync_out(self):
219 """Sync files from the destination directory to the source directory."""
220 self._sync(self.destination, self.source)
221 self.field.CopyFrom(self._original_message)
222
223
Alex Kleinc05f3d12019-05-29 14:16:21 -0600224@contextlib.contextmanager
Alex Kleinaae49772019-07-26 10:20:50 -0600225def copy_paths_in(message, destination, delete=True, prefix=None):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600226 """Context manager function to transfer and cleanup all Path messages.
227
228 Args:
229 message (Message): A message whose Path messages should be transferred.
Alex Kleinf0717a62019-12-06 09:45:00 -0700230 destination (str): The base destination path.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600231 delete (bool): Whether the file(s) should be deleted.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600232 prefix (str|None): A prefix path to remove from the final destination path
233 in the Path message (i.e. remove the chroot path).
234
235 Returns:
236 list[PathHandler]: The path handlers.
237 """
238 assert destination
Alex Kleinc05f3d12019-05-29 14:16:21 -0600239
Alex Kleinf0717a62019-12-06 09:45:00 -0700240 handlers = _extract_handlers(message, destination, prefix, delete=delete,
241 reset=True)
Alex Kleinaa705412019-06-04 15:00:30 -0600242
243 for handler in handlers:
Alex Kleinaae49772019-07-26 10:20:50 -0600244 handler.transfer(PathHandler.INSIDE)
Alex Kleinaa705412019-06-04 15:00:30 -0600245
246 try:
247 yield handlers
248 finally:
249 for handler in handlers:
250 handler.cleanup()
251
252
Alex Kleinf0717a62019-12-06 09:45:00 -0700253@contextlib.contextmanager
254def sync_dirs(message, destination, prefix):
255 """Context manager function to handle SyncedDir messages.
256
257 The sync semantics are effectively:
258 rsync -r --del source/ destination/
259 * The endpoint runs. *
260 rsync -r --del destination/ source/
261
262 Args:
263 message (Message): A message whose SyncedPath messages should be synced.
264 destination (str): The destination path.
265 prefix (str): A prefix path to remove from the final destination path
266 in the Path message (i.e. remove the chroot path).
267
268 Returns:
269 list[SyncedDirHandler]: The handlers.
270 """
271 assert destination
272
273 handlers = _extract_handlers(message, destination, prefix=prefix,
274 delete=False, reset=True,
275 message_type=common_pb2.SyncedDir)
276
277 for handler in handlers:
278 handler.sync_in()
279
280 try:
281 yield handlers
282 finally:
283 for handler in handlers:
284 handler.sync_out()
285
286
Alex Kleinaae49772019-07-26 10:20:50 -0600287def extract_results(request_message, response_message, chroot):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600288 """Transfer all response Path messages to the request's ResultPath.
289
290 Args:
291 request_message (Message): The request message containing a ResultPath
292 message.
293 response_message (Message): The response message whose Path message(s)
294 are to be transferred.
295 chroot (chroot_lib.Chroot): The chroot the files are being copied out of.
296 """
297 # Find the ResultPath.
298 for descriptor in request_message.DESCRIPTOR.fields:
299 field = getattr(request_message, descriptor.name)
300 if isinstance(field, common_pb2.ResultPath):
301 result_path_message = field
302 break
303 else:
304 # No ResultPath to handle.
305 return
306
307 destination = result_path_message.path.path
Alex Kleinf0717a62019-12-06 09:45:00 -0700308 handlers = _extract_handlers(response_message, destination, chroot.path,
309 delete=False, reset=False)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600310
311 for handler in handlers:
312 handler.transfer(PathHandler.OUTSIDE)
313 handler.cleanup()
314
315
Alex Kleinf0717a62019-12-06 09:45:00 -0700316def _extract_handlers(message, destination, prefix, delete=False, reset=False,
317 field_name=None, message_type=None):
Alex Kleinaa705412019-06-04 15:00:30 -0600318 """Recursive helper for handle_paths to extract Path messages."""
Alex Kleinf0717a62019-12-06 09:45:00 -0700319 message_type = message_type or common_pb2.Path
320 is_path_target = message_type is common_pb2.Path
321 is_synced_target = message_type is common_pb2.SyncedDir
322
Alex Kleinbd6edf82019-07-18 10:30:49 -0600323 is_message = isinstance(message, protobuf_message.Message)
324 is_result_path = isinstance(message, common_pb2.ResultPath)
325 if not is_message or is_result_path:
326 # Base case: Nothing to handle.
327 # There's nothing we can do with scalar values.
328 # Skip ResultPath instances to avoid unnecessary file copying.
329 return []
Alex Kleinf0717a62019-12-06 09:45:00 -0700330 elif is_path_target and isinstance(message, common_pb2.Path):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600331 # Base case: Create handler for this message.
332 if not message.path or not message.location:
333 logging.debug('Skipping %s; incomplete.', field_name or 'message')
334 return []
335
336 handler = PathHandler(message, destination, delete=delete, prefix=prefix,
337 reset=reset)
338 return [handler]
Alex Kleinf0717a62019-12-06 09:45:00 -0700339 elif is_synced_target and isinstance(message, common_pb2.SyncedDir):
340 if not message.dir:
341 logging.debug('Skipping %s; no directory given.', field_name or 'message')
342 return []
343
344 handler = SyncedDirHandler(message, destination, prefix)
345 return [handler]
Alex Kleinbd6edf82019-07-18 10:30:49 -0600346
347 # Iterate through each field and recurse.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600348 handlers = []
349 for descriptor in message.DESCRIPTOR.fields:
350 field = getattr(message, descriptor.name)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600351 if field_name:
352 new_field_name = '%s.%s' % (field_name, descriptor.name)
353 else:
354 new_field_name = descriptor.name
355
356 if isinstance(field, protobuf_message.Message):
357 # Recurse for nested Paths.
358 handlers.extend(
Alex Kleinf0717a62019-12-06 09:45:00 -0700359 _extract_handlers(field, destination, prefix, delete, reset,
360 field_name=new_field_name,
361 message_type=message_type))
Alex Kleinbd6edf82019-07-18 10:30:49 -0600362 else:
363 # If it's iterable it may be a repeated field, try each element.
364 try:
365 iterator = iter(field)
366 except TypeError:
367 # Definitely not a repeated field, just move on.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600368 continue
369
Alex Kleinbd6edf82019-07-18 10:30:49 -0600370 for element in iterator:
371 handlers.extend(
Alex Kleinf0717a62019-12-06 09:45:00 -0700372 _extract_handlers(element, destination, prefix, delete, reset,
373 field_name=new_field_name,
374 message_type=message_type))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600375
Alex Kleinaa705412019-06-04 15:00:30 -0600376 return handlers