blob: b54c0cd17e9a9270e480fca519428ae176ef6c03 [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
18
Mike Frysinger849d6402019-10-17 00:14:16 -040019from google.protobuf import message as protobuf_message
20
Alex Klein38c7d9e2019-05-08 09:31:19 -060021from chromite.api.controller import controller_util
Alex Kleinc05f3d12019-05-29 14:16:21 -060022from chromite.api.gen.chromiumos import common_pb2
Alex Kleinc05f3d12019-05-29 14:16:21 -060023from chromite.lib import cros_logging as logging
24from chromite.lib import osutils
25
26
Alex Kleinbd6edf82019-07-18 10:30:49 -060027class Error(Exception):
28 """Base error class for the module."""
29
30
31class InvalidResultPathError(Error):
32 """Result path is invalid."""
33
34
Alex Kleinc05f3d12019-05-29 14:16:21 -060035class 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 Klein38c7d9e2019-05-08 09:31:19 -060057 return controller_util.ParseChroot(chroot_message)
Alex Kleinc05f3d12019-05-29 14:16:21 -060058
59
60def 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
75class 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 Kleinc05f3d12019-05-29 14:16:21 -060080
Alex Kleinbd6edf82019-07-18 10:30:49 -060081 def __init__(self, field, destination, delete, prefix=None, reset=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060082 """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 Kleinbd6edf82019-07-18 10:30:49 -060089 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 Kleinc05f3d12019-05-29 14:16:21 -060092 """
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 Kleinbd6edf82019-07-18 10:30:49 -0600102 self.reset = reset
103
Alex Kleinaa705412019-06-04 15:00:30 -0600104 # For resetting the state.
105 self._transferred = False
106 self._original_message = common_pb2.Path()
107 self._original_message.CopyFrom(self.field)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600108
Alex Kleinaae49772019-07-26 10:20:50 -0600109 def transfer(self, direction):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600110 """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 Kleinaa705412019-06-04 15:00:30 -0600117 if self._transferred:
118 return
119
Alex Kleinaae49772019-07-26 10:20:50 -0600120 assert direction in [self.INSIDE, self.OUTSIDE]
Alex Kleinc05f3d12019-05-29 14:16:21 -0600121
122 if self.field.location == direction:
Alex Kleinaa705412019-06-04 15:00:30 -0600123 # Already in the correct location, nothing to do.
124 return
Alex Kleinc05f3d12019-05-29 14:16:21 -0600125
Alex Kleinaae49772019-07-26 10:20:50 -0600126 # Create a tempdir for the copied file if we're cleaning it up afterwords.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600127 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 Kleinbd6edf82019-07-18 10:30:49 -0600133 source = self.field.path
134 if direction == self.OUTSIDE and self.prefix:
Alex Kleinaae49772019-07-26 10:20:50 -0600135 # When we're extracting files, we need /tmp/result to be
136 # /path/to/chroot/tmp/result.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600137 source = os.path.join(self.prefix, source.lstrip(os.sep))
138
139 if os.path.isfile(source):
Alex Kleinaae49772019-07-26 10:20:50 -0600140 # File - use the old file name, just copy it into the destination.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600141 dest_path = os.path.join(destination, os.path.basename(source))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600142 copy_fn = shutil.copy
143 else:
Alex Kleinbd6edf82019-07-18 10:30:49 -0600144 # Directory - just copy everything into the new location.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600145 dest_path = destination
Alex Kleinbd6edf82019-07-18 10:30:49 -0600146 copy_fn = functools.partial(osutils.CopyDirContents, allow_nonempty=True)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600147
Alex Kleinbd6edf82019-07-18 10:30:49 -0600148 logging.debug('Copying %s to %s', source, dest_path)
149 copy_fn(source, dest_path)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600150
151 # Clean up the destination path for returning, if applicable.
152 return_path = dest_path
Alex Kleinbd6edf82019-07-18 10:30:49 -0600153 if direction == self.INSIDE and return_path.startswith(self.prefix):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600154 return_path = return_path[len(self.prefix):]
155
Alex Kleinaa705412019-06-04 15:00:30 -0600156 self.field.path = return_path
157 self.field.location = direction
158 self._transferred = True
Alex Kleinc05f3d12019-05-29 14:16:21 -0600159
160 def cleanup(self):
161 if self.tempdir:
162 self.tempdir.Cleanup()
163 self.tempdir = None
164
Alex Kleinbd6edf82019-07-18 10:30:49 -0600165 if self.reset:
166 self.field.CopyFrom(self._original_message)
Alex Kleinaa705412019-06-04 15:00:30 -0600167
Alex Kleinc05f3d12019-05-29 14:16:21 -0600168
Alex Kleinf0717a62019-12-06 09:45:00 -0700169class 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 Kleinc05f3d12019-05-29 14:16:21 -0600205@contextlib.contextmanager
Alex Kleinaae49772019-07-26 10:20:50 -0600206def copy_paths_in(message, destination, delete=True, prefix=None):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600207 """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 Kleinf0717a62019-12-06 09:45:00 -0700211 destination (str): The base destination path.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600212 delete (bool): Whether the file(s) should be deleted.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600213 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 Kleinc05f3d12019-05-29 14:16:21 -0600220
Alex Kleinf0717a62019-12-06 09:45:00 -0700221 handlers = _extract_handlers(message, destination, prefix, delete=delete,
222 reset=True)
Alex Kleinaa705412019-06-04 15:00:30 -0600223
224 for handler in handlers:
Alex Kleinaae49772019-07-26 10:20:50 -0600225 handler.transfer(PathHandler.INSIDE)
Alex Kleinaa705412019-06-04 15:00:30 -0600226
227 try:
228 yield handlers
229 finally:
230 for handler in handlers:
231 handler.cleanup()
232
233
Alex Kleinf0717a62019-12-06 09:45:00 -0700234@contextlib.contextmanager
235def 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 Kleinaae49772019-07-26 10:20:50 -0600268def extract_results(request_message, response_message, chroot):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600269 """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 Kleinf0717a62019-12-06 09:45:00 -0700289 handlers = _extract_handlers(response_message, destination, chroot.path,
290 delete=False, reset=False)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600291
292 for handler in handlers:
293 handler.transfer(PathHandler.OUTSIDE)
294 handler.cleanup()
295
296
Alex Kleinf0717a62019-12-06 09:45:00 -0700297def _extract_handlers(message, destination, prefix, delete=False, reset=False,
298 field_name=None, message_type=None):
Alex Kleinaa705412019-06-04 15:00:30 -0600299 """Recursive helper for handle_paths to extract Path messages."""
Alex Kleinf0717a62019-12-06 09:45:00 -0700300 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 Kleinbd6edf82019-07-18 10:30:49 -0600304 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 Kleinf0717a62019-12-06 09:45:00 -0700311 elif is_path_target and isinstance(message, common_pb2.Path):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600312 # 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 Kleinf0717a62019-12-06 09:45:00 -0700320 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 Kleinbd6edf82019-07-18 10:30:49 -0600327
328 # Iterate through each field and recurse.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600329 handlers = []
330 for descriptor in message.DESCRIPTOR.fields:
331 field = getattr(message, descriptor.name)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600332 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 Kleinf0717a62019-12-06 09:45:00 -0700340 _extract_handlers(field, destination, prefix, delete, reset,
341 field_name=new_field_name,
342 message_type=message_type))
Alex Kleinbd6edf82019-07-18 10:30:49 -0600343 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 Kleinc05f3d12019-05-29 14:16:21 -0600349 continue
350
Alex Kleinbd6edf82019-07-18 10:30:49 -0600351 for element in iterator:
352 handlers.extend(
Alex Kleinf0717a62019-12-06 09:45:00 -0700353 _extract_handlers(element, destination, prefix, delete, reset,
354 field_name=new_field_name,
355 message_type=message_type))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600356
Alex Kleinaa705412019-06-04 15:00:30 -0600357 return handlers