blob: 9f41400b0d68d2e0993973bd189ee7f5a6cdfd35 [file] [log] [blame]
Alex Kleinf4dc4f52018-12-05 13:55:12 -07001# -*- 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
8from __future__ import print_function
9
10import importlib
Alex Klein5bcb4d22019-03-21 13:51:54 -060011import os
Alex Kleinf4dc4f52018-12-05 13:55:12 -070012
Alex Kleinf4dc4f52018-12-05 13:55:12 -070013from google.protobuf import json_format
14from google.protobuf import symbol_database
15
Alex Kleinb7cdbe62019-02-22 11:41:32 -070016from chromite.api import controller
Alex Klein7107bdd2019-03-14 17:14:31 -060017from chromite.api.gen.chromite.api import build_api_pb2
18from chromite.api.gen.chromite.api import depgraph_pb2
19from chromite.api.gen.chromite.api import image_pb2
20from chromite.api.gen.chromite.api import sdk_pb2
21from chromite.api.gen.chromite.api import test_archive_pb2
Alex Kleinf4dc4f52018-12-05 13:55:12 -070022from chromite.lib import commandline
Alex Klein2bfacb22019-02-04 11:42:17 -070023from chromite.lib import cros_build_lib
Alex Kleinf4dc4f52018-12-05 13:55:12 -070024from chromite.lib import osutils
Alex Klein00b1f1e2019-02-08 13:53:42 -070025from chromite.utils import matching
Alex Kleinf4dc4f52018-12-05 13:55:12 -070026
27
28class Error(Exception):
29 """Base error class for the module."""
30
31
Alex Klein5bcb4d22019-03-21 13:51:54 -060032class InvalidInputFileError(Error):
33 """Raised when the input file cannot be read."""
34
35
Alex Klein7a115172019-02-08 14:14:20 -070036class InvalidInputFormatError(Error):
37 """Raised when the passed input protobuf can't be parsed."""
38
39
Alex Klein5bcb4d22019-03-21 13:51:54 -060040class InvalidOutputFileError(Error):
41 """Raised when the output file cannot be written."""
42
43
Alex Kleinf4dc4f52018-12-05 13:55:12 -070044# API Service Errors.
45class UnknownServiceError(Error):
46 """Error raised when the requested service has not been registered."""
47
48
Alex Kleinb7cdbe62019-02-22 11:41:32 -070049class ControllerModuleNotDefinedError(Error):
50 """Error class for when no controller is defined for a service."""
Alex Kleinf4dc4f52018-12-05 13:55:12 -070051
52
Alex Kleinb7cdbe62019-02-22 11:41:32 -070053class ServiceControllerNotFoundError(Error):
54 """Error raised when the service's controller cannot be imported."""
Alex Kleinf4dc4f52018-12-05 13:55:12 -070055
56
57# API Method Errors.
58class UnknownMethodError(Error):
Alex Kleinb7cdbe62019-02-22 11:41:32 -070059 """The service is defined in the proto but the method is not."""
Alex Kleinf4dc4f52018-12-05 13:55:12 -070060
61
62class MethodNotFoundError(Error):
Alex Kleinb7cdbe62019-02-22 11:41:32 -070063 """The method's implementation cannot be found in the service's controller."""
Alex Kleinf4dc4f52018-12-05 13:55:12 -070064
65
66def GetParser():
Alex Klein00b1f1e2019-02-08 13:53:42 -070067 """Build the argument parser."""
Alex Kleinf4dc4f52018-12-05 13:55:12 -070068 parser = commandline.ArgumentParser(description=__doc__)
69
70 parser.add_argument('service_method',
71 help='The "chromite.api.Service/Method" that is being '
72 'called.')
73
74 parser.add_argument(
Alex Klein7a115172019-02-08 14:14:20 -070075 '--input-json', type='path', required=True,
Alex Kleinf4dc4f52018-12-05 13:55:12 -070076 help='Path to the JSON serialized input argument protobuf message.')
77 parser.add_argument(
Alex Klein7a115172019-02-08 14:14:20 -070078 '--output-json', type='path', required=True,
Alex Kleinf4dc4f52018-12-05 13:55:12 -070079 help='The path to which the result protobuf message should be written.')
80
81 return parser
82
83
Alex Klein00b1f1e2019-02-08 13:53:42 -070084def _ParseArgs(argv, router):
Alex Kleinf4dc4f52018-12-05 13:55:12 -070085 """Parse and validate arguments."""
86 parser = GetParser()
87 opts = parser.parse_args(argv)
88
Alex Klein00b1f1e2019-02-08 13:53:42 -070089 methods = router.ListMethods()
90 if opts.service_method not in methods:
91 matched = matching.GetMostLikelyMatchedObject(methods, opts.service_method,
92 matched_score_threshold=0.6)
93 error = 'Unrecognized service name.'
94 if matched:
95 error += '\nDid you mean: \n%s' % '\n'.join(matched)
96 parser.error(error)
97
Alex Kleinf4dc4f52018-12-05 13:55:12 -070098 parts = opts.service_method.split('/')
99
100 if len(parts) != 2:
101 parser.error('Must pass "Service/Method".')
102
103 opts.service = parts[0]
104 opts.method = parts[1]
105
Alex Klein5bcb4d22019-03-21 13:51:54 -0600106 if not os.path.exists(opts.input_json):
107 parser.error('Input file does not exist.')
108
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700109 opts.Freeze()
110 return opts
111
112
113class Router(object):
114 """Encapsulates the request dispatching logic."""
115
116 def __init__(self):
117 self._services = {}
118 self._aliases = {}
119 # All imported generated messages get added to this symbol db.
120 self._sym_db = symbol_database.Default()
121
122 extensions = build_api_pb2.DESCRIPTOR.extensions_by_name
123 self._service_options = extensions['service_options']
124 self._method_options = extensions['method_options']
125
126 def Register(self, proto_module):
127 """Register the services from a generated proto module.
128
129 Args:
130 proto_module (module): The generated proto module whose service is being
131 registered.
132
133 Raises:
134 ServiceModuleNotDefinedError when the service cannot be found in the
135 provided module.
136 """
137 services = proto_module.DESCRIPTOR.services_by_name
138 for service_name, svc in services.items():
139 module_name = svc.GetOptions().Extensions[self._service_options].module
140
141 if not module_name:
Alex Kleinb7cdbe62019-02-22 11:41:32 -0700142 raise ControllerModuleNotDefinedError(
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700143 'The module must be defined in the service definition: %s.%s' %
144 (proto_module, service_name))
145
146 self._services[svc.full_name] = (svc, module_name)
147
Alex Klein00b1f1e2019-02-08 13:53:42 -0700148 def ListMethods(self):
149 """List all methods registered with the router."""
150 services = []
151 for service_name, (svc, _module) in self._services.items():
152 for method_name in svc.methods_by_name.keys():
153 services.append('%s/%s' % (service_name, method_name))
154
155 return sorted(services)
156
Alex Klein5bcb4d22019-03-21 13:51:54 -0600157 def Route(self, service_name, method_name, input_path, output_path):
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700158 """Dispatch the request.
159
160 Args:
161 service_name (str): The fully qualified service name.
162 method_name (str): The name of the method being called.
Alex Klein5bcb4d22019-03-21 13:51:54 -0600163 input_path (str): The path to the input message file.
164 output_path (str): The path where the output message should be written.
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700165
166 Returns:
Alex Klein5bcb4d22019-03-21 13:51:54 -0600167 int: The return code.
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700168
169 Raises:
Alex Klein5bcb4d22019-03-21 13:51:54 -0600170 InvalidInputFileError when the input file cannot be read.
171 InvalidOutputFileError when the output file cannot be written.
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700172 ServiceModuleNotFoundError when the service module cannot be imported.
173 MethodNotFoundError when the method cannot be retrieved from the module.
174 """
175 try:
Alex Klein5bcb4d22019-03-21 13:51:54 -0600176 input_json = osutils.ReadFile(input_path)
177 except IOError as e:
178 raise InvalidInputFileError('Unable to read input file: %s' % e.message)
179
180 try:
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700181 svc, module_name = self._services[service_name]
182 except KeyError:
183 raise UnknownServiceError('The %s service has not been registered.'
184 % service_name)
185
186 try:
187 method_desc = svc.methods_by_name[method_name]
188 except KeyError:
189 raise UnknownMethodError('The %s method has not been defined in the %s '
190 'service.' % (method_name, service_name))
191
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700192 # Parse the input file to build an instance of the input message.
193 input_msg = self._sym_db.GetPrototype(method_desc.input_type)()
Alex Klein7a115172019-02-08 14:14:20 -0700194 try:
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700195 json_format.Parse(input_json, input_msg, ignore_unknown_fields=True)
Alex Klein7a115172019-02-08 14:14:20 -0700196 except json_format.ParseError as e:
197 raise InvalidInputFormatError(
198 'Unable to parse the input json: %s' % e.message)
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700199
200 # Get an empty output message instance.
201 output_msg = self._sym_db.GetPrototype(method_desc.output_type)()
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700202
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700203 # Allow proto-based method name override.
204 method_options = method_desc.GetOptions().Extensions[self._method_options]
205 if method_options.HasField('implementation_name'):
206 method_name = method_options.implementation_name
207
Alex Klein2bfacb22019-02-04 11:42:17 -0700208 # Check the chroot assertion settings before running.
209 service_options = svc.GetOptions().Extensions[self._service_options]
210 self._HandleChrootAssert(service_options, method_options)
211
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700212 # Import the module and get the method.
213 method_impl = self._GetMethod(module_name, method_name)
214
215 # Successfully located; call and return.
Alex Klein5bcb4d22019-03-21 13:51:54 -0600216 return_code = method_impl(input_msg, output_msg)
217 if return_code is None:
218 return_code = 0
219
220 try:
221 osutils.WriteFile(output_path, json_format.MessageToJson(output_msg))
222 except IOError as e:
223 raise InvalidOutputFileError('Cannot write output file: %s' % e.message)
224
225 return return_code
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700226
Alex Klein2bfacb22019-02-04 11:42:17 -0700227 def _HandleChrootAssert(self, service_options, method_options):
228 """Check the chroot assert options and execute assertion as needed.
229
230 Args:
231 service_options (google.protobuf.Message): The service options.
232 method_options (google.protobuf.Message): The method options.
233 """
234 chroot_assert = build_api_pb2.NO_ASSERTION
235 if method_options.HasField('method_chroot_assert'):
236 # Prefer the method option when set.
237 chroot_assert = method_options.method_chroot_assert
238 elif service_options.HasField('service_chroot_assert'):
239 # Fall back to the service option.
240 chroot_assert = service_options.service_chroot_assert
241
242 # Execute appropriate assertion if set.
243 if chroot_assert == build_api_pb2.INSIDE:
244 cros_build_lib.AssertInsideChroot()
245 elif chroot_assert == build_api_pb2.OUTSIDE:
246 cros_build_lib.AssertOutsideChroot()
247
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700248 def _GetMethod(self, module_name, method_name):
249 """Get the implementation of the method for the service module.
250
251 Args:
252 module_name (str): The name of the service module.
253 method_name (str): The name of the method.
254
255 Returns:
256 callable - The method.
257
258 Raises:
259 MethodNotFoundError when the method cannot be found in the module.
260 ServiceModuleNotFoundError when the service module cannot be imported.
261 """
262 try:
Alex Kleinb7cdbe62019-02-22 11:41:32 -0700263 module = importlib.import_module(controller.IMPORT_PATTERN % module_name)
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700264 except ImportError as e:
Alex Kleinb7cdbe62019-02-22 11:41:32 -0700265 raise ServiceControllerNotFoundError(e.message)
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700266 try:
267 return getattr(module, method_name)
268 except AttributeError as e:
269 raise MethodNotFoundError(e.message)
270
271
272def RegisterServices(router):
273 """Register all the services.
274
275 Args:
276 router (Router): The router.
277 """
Ned Nguyen9a7a9052019-02-05 11:04:03 -0700278 router.Register(depgraph_pb2)
Alex Klein2966e302019-01-17 13:29:38 -0700279 router.Register(image_pb2)
Alex Klein19c4cc42019-02-27 14:47:57 -0700280 router.Register(sdk_pb2)
Alex Kleinb400da62019-02-20 16:42:50 -0700281 router.Register(test_archive_pb2)
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700282
283
284def main(argv):
Alex Kleinf4dc4f52018-12-05 13:55:12 -0700285 router = Router()
286 RegisterServices(router)
287
Alex Klein00b1f1e2019-02-08 13:53:42 -0700288 opts = _ParseArgs(argv, router)
289
Alex Klein7a115172019-02-08 14:14:20 -0700290 try:
Alex Klein5bcb4d22019-03-21 13:51:54 -0600291 return router.Route(opts.service, opts.method, opts.input_json,
292 opts.output_json)
Alex Klein7a115172019-02-08 14:14:20 -0700293 except Error as e:
294 # Error derivatives are handled nicely, but let anything else bubble up.
295 cros_build_lib.Die(e.message)