blob: e6c14184b0f87eb5ce80d959e859478961cce964 [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
Alex Klein38c7d9e2019-05-08 09:31:19 -060019from chromite.api.controller import controller_util
Alex Kleinc05f3d12019-05-29 14:16:21 -060020from chromite.api.gen.chromiumos import common_pb2
Alex Kleinc05f3d12019-05-29 14:16:21 -060021from chromite.lib import cros_logging as logging
22from chromite.lib import osutils
23
Alex Kleinaa705412019-06-04 15:00:30 -060024from google.protobuf import message as protobuf_message
25
Alex Kleinc05f3d12019-05-29 14:16:21 -060026
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
169@contextlib.contextmanager
Alex Kleinaae49772019-07-26 10:20:50 -0600170def copy_paths_in(message, destination, delete=True, prefix=None):
Alex Kleinc05f3d12019-05-29 14:16:21 -0600171 """Context manager function to transfer and cleanup all Path messages.
172
173 Args:
174 message (Message): A message whose Path messages should be transferred.
175 destination (str): A base destination path.
176 delete (bool): Whether the file(s) should be deleted.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600177 prefix (str|None): A prefix path to remove from the final destination path
178 in the Path message (i.e. remove the chroot path).
179
180 Returns:
181 list[PathHandler]: The path handlers.
182 """
183 assert destination
Alex Kleinc05f3d12019-05-29 14:16:21 -0600184
Alex Kleinbd6edf82019-07-18 10:30:49 -0600185 handlers = _extract_handlers(message, destination, delete, prefix, reset=True)
Alex Kleinaa705412019-06-04 15:00:30 -0600186
187 for handler in handlers:
Alex Kleinaae49772019-07-26 10:20:50 -0600188 handler.transfer(PathHandler.INSIDE)
Alex Kleinaa705412019-06-04 15:00:30 -0600189
190 try:
191 yield handlers
192 finally:
193 for handler in handlers:
194 handler.cleanup()
195
196
Alex Kleinaae49772019-07-26 10:20:50 -0600197def extract_results(request_message, response_message, chroot):
Alex Kleinbd6edf82019-07-18 10:30:49 -0600198 """Transfer all response Path messages to the request's ResultPath.
199
200 Args:
201 request_message (Message): The request message containing a ResultPath
202 message.
203 response_message (Message): The response message whose Path message(s)
204 are to be transferred.
205 chroot (chroot_lib.Chroot): The chroot the files are being copied out of.
206 """
207 # Find the ResultPath.
208 for descriptor in request_message.DESCRIPTOR.fields:
209 field = getattr(request_message, descriptor.name)
210 if isinstance(field, common_pb2.ResultPath):
211 result_path_message = field
212 break
213 else:
214 # No ResultPath to handle.
215 return
216
217 destination = result_path_message.path.path
218 handlers = _extract_handlers(response_message, destination, delete=False,
219 prefix=chroot.path, reset=False)
220
221 for handler in handlers:
222 handler.transfer(PathHandler.OUTSIDE)
223 handler.cleanup()
224
225
226def _extract_handlers(message, destination, delete, prefix, reset,
227 field_name=None):
Alex Kleinaa705412019-06-04 15:00:30 -0600228 """Recursive helper for handle_paths to extract Path messages."""
Alex Kleinbd6edf82019-07-18 10:30:49 -0600229 is_message = isinstance(message, protobuf_message.Message)
230 is_result_path = isinstance(message, common_pb2.ResultPath)
231 if not is_message or is_result_path:
232 # Base case: Nothing to handle.
233 # There's nothing we can do with scalar values.
234 # Skip ResultPath instances to avoid unnecessary file copying.
235 return []
236 elif isinstance(message, common_pb2.Path):
237 # Base case: Create handler for this message.
238 if not message.path or not message.location:
239 logging.debug('Skipping %s; incomplete.', field_name or 'message')
240 return []
241
242 handler = PathHandler(message, destination, delete=delete, prefix=prefix,
243 reset=reset)
244 return [handler]
245
246 # Iterate through each field and recurse.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600247 handlers = []
248 for descriptor in message.DESCRIPTOR.fields:
249 field = getattr(message, descriptor.name)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600250 if field_name:
251 new_field_name = '%s.%s' % (field_name, descriptor.name)
252 else:
253 new_field_name = descriptor.name
254
255 if isinstance(field, protobuf_message.Message):
256 # Recurse for nested Paths.
257 handlers.extend(
258 _extract_handlers(field, destination, delete, prefix, reset,
259 field_name=new_field_name))
260 else:
261 # If it's iterable it may be a repeated field, try each element.
262 try:
263 iterator = iter(field)
264 except TypeError:
265 # Definitely not a repeated field, just move on.
Alex Kleinc05f3d12019-05-29 14:16:21 -0600266 continue
267
Alex Kleinbd6edf82019-07-18 10:30:49 -0600268 for element in iterator:
269 handlers.extend(
270 _extract_handlers(element, destination, delete, prefix, reset,
271 field_name=new_field_name))
Alex Kleinc05f3d12019-05-29 14:16:21 -0600272
Alex Kleinaa705412019-06-04 15:00:30 -0600273 return handlers