blob: 32f7b9813ea327e6a282bd1994b9b8f21674149f [file] [log] [blame]
Alex Klein146d4772019-06-20 13:48:25 -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
Alex Kleine0fa6422019-06-21 12:01:39 -06006"""Router class for the Build API.
7
8Handles routing requests to the appropriate controller and handles service
9registration.
10"""
Alex Klein146d4772019-06-20 13:48:25 -060011
12from __future__ import print_function
13
14import importlib
15import os
Alex Klein146d4772019-06-20 13:48:25 -060016
17from google.protobuf import json_format
18from google.protobuf import symbol_database
19
20from chromite.api import controller
21from chromite.api import field_handler
Alex Klein4de25e82019-08-05 15:58:39 -060022from chromite.api.gen.chromite.api import android_pb2
Alex Klein54e38e32019-06-21 14:54:17 -060023from chromite.api.gen.chromite.api import api_pb2
Alex Klein146d4772019-06-20 13:48:25 -060024from chromite.api.gen.chromite.api import artifacts_pb2
25from chromite.api.gen.chromite.api import binhost_pb2
26from chromite.api.gen.chromite.api import build_api_pb2
27from chromite.api.gen.chromite.api import depgraph_pb2
28from chromite.api.gen.chromite.api import image_pb2
Alex Kleineb77ffa2019-05-28 14:47:44 -060029from chromite.api.gen.chromite.api import packages_pb2
Alex Klein146d4772019-06-20 13:48:25 -060030from chromite.api.gen.chromite.api import sdk_pb2
31from chromite.api.gen.chromite.api import sysroot_pb2
32from chromite.api.gen.chromite.api import test_pb2
Tiancong Wangaf050172019-07-10 11:52:03 -070033from chromite.api.gen.chromite.api import toolchain_pb2
Alex Klein146d4772019-06-20 13:48:25 -060034from chromite.lib import cros_build_lib
35from chromite.lib import cros_logging as logging
36from chromite.lib import osutils
37
38
39class Error(Exception):
40 """Base error class for the module."""
41
42
43class InvalidInputFileError(Error):
44 """Raised when the input file cannot be read."""
45
46
47class InvalidInputFormatError(Error):
48 """Raised when the passed input protobuf can't be parsed."""
49
50
51class InvalidOutputFileError(Error):
52 """Raised when the output file cannot be written."""
53
54
55class CrosSdkNotRunError(Error):
56 """Raised when the cros_sdk command could not be run to enter the chroot."""
57
58
59# API Service Errors.
60class UnknownServiceError(Error):
61 """Error raised when the requested service has not been registered."""
62
63
64class ControllerModuleNotDefinedError(Error):
65 """Error class for when no controller is defined for a service."""
66
67
68class ServiceControllerNotFoundError(Error):
69 """Error raised when the service's controller cannot be imported."""
70
71
72# API Method Errors.
73class UnknownMethodError(Error):
74 """The service is defined in the proto but the method is not."""
75
76
77class MethodNotFoundError(Error):
78 """The method's implementation cannot be found in the service's controller."""
79
80
81class Router(object):
82 """Encapsulates the request dispatching logic."""
83
Alex Kleinbd6edf82019-07-18 10:30:49 -060084 REEXEC_INPUT_FILE = 'input.json'
85 REEXEC_OUTPUT_FILE = 'output.json'
86
Alex Klein146d4772019-06-20 13:48:25 -060087 def __init__(self):
88 self._services = {}
89 self._aliases = {}
90 # All imported generated messages get added to this symbol db.
91 self._sym_db = symbol_database.Default()
92
93 extensions = build_api_pb2.DESCRIPTOR.extensions_by_name
94 self._service_options = extensions['service_options']
95 self._method_options = extensions['method_options']
96
97 def Register(self, proto_module):
98 """Register the services from a generated proto module.
99
100 Args:
101 proto_module (module): The generated proto module whose service is being
102 registered.
103
104 Raises:
105 ServiceModuleNotDefinedError when the service cannot be found in the
106 provided module.
107 """
108 services = proto_module.DESCRIPTOR.services_by_name
109 for service_name, svc in services.items():
110 module_name = svc.GetOptions().Extensions[self._service_options].module
111
112 if not module_name:
113 raise ControllerModuleNotDefinedError(
114 'The module must be defined in the service definition: %s.%s' %
115 (proto_module, service_name))
116
117 self._services[svc.full_name] = (svc, module_name)
118
119 def ListMethods(self):
120 """List all methods registered with the router."""
121 services = []
122 for service_name, (svc, _module) in self._services.items():
123 for method_name in svc.methods_by_name.keys():
124 services.append('%s/%s' % (service_name, method_name))
125
126 return sorted(services)
127
Alex Klein69339cc2019-07-22 14:08:35 -0600128 def Route(self, service_name, method_name, input_path, output_path, config):
Alex Klein146d4772019-06-20 13:48:25 -0600129 """Dispatch the request.
130
131 Args:
132 service_name (str): The fully qualified service name.
133 method_name (str): The name of the method being called.
134 input_path (str): The path to the input message file.
135 output_path (str): The path where the output message should be written.
Alex Klein69339cc2019-07-22 14:08:35 -0600136 config (api_config.ApiConfig): The optional call configs.
Alex Klein146d4772019-06-20 13:48:25 -0600137
138 Returns:
139 int: The return code.
140
141 Raises:
142 InvalidInputFileError when the input file cannot be read.
143 InvalidOutputFileError when the output file cannot be written.
144 ServiceModuleNotFoundError when the service module cannot be imported.
145 MethodNotFoundError when the method cannot be retrieved from the module.
146 """
147 try:
148 input_json = osutils.ReadFile(input_path).strip()
149 except IOError as e:
Mike Frysinger6b5c3cd2019-08-27 16:51:00 -0400150 raise InvalidInputFileError('Unable to read input file: %s' % e)
Alex Klein146d4772019-06-20 13:48:25 -0600151
152 try:
153 svc, module_name = self._services[service_name]
154 except KeyError:
155 raise UnknownServiceError('The %s service has not been registered.'
156 % service_name)
157
158 try:
159 method_desc = svc.methods_by_name[method_name]
160 except KeyError:
161 raise UnknownMethodError('The %s method has not been defined in the %s '
162 'service.' % (method_name, service_name))
163
164 # Parse the input file to build an instance of the input message.
165 input_msg = self._sym_db.GetPrototype(method_desc.input_type)()
166 try:
167 json_format.Parse(input_json, input_msg, ignore_unknown_fields=True)
168 except json_format.ParseError as e:
Mike Frysinger6b5c3cd2019-08-27 16:51:00 -0400169 raise InvalidInputFormatError('Unable to parse the input json: %s' % e)
Alex Klein146d4772019-06-20 13:48:25 -0600170
171 # Get an empty output message instance.
172 output_msg = self._sym_db.GetPrototype(method_desc.output_type)()
173
Alex Kleinbd6edf82019-07-18 10:30:49 -0600174 # Fetch the method options for chroot and method name overrides.
Alex Klein146d4772019-06-20 13:48:25 -0600175 method_options = method_desc.GetOptions().Extensions[self._method_options]
Alex Klein146d4772019-06-20 13:48:25 -0600176
177 # Check the chroot settings before running.
178 service_options = svc.GetOptions().Extensions[self._service_options]
179 if self._ChrootCheck(service_options, method_options):
180 # Run inside the chroot instead.
181 logging.info('Re-executing the endpoint inside the chroot.')
Alex Kleinbd6edf82019-07-18 10:30:49 -0600182 return self._ReexecuteInside(input_msg, output_msg, output_path,
Alex Klein69339cc2019-07-22 14:08:35 -0600183 service_name, method_name, config)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600184
185 # Allow proto-based method name override.
186 if method_options.HasField('implementation_name'):
187 method_name = method_options.implementation_name
Alex Klein146d4772019-06-20 13:48:25 -0600188
189 # Import the module and get the method.
190 method_impl = self._GetMethod(module_name, method_name)
191
192 # Successfully located; call and return.
Alex Klein69339cc2019-07-22 14:08:35 -0600193 return_code = method_impl(input_msg, output_msg, config)
Alex Klein146d4772019-06-20 13:48:25 -0600194 if return_code is None:
195 return_code = controller.RETURN_CODE_SUCCESS
196
197 try:
198 osutils.WriteFile(output_path, json_format.MessageToJson(output_msg))
199 except IOError as e:
Mike Frysinger6b5c3cd2019-08-27 16:51:00 -0400200 raise InvalidOutputFileError('Cannot write output file: %s' % e)
Alex Klein146d4772019-06-20 13:48:25 -0600201
202 return return_code
203
204 def _ChrootCheck(self, service_options, method_options):
205 """Check the chroot options, and execute assertion or note reexec as needed.
206
207 Args:
208 service_options (google.protobuf.Message): The service options.
209 method_options (google.protobuf.Message): The method options.
210
211 Returns:
212 bool - True iff it needs to be reexeced inside the chroot.
213
214 Raises:
215 cros_build_lib.DieSystemExit when the chroot setting cannot be satisfied.
216 """
217 chroot_assert = build_api_pb2.NO_ASSERTION
218 if method_options.HasField('method_chroot_assert'):
219 # Prefer the method option when set.
220 chroot_assert = method_options.method_chroot_assert
221 elif service_options.HasField('service_chroot_assert'):
222 # Fall back to the service option.
223 chroot_assert = service_options.service_chroot_assert
224
225 if chroot_assert == build_api_pb2.INSIDE:
226 return not cros_build_lib.IsInsideChroot()
227 elif chroot_assert == build_api_pb2.OUTSIDE:
228 # If it must be run outside we have to already be outside.
229 cros_build_lib.AssertOutsideChroot()
230
231 return False
232
Alex Kleinbd6edf82019-07-18 10:30:49 -0600233 def _ReexecuteInside(self, input_msg, output_msg, output_path, service_name,
Alex Klein69339cc2019-07-22 14:08:35 -0600234 method_name, config):
Alex Klein146d4772019-06-20 13:48:25 -0600235 """Re-execute the service inside the chroot.
236
237 Args:
238 input_msg (Message): The parsed input message.
Alex Kleinbd6edf82019-07-18 10:30:49 -0600239 output_msg (Message): The empty output message instance.
Alex Klein146d4772019-06-20 13:48:25 -0600240 output_path (str): The path for the serialized output.
241 service_name (str): The name of the service to run.
242 method_name (str): The name of the method to run.
Alex Klein69339cc2019-07-22 14:08:35 -0600243 config (api_config.ApiConfig): The optional call configs.
Alex Klein146d4772019-06-20 13:48:25 -0600244 """
245 # Parse the chroot and clear the chroot field in the input message.
246 chroot = field_handler.handle_chroot(input_msg)
247
Alex Kleinaae49772019-07-26 10:20:50 -0600248 with field_handler.copy_paths_in(input_msg, chroot.tmp, prefix=chroot.path):
249 with chroot.tempdir() as tempdir:
Alex Kleinbd6edf82019-07-18 10:30:49 -0600250 new_input = os.path.join(tempdir, self.REEXEC_INPUT_FILE)
Alex Klein146d4772019-06-20 13:48:25 -0600251 chroot_input = '/%s' % os.path.relpath(new_input, chroot.path)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600252 new_output = os.path.join(tempdir, self.REEXEC_OUTPUT_FILE)
Alex Klein146d4772019-06-20 13:48:25 -0600253 chroot_output = '/%s' % os.path.relpath(new_output, chroot.path)
254
255 logging.info('Writing input message to: %s', new_input)
256 osutils.WriteFile(new_input, json_format.MessageToJson(input_msg))
257 osutils.Touch(new_output)
258
259 cmd = ['build_api', '%s/%s' % (service_name, method_name),
260 '--input-json', chroot_input, '--output-json', chroot_output]
261
Alex Klein69339cc2019-07-22 14:08:35 -0600262 if config.validate_only:
263 cmd.append('--validate-only')
264
Alex Klein146d4772019-06-20 13:48:25 -0600265 try:
Mike Frysinger45602c72019-09-22 02:15:11 -0400266 result = cros_build_lib.run(
Alex Klein8ee44b42019-09-24 14:59:32 -0600267 cmd,
268 enter_chroot=True,
269 chroot_args=chroot.get_enter_args(),
270 error_code_ok=True,
271 extra_env=chroot.env)
Alex Klein146d4772019-06-20 13:48:25 -0600272 except cros_build_lib.RunCommandError:
273 # A non-zero return code will not result in an error, but one is still
274 # thrown when the command cannot be run in the first place. This is
275 # known to happen at least when the PATH does not include the chromite
276 # bin dir.
277 raise CrosSdkNotRunError('Unable to enter the chroot.')
278
279 logging.info('Endpoint execution completed, return code: %d',
280 result.returncode)
281
Alex Kleinbd6edf82019-07-18 10:30:49 -0600282 # Transfer result files out of the chroot.
283 output_content = osutils.ReadFile(new_output)
284 if output_content:
285 json_format.Parse(output_content, output_msg)
Alex Kleinaae49772019-07-26 10:20:50 -0600286 field_handler.extract_results(input_msg, output_msg, chroot)
Alex Kleinbd6edf82019-07-18 10:30:49 -0600287
288 osutils.WriteFile(output_path, json_format.MessageToJson(output_msg))
Alex Klein146d4772019-06-20 13:48:25 -0600289
290 return result.returncode
291
Alex Klein146d4772019-06-20 13:48:25 -0600292 def _GetMethod(self, module_name, method_name):
293 """Get the implementation of the method for the service module.
294
295 Args:
296 module_name (str): The name of the service module.
297 method_name (str): The name of the method.
298
299 Returns:
300 callable - The method.
301
302 Raises:
303 MethodNotFoundError when the method cannot be found in the module.
304 ServiceModuleNotFoundError when the service module cannot be imported.
305 """
306 try:
307 module = importlib.import_module(controller.IMPORT_PATTERN % module_name)
308 except ImportError as e:
Mike Frysinger6b5c3cd2019-08-27 16:51:00 -0400309 raise ServiceControllerNotFoundError(str(e))
Alex Klein146d4772019-06-20 13:48:25 -0600310 try:
311 return getattr(module, method_name)
312 except AttributeError as e:
Mike Frysinger6b5c3cd2019-08-27 16:51:00 -0400313 raise MethodNotFoundError(str(e))
Alex Klein146d4772019-06-20 13:48:25 -0600314
315
316def RegisterServices(router):
317 """Register all the services.
318
319 Args:
320 router (Router): The router.
321 """
Alex Klein4de25e82019-08-05 15:58:39 -0600322 router.Register(android_pb2)
Alex Klein54e38e32019-06-21 14:54:17 -0600323 router.Register(api_pb2)
Alex Klein146d4772019-06-20 13:48:25 -0600324 router.Register(artifacts_pb2)
325 router.Register(binhost_pb2)
326 router.Register(depgraph_pb2)
327 router.Register(image_pb2)
Alex Kleineb77ffa2019-05-28 14:47:44 -0600328 router.Register(packages_pb2)
Alex Klein146d4772019-06-20 13:48:25 -0600329 router.Register(sdk_pb2)
330 router.Register(sysroot_pb2)
331 router.Register(test_pb2)
Tiancong Wangaf050172019-07-10 11:52:03 -0700332 router.Register(toolchain_pb2)
Alex Klein146d4772019-06-20 13:48:25 -0600333 logging.debug('Services registered successfully.')
334
335
336def GetRouter():
337 """Get a router that has had all of the services registered."""
338 router = Router()
339 RegisterServices(router)
340
341 return router