Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2018 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 | """The build API entry point.""" |
| 7 | |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | import importlib |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 11 | import os |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 12 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 13 | from google.protobuf import json_format |
| 14 | from google.protobuf import symbol_database |
| 15 | |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 16 | from chromite.api import controller |
Evan Hernandez | aeb556a | 2019-04-03 11:28:49 -0600 | [diff] [blame] | 17 | from chromite.api.gen.chromite.api import artifacts_pb2 |
| 18 | from chromite.api.gen.chromite.api import binhost_pb2 |
Alex Klein | 7107bdd | 2019-03-14 17:14:31 -0600 | [diff] [blame] | 19 | from chromite.api.gen.chromite.api import build_api_pb2 |
| 20 | from chromite.api.gen.chromite.api import depgraph_pb2 |
| 21 | from chromite.api.gen.chromite.api import image_pb2 |
| 22 | from chromite.api.gen.chromite.api import sdk_pb2 |
Alex Klein | d4e1e42 | 2019-03-18 16:00:41 -0600 | [diff] [blame] | 23 | from chromite.api.gen.chromite.api import sysroot_pb2 |
Alex Klein | c5403d6 | 2019-04-03 09:34:59 -0600 | [diff] [blame] | 24 | from chromite.api.gen.chromite.api import test_pb2 |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 25 | from chromite.lib import commandline |
Alex Klein | 2bfacb2 | 2019-02-04 11:42:17 -0700 | [diff] [blame] | 26 | from chromite.lib import cros_build_lib |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 27 | from chromite.lib import osutils |
Alex Klein | 00b1f1e | 2019-02-08 13:53:42 -0700 | [diff] [blame] | 28 | from chromite.utils import matching |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 29 | |
| 30 | |
| 31 | class Error(Exception): |
| 32 | """Base error class for the module.""" |
| 33 | |
| 34 | |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 35 | class InvalidInputFileError(Error): |
| 36 | """Raised when the input file cannot be read.""" |
| 37 | |
| 38 | |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 39 | class InvalidInputFormatError(Error): |
| 40 | """Raised when the passed input protobuf can't be parsed.""" |
| 41 | |
| 42 | |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 43 | class InvalidOutputFileError(Error): |
| 44 | """Raised when the output file cannot be written.""" |
| 45 | |
| 46 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 47 | # API Service Errors. |
| 48 | class UnknownServiceError(Error): |
| 49 | """Error raised when the requested service has not been registered.""" |
| 50 | |
| 51 | |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 52 | class ControllerModuleNotDefinedError(Error): |
| 53 | """Error class for when no controller is defined for a service.""" |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 54 | |
| 55 | |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 56 | class ServiceControllerNotFoundError(Error): |
| 57 | """Error raised when the service's controller cannot be imported.""" |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 58 | |
| 59 | |
| 60 | # API Method Errors. |
| 61 | class UnknownMethodError(Error): |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 62 | """The service is defined in the proto but the method is not.""" |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 63 | |
| 64 | |
| 65 | class MethodNotFoundError(Error): |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 66 | """The method's implementation cannot be found in the service's controller.""" |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 67 | |
| 68 | |
| 69 | def GetParser(): |
Alex Klein | 00b1f1e | 2019-02-08 13:53:42 -0700 | [diff] [blame] | 70 | """Build the argument parser.""" |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 71 | parser = commandline.ArgumentParser(description=__doc__) |
| 72 | |
| 73 | parser.add_argument('service_method', |
| 74 | help='The "chromite.api.Service/Method" that is being ' |
| 75 | 'called.') |
| 76 | |
| 77 | parser.add_argument( |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 78 | '--input-json', type='path', required=True, |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 79 | help='Path to the JSON serialized input argument protobuf message.') |
| 80 | parser.add_argument( |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 81 | '--output-json', type='path', required=True, |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 82 | help='The path to which the result protobuf message should be written.') |
| 83 | |
| 84 | return parser |
| 85 | |
| 86 | |
Alex Klein | 00b1f1e | 2019-02-08 13:53:42 -0700 | [diff] [blame] | 87 | def _ParseArgs(argv, router): |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 88 | """Parse and validate arguments.""" |
| 89 | parser = GetParser() |
| 90 | opts = parser.parse_args(argv) |
| 91 | |
Alex Klein | 00b1f1e | 2019-02-08 13:53:42 -0700 | [diff] [blame] | 92 | methods = router.ListMethods() |
| 93 | if opts.service_method not in methods: |
| 94 | matched = matching.GetMostLikelyMatchedObject(methods, opts.service_method, |
| 95 | matched_score_threshold=0.6) |
| 96 | error = 'Unrecognized service name.' |
| 97 | if matched: |
| 98 | error += '\nDid you mean: \n%s' % '\n'.join(matched) |
| 99 | parser.error(error) |
| 100 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 101 | parts = opts.service_method.split('/') |
| 102 | |
| 103 | if len(parts) != 2: |
| 104 | parser.error('Must pass "Service/Method".') |
| 105 | |
| 106 | opts.service = parts[0] |
| 107 | opts.method = parts[1] |
| 108 | |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 109 | if not os.path.exists(opts.input_json): |
| 110 | parser.error('Input file does not exist.') |
| 111 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 112 | opts.Freeze() |
| 113 | return opts |
| 114 | |
| 115 | |
| 116 | class Router(object): |
| 117 | """Encapsulates the request dispatching logic.""" |
| 118 | |
| 119 | def __init__(self): |
| 120 | self._services = {} |
| 121 | self._aliases = {} |
| 122 | # All imported generated messages get added to this symbol db. |
| 123 | self._sym_db = symbol_database.Default() |
| 124 | |
| 125 | extensions = build_api_pb2.DESCRIPTOR.extensions_by_name |
| 126 | self._service_options = extensions['service_options'] |
| 127 | self._method_options = extensions['method_options'] |
| 128 | |
| 129 | def Register(self, proto_module): |
| 130 | """Register the services from a generated proto module. |
| 131 | |
| 132 | Args: |
| 133 | proto_module (module): The generated proto module whose service is being |
| 134 | registered. |
| 135 | |
| 136 | Raises: |
| 137 | ServiceModuleNotDefinedError when the service cannot be found in the |
| 138 | provided module. |
| 139 | """ |
| 140 | services = proto_module.DESCRIPTOR.services_by_name |
| 141 | for service_name, svc in services.items(): |
| 142 | module_name = svc.GetOptions().Extensions[self._service_options].module |
| 143 | |
| 144 | if not module_name: |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 145 | raise ControllerModuleNotDefinedError( |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 146 | 'The module must be defined in the service definition: %s.%s' % |
| 147 | (proto_module, service_name)) |
| 148 | |
| 149 | self._services[svc.full_name] = (svc, module_name) |
| 150 | |
Alex Klein | 00b1f1e | 2019-02-08 13:53:42 -0700 | [diff] [blame] | 151 | def ListMethods(self): |
| 152 | """List all methods registered with the router.""" |
| 153 | services = [] |
| 154 | for service_name, (svc, _module) in self._services.items(): |
| 155 | for method_name in svc.methods_by_name.keys(): |
| 156 | services.append('%s/%s' % (service_name, method_name)) |
| 157 | |
| 158 | return sorted(services) |
| 159 | |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 160 | def Route(self, service_name, method_name, input_path, output_path): |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 161 | """Dispatch the request. |
| 162 | |
| 163 | Args: |
| 164 | service_name (str): The fully qualified service name. |
| 165 | method_name (str): The name of the method being called. |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 166 | input_path (str): The path to the input message file. |
| 167 | output_path (str): The path where the output message should be written. |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 168 | |
| 169 | Returns: |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 170 | int: The return code. |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 171 | |
| 172 | Raises: |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 173 | InvalidInputFileError when the input file cannot be read. |
| 174 | InvalidOutputFileError when the output file cannot be written. |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 175 | ServiceModuleNotFoundError when the service module cannot be imported. |
| 176 | MethodNotFoundError when the method cannot be retrieved from the module. |
| 177 | """ |
| 178 | try: |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 179 | input_json = osutils.ReadFile(input_path) |
| 180 | except IOError as e: |
| 181 | raise InvalidInputFileError('Unable to read input file: %s' % e.message) |
| 182 | |
| 183 | try: |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 184 | svc, module_name = self._services[service_name] |
| 185 | except KeyError: |
| 186 | raise UnknownServiceError('The %s service has not been registered.' |
| 187 | % service_name) |
| 188 | |
| 189 | try: |
| 190 | method_desc = svc.methods_by_name[method_name] |
| 191 | except KeyError: |
| 192 | raise UnknownMethodError('The %s method has not been defined in the %s ' |
| 193 | 'service.' % (method_name, service_name)) |
| 194 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 195 | # Parse the input file to build an instance of the input message. |
| 196 | input_msg = self._sym_db.GetPrototype(method_desc.input_type)() |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 197 | try: |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 198 | json_format.Parse(input_json, input_msg, ignore_unknown_fields=True) |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 199 | except json_format.ParseError as e: |
| 200 | raise InvalidInputFormatError( |
| 201 | 'Unable to parse the input json: %s' % e.message) |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 202 | |
| 203 | # Get an empty output message instance. |
| 204 | output_msg = self._sym_db.GetPrototype(method_desc.output_type)() |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 205 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 206 | # Allow proto-based method name override. |
| 207 | method_options = method_desc.GetOptions().Extensions[self._method_options] |
| 208 | if method_options.HasField('implementation_name'): |
| 209 | method_name = method_options.implementation_name |
| 210 | |
Alex Klein | 2bfacb2 | 2019-02-04 11:42:17 -0700 | [diff] [blame] | 211 | # Check the chroot assertion settings before running. |
| 212 | service_options = svc.GetOptions().Extensions[self._service_options] |
| 213 | self._HandleChrootAssert(service_options, method_options) |
| 214 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 215 | # Import the module and get the method. |
| 216 | method_impl = self._GetMethod(module_name, method_name) |
| 217 | |
| 218 | # Successfully located; call and return. |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 219 | return_code = method_impl(input_msg, output_msg) |
| 220 | if return_code is None: |
| 221 | return_code = 0 |
| 222 | |
| 223 | try: |
| 224 | osutils.WriteFile(output_path, json_format.MessageToJson(output_msg)) |
| 225 | except IOError as e: |
| 226 | raise InvalidOutputFileError('Cannot write output file: %s' % e.message) |
| 227 | |
| 228 | return return_code |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 229 | |
Alex Klein | 2bfacb2 | 2019-02-04 11:42:17 -0700 | [diff] [blame] | 230 | def _HandleChrootAssert(self, service_options, method_options): |
| 231 | """Check the chroot assert options and execute assertion as needed. |
| 232 | |
| 233 | Args: |
| 234 | service_options (google.protobuf.Message): The service options. |
| 235 | method_options (google.protobuf.Message): The method options. |
| 236 | """ |
| 237 | chroot_assert = build_api_pb2.NO_ASSERTION |
| 238 | if method_options.HasField('method_chroot_assert'): |
| 239 | # Prefer the method option when set. |
| 240 | chroot_assert = method_options.method_chroot_assert |
| 241 | elif service_options.HasField('service_chroot_assert'): |
| 242 | # Fall back to the service option. |
| 243 | chroot_assert = service_options.service_chroot_assert |
| 244 | |
| 245 | # Execute appropriate assertion if set. |
| 246 | if chroot_assert == build_api_pb2.INSIDE: |
| 247 | cros_build_lib.AssertInsideChroot() |
| 248 | elif chroot_assert == build_api_pb2.OUTSIDE: |
| 249 | cros_build_lib.AssertOutsideChroot() |
| 250 | |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 251 | def _GetMethod(self, module_name, method_name): |
| 252 | """Get the implementation of the method for the service module. |
| 253 | |
| 254 | Args: |
| 255 | module_name (str): The name of the service module. |
| 256 | method_name (str): The name of the method. |
| 257 | |
| 258 | Returns: |
| 259 | callable - The method. |
| 260 | |
| 261 | Raises: |
| 262 | MethodNotFoundError when the method cannot be found in the module. |
| 263 | ServiceModuleNotFoundError when the service module cannot be imported. |
| 264 | """ |
| 265 | try: |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 266 | module = importlib.import_module(controller.IMPORT_PATTERN % module_name) |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 267 | except ImportError as e: |
Alex Klein | b7cdbe6 | 2019-02-22 11:41:32 -0700 | [diff] [blame] | 268 | raise ServiceControllerNotFoundError(e.message) |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 269 | try: |
| 270 | return getattr(module, method_name) |
| 271 | except AttributeError as e: |
| 272 | raise MethodNotFoundError(e.message) |
| 273 | |
| 274 | |
| 275 | def RegisterServices(router): |
| 276 | """Register all the services. |
| 277 | |
| 278 | Args: |
| 279 | router (Router): The router. |
| 280 | """ |
Evan Hernandez | aeb556a | 2019-04-03 11:28:49 -0600 | [diff] [blame] | 281 | router.Register(artifacts_pb2) |
| 282 | router.Register(binhost_pb2) |
Ned Nguyen | 9a7a905 | 2019-02-05 11:04:03 -0700 | [diff] [blame] | 283 | router.Register(depgraph_pb2) |
Alex Klein | 2966e30 | 2019-01-17 13:29:38 -0700 | [diff] [blame] | 284 | router.Register(image_pb2) |
Alex Klein | 19c4cc4 | 2019-02-27 14:47:57 -0700 | [diff] [blame] | 285 | router.Register(sdk_pb2) |
Alex Klein | d4e1e42 | 2019-03-18 16:00:41 -0600 | [diff] [blame] | 286 | router.Register(sysroot_pb2) |
Alex Klein | c5403d6 | 2019-04-03 09:34:59 -0600 | [diff] [blame] | 287 | router.Register(test_pb2) |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 288 | |
| 289 | |
| 290 | def main(argv): |
Alex Klein | f4dc4f5 | 2018-12-05 13:55:12 -0700 | [diff] [blame] | 291 | router = Router() |
| 292 | RegisterServices(router) |
| 293 | |
Alex Klein | 00b1f1e | 2019-02-08 13:53:42 -0700 | [diff] [blame] | 294 | opts = _ParseArgs(argv, router) |
| 295 | |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 296 | try: |
Alex Klein | 5bcb4d2 | 2019-03-21 13:51:54 -0600 | [diff] [blame] | 297 | return router.Route(opts.service, opts.method, opts.input_json, |
| 298 | opts.output_json) |
Alex Klein | 7a11517 | 2019-02-08 14:14:20 -0700 | [diff] [blame] | 299 | except Error as e: |
| 300 | # Error derivatives are handled nicely, but let anything else bubble up. |
| 301 | cros_build_lib.Die(e.message) |