blob: 78aa20158aca6dba6ea4fc1a6fb59c0de70dc8fa [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
Alex Klein915cce92019-12-17 14:19:50 -070038 def __init__(self, clear_field, parse_goma):
Alex Kleinc05f3d12019-05-29 14:16:21 -060039 self.clear_field = clear_field
Alex Klein915cce92019-12-17 14:19:50 -070040 self.parse_goma = parse_goma
Alex Kleinc05f3d12019-05-29 14:16:21 -060041
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 Klein915cce92019-12-17 14:19:50 -070058 return controller_util.ParseChroot(chroot_message,
59 parse_goma=self.parse_goma)
Alex Kleinc05f3d12019-05-29 14:16:21 -060060
61
Alex Klein915cce92019-12-17 14:19:50 -070062def handle_chroot(message, clear_field=True, parse_goma=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060063 """Find and parse the chroot field, returning the Chroot instance.
64
65 Returns:
66 chroot_lib.Chroot
67 """
Alex Klein915cce92019-12-17 14:19:50 -070068 handler = ChrootHandler(clear_field, parse_goma)
Alex Kleinc05f3d12019-05-29 14:16:21 -060069 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
77class 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 Kleinc05f3d12019-05-29 14:16:21 -060082
Alex Kleinbd6edf82019-07-18 10:30:49 -060083 def __init__(self, field, destination, delete, prefix=None, reset=True):
Alex Kleinc05f3d12019-05-29 14:16:21 -060084 """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 Kleinbd6edf82019-07-18 10:30:49 -060091 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 Kleinc05f3d12019-05-29 14:16:21 -060094 """
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 Kleinbd6edf82019-07-18 10:30:49 -0600104 self.reset = reset
105
Alex Kleinaa705412019-06-04 15:00:30 -0600106 # For resetting the state.
107 self._transferred = False
108 self._original_message = common_pb2.Path()
109 self._original_message.CopyFrom(self.field)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600110
Alex Kleinaae49772019-07-26 10:20:50 -0600111 def transfer(self, direction):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600112 """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 Kleinaa705412019-06-04 15:00:30 -0600119 if self._transferred:
120 return
121
Alex Kleinaae49772019-07-26 10:20:50 -0600122 assert direction in [self.INSIDE, self.OUTSIDE]
Alex Kleinc05f3d12019-05-29 14:16:21 -0600123
124 if self.field.location == direction:
Alex Kleinaa705412019-06-04 15:00:30 -0600125 # Already in the correct location, nothing to do.
126 return
Alex Kleinc05f3d12019-05-29 14:16:21 -0600127
Alex Kleinaae49772019-07-26 10:20:50 -0600128 # Create a tempdir for the copied file if we're cleaning it up afterwords.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600129 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 Kleinbd6edf82019-07-18 10:30:49 -0600135 source = self.field.path
136 if direction == self.OUTSIDE and self.prefix:
Alex Kleinaae49772019-07-26 10:20:50 -0600137 # When we're extracting files, we need /tmp/result to be
138 # /path/to/chroot/tmp/result.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600139 source = os.path.join(self.prefix, source.lstrip(os.sep))
140
141 if os.path.isfile(source):
Alex Kleinaae49772019-07-26 10:20:50 -0600142 # File - use the old file name, just copy it into the destination.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600143 dest_path = os.path.join(destination, os.path.basename(source))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600144 copy_fn = shutil.copy
145 else:
Alex Kleinbd6edf82019-07-18 10:30:49 -0600146 # Directory - just copy everything into the new location.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600147 dest_path = destination
Alex Kleinbd6edf82019-07-18 10:30:49 -0600148 copy_fn = functools.partial(osutils.CopyDirContents, allow_nonempty=True)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600149
Alex Kleinbd6edf82019-07-18 10:30:49 -0600150 logging.debug('Copying %s to %s', source, dest_path)
151 copy_fn(source, dest_path)
Alex Kleinc05f3d12019-05-29 14:16:21 -0600152
153 # Clean up the destination path for returning, if applicable.
154 return_path = dest_path
Alex Kleinbd6edf82019-07-18 10:30:49 -0600155 if direction == self.INSIDE and return_path.startswith(self.prefix):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600156 return_path = return_path[len(self.prefix):]
157
Alex Kleinaa705412019-06-04 15:00:30 -0600158 self.field.path = return_path
159 self.field.location = direction
160 self._transferred = True
Alex Kleinc05f3d12019-05-29 14:16:21 -0600161
162 def cleanup(self):
163 if self.tempdir:
164 self.tempdir.Cleanup()
165 self.tempdir = None
166
Alex Kleinbd6edf82019-07-18 10:30:49 -0600167 if self.reset:
168 self.field.CopyFrom(self._original_message)
Alex Kleinaa705412019-06-04 15:00:30 -0600169
Alex Kleinc05f3d12019-05-29 14:16:21 -0600170
Alex Kleinf0717a62019-12-06 09:45:00 -0700171class 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 Klein915cce92019-12-17 14:19:50 -0700191 logging.info('Syncing %s to %s', src, dest)
Alex Kleinf0717a62019-12-06 09:45:00 -0700192 # 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 Kleinc05f3d12019-05-29 14:16:21 -0600207@contextlib.contextmanager
Alex Kleinaae49772019-07-26 10:20:50 -0600208def copy_paths_in(message, destination, delete=True, prefix=None):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600209 """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 Kleinf0717a62019-12-06 09:45:00 -0700213 destination (str): The base destination path.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600214 delete (bool): Whether the file(s) should be deleted.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600215 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 Kleinc05f3d12019-05-29 14:16:21 -0600222
Alex Kleinf0717a62019-12-06 09:45:00 -0700223 handlers = _extract_handlers(message, destination, prefix, delete=delete,
224 reset=True)
Alex Kleinaa705412019-06-04 15:00:30 -0600225
226 for handler in handlers:
Alex Kleinaae49772019-07-26 10:20:50 -0600227 handler.transfer(PathHandler.INSIDE)
Alex Kleinaa705412019-06-04 15:00:30 -0600228
229 try:
230 yield handlers
231 finally:
232 for handler in handlers:
233 handler.cleanup()
234
235
Alex Kleinf0717a62019-12-06 09:45:00 -0700236@contextlib.contextmanager
237def 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 Kleinaae49772019-07-26 10:20:50 -0600270def extract_results(request_message, response_message, chroot):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600271 """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 Kleinf0717a62019-12-06 09:45:00 -0700291 handlers = _extract_handlers(response_message, destination, chroot.path,
292 delete=False, reset=False)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600293
294 for handler in handlers:
295 handler.transfer(PathHandler.OUTSIDE)
296 handler.cleanup()
297
298
Alex Kleinf0717a62019-12-06 09:45:00 -0700299def _extract_handlers(message, destination, prefix, delete=False, reset=False,
300 field_name=None, message_type=None):
Alex Kleinaa705412019-06-04 15:00:30 -0600301 """Recursive helper for handle_paths to extract Path messages."""
Alex Kleinf0717a62019-12-06 09:45:00 -0700302 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 Kleinbd6edf82019-07-18 10:30:49 -0600306 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 Kleinf0717a62019-12-06 09:45:00 -0700313 elif is_path_target and isinstance(message, common_pb2.Path):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600314 # 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 Kleinf0717a62019-12-06 09:45:00 -0700322 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 Kleinbd6edf82019-07-18 10:30:49 -0600329
330 # Iterate through each field and recurse.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600331 handlers = []
332 for descriptor in message.DESCRIPTOR.fields:
333 field = getattr(message, descriptor.name)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600334 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 Kleinf0717a62019-12-06 09:45:00 -0700342 _extract_handlers(field, destination, prefix, delete, reset,
343 field_name=new_field_name,
344 message_type=message_type))
Alex Kleinbd6edf82019-07-18 10:30:49 -0600345 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 Kleinc05f3d12019-05-29 14:16:21 -0600351 continue
352
Alex Kleinbd6edf82019-07-18 10:30:49 -0600353 for element in iterator:
354 handlers.extend(
Alex Kleinf0717a62019-12-06 09:45:00 -0700355 _extract_handlers(element, destination, prefix, delete, reset,
356 field_name=new_field_name,
357 message_type=message_type))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600358
Alex Kleinaa705412019-06-04 15:00:30 -0600359 return handlers