1# Copyright 2022 Google Inc. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""The JSON RPC client base for communicating with snippet servers. 15 16The JSON RPC protocol expected by this module is: 17 18.. code-block:: json 19 20 Request: 21 { 22 'id': <Required. Monotonically increasing integer containing the ID of this 23 request.>, 24 'method': <Required. String containing the name of the method to execute.>, 25 'params': <Required. JSON array containing the arguments to the method, 26 `null` if no positional arguments for the RPC method.>, 27 'kwargs': <Optional. JSON dict containing the keyword arguments for the 28 method, `null` if no positional arguments for the RPC method.>, 29 } 30 31 Response: 32 { 33 'error': <Required. String containing the error thrown by executing the 34 method, `null` if no error occurred.>, 35 'id': <Required. Int id of request that this response maps to.>, 36 'result': <Required. Arbitrary JSON object containing the result of 37 executing the method, `null` if the method could not be executed 38 or returned void.>, 39 'callback': <Required. String that represents a callback ID used to 40 identify events associated with a particular CallbackHandler 41 object, `null` if this is not an asynchronous RPC.>, 42 } 43""" 44 45import abc 46import json 47import threading 48import time 49 50from mobly.snippet import errors 51 52# Maximum logging length of RPC response in DEBUG level when verbose logging is 53# off. 54_MAX_RPC_RESP_LOGGING_LENGTH = 1024 55 56# The required field names of RPC response. 57RPC_RESPONSE_REQUIRED_FIELDS = ('id', 'error', 'result', 'callback') 58 59 60class ClientBase(abc.ABC): 61 """Base class for JSON RPC clients that connect to snippet servers. 62 63 Connects to a remote device running a JSON RPC compatible server. Users call 64 the function `start_server` to start the server on the remote device before 65 sending any RPC. After sending all RPCs, users call the function `stop` 66 to stop the snippet server and release all the requested resources. 67 68 Attributes: 69 package: str, the user-visible name of the snippet library being 70 communicated with. 71 log: Logger, the logger of the corresponding device controller. 72 verbose_logging: bool, if True, prints more detailed log 73 information. Default is True. 74 """ 75 76 def __init__(self, package, device): 77 """Initializes the instance of ClientBase. 78 79 Args: 80 package: str, the user-visible name of the snippet library being 81 communicated with. 82 device: DeviceController, the device object associated with a client. 83 """ 84 85 self.package = package 86 self.log = device.log 87 self.verbose_logging = True 88 self._device = device 89 self._counter = None 90 self._lock = threading.Lock() 91 self._event_client = None 92 93 def __del__(self): 94 self.close_connection() 95 96 def initialize(self): 97 """Initializes the snippet client to interact with the remote device. 98 99 This function contains following stages: 100 1. before starting server: preparing to start the snippet server. 101 2. start server: starting the snippet server on the remote device. 102 3. make connection: making a connection to the snippet server. 103 104 An error occurring at any stage will abort the initialization. Only errors 105 at the `start_server` and `make_connection` stages will trigger `stop` to 106 clean up. 107 108 Raises: 109 errors.ProtocolError: something went wrong when exchanging data with the 110 server. 111 errors.ServerStartPreCheckError: when prechecks for starting the server 112 failed. 113 errors.ServerStartError: when failed to start the snippet server. 114 """ 115 116 # Use log.info here so people can follow along with the initialization 117 # process. Initialization can be slow, especially if there are 118 # multiple snippets, this avoids the perception that the framework 119 # is hanging for a long time doing nothing. 120 self.log.info('Initializing the snippet package %s.', self.package) 121 start_time = time.perf_counter() 122 123 self.log.debug('Preparing to start the snippet server of %s.', self.package) 124 self.before_starting_server() 125 126 try: 127 self.log.debug('Starting the snippet server of %s.', self.package) 128 self.start_server() 129 130 self.log.debug('Making a connection to the snippet server of %s.', 131 self.package) 132 self._make_connection() 133 134 except Exception: 135 self.log.error( 136 'Error occurred trying to start and connect to the snippet server ' 137 'of %s.', self.package) 138 try: 139 self.stop() 140 except Exception: # pylint: disable=broad-except 141 # Only prints this exception and re-raises the original exception 142 self.log.exception( 143 'Failed to stop the snippet package %s after failure to start ' 144 'and connect.', self.package) 145 146 raise 147 148 self.log.debug('Snippet package %s initialized after %.1fs.', self.package, 149 time.perf_counter() - start_time) 150 151 @abc.abstractmethod 152 def before_starting_server(self): 153 """Performs the preparation steps before starting the remote server. 154 155 For example, subclass can check or modify the device settings at this 156 stage. 157 158 NOTE: Any error at this stage will abort the initialization without cleanup. 159 So do not acquire resources in this function, or this function should 160 release the acquired resources if an error occurs. 161 162 Raises: 163 errors.ServerStartPreCheckError: when prechecks for starting the server 164 failed. 165 """ 166 167 @abc.abstractmethod 168 def start_server(self): 169 """Starts the server on the remote device. 170 171 The client has completed the preparations, so the client calls this 172 function to start the server. 173 """ 174 175 def _make_connection(self): 176 """Proxy function of make_connection. 177 178 This function resets the RPC id counter before calling `make_connection`. 179 """ 180 self._counter = self._id_counter() 181 self.make_connection() 182 183 @abc.abstractmethod 184 def make_connection(self): 185 """Makes a connection to the snippet server on the remote device. 186 187 This function makes a connection to the server and sends a handshake 188 request to ensure the server is available for upcoming RPCs. 189 190 There are two types of connections used by snippet clients: 191 * The client makes a new connection each time it needs to send an RPC. 192 * The client makes a connection in this stage and uses it for all the RPCs. 193 In this case, the client should implement `close_connection` to close 194 the connection. 195 196 Raises: 197 errors.ProtocolError: something went wrong when exchanging data with the 198 server. 199 """ 200 201 def __getattr__(self, name): 202 """Wrapper for python magic to turn method calls into RPCs.""" 203 204 def rpc_call(*args, **kwargs): 205 return self._rpc(name, *args, **kwargs) 206 207 return rpc_call 208 209 def _id_counter(self): 210 """Returns an id generator.""" 211 i = 0 212 while True: 213 yield i 214 i += 1 215 216 def set_snippet_client_verbose_logging(self, verbose): 217 """Switches verbose logging. True for logging full RPC responses. 218 219 By default it will write full messages returned from RPCs. Turning off the 220 verbose logging will result in writing no more than 221 _MAX_RPC_RESP_LOGGING_LENGTH characters per RPC returned string. 222 223 _MAX_RPC_RESP_LOGGING_LENGTH will be set to 1024 by default. The length 224 contains the full RPC response in JSON format, not just the RPC result 225 field. 226 227 Args: 228 verbose: bool, if True, turns on verbose logging, otherwise turns off. 229 """ 230 self.log.info('Sets verbose logging to %s.', verbose) 231 self.verbose_logging = verbose 232 233 @abc.abstractmethod 234 def restore_server_connection(self, port=None): 235 """Reconnects to the server after the device was disconnected. 236 237 Instead of creating a new instance of the client: 238 - Uses the given port (or finds a new available host port if 0 or None is 239 given). 240 - Tries to connect to the remote server with the selected port. 241 242 Args: 243 port: int, if given, this is the host port from which to connect to the 244 remote device port. Otherwise, finds a new available port as host 245 port. 246 247 Raises: 248 errors.ServerRestoreConnectionError: when failed to restore the connection 249 to the snippet server. 250 """ 251 252 def _rpc(self, rpc_func_name, *args, **kwargs): 253 """Sends an RPC to the server. 254 255 Args: 256 rpc_func_name: str, the name of the snippet function to execute on the 257 server. 258 *args: any, the positional arguments of the RPC request. 259 **kwargs: any, the keyword arguments of the RPC request. 260 261 Returns: 262 The result of the RPC. 263 264 Raises: 265 errors.ProtocolError: something went wrong when exchanging data with the 266 server. 267 errors.ApiError: the RPC went through, however executed with errors. 268 """ 269 try: 270 self.check_server_proc_running() 271 except Exception: 272 self.log.error( 273 'Server process running check failed, skip sending RPC method(%s).', 274 rpc_func_name) 275 raise 276 277 with self._lock: 278 rpc_id = next(self._counter) 279 request = self._gen_rpc_request(rpc_id, rpc_func_name, *args, **kwargs) 280 281 self.log.debug('Sending RPC request %s.', request) 282 response = self.send_rpc_request(request) 283 self.log.debug('RPC request sent.') 284 285 if self.verbose_logging or _MAX_RPC_RESP_LOGGING_LENGTH >= len(response): 286 self.log.debug('Snippet received: %s', response) 287 else: 288 self.log.debug('Snippet received: %s... %d chars are truncated', 289 response[:_MAX_RPC_RESP_LOGGING_LENGTH], 290 len(response) - _MAX_RPC_RESP_LOGGING_LENGTH) 291 292 response_decoded = self._decode_response_string_and_validate_format( 293 rpc_id, response) 294 return self._handle_rpc_response(rpc_func_name, response_decoded) 295 296 @abc.abstractmethod 297 def check_server_proc_running(self): 298 """Checks whether the server is still running. 299 300 If the server is not running, it throws an error. As this function is called 301 each time the client tries to send an RPC, this should be a quick check 302 without affecting performance. Otherwise it is fine to not check anything. 303 304 Raises: 305 errors.ServerDiedError: if the server died. 306 """ 307 308 def _gen_rpc_request(self, rpc_id, rpc_func_name, *args, **kwargs): 309 """Generates the JSON RPC request. 310 311 In the generated JSON string, the fields are sorted by keys in ascending 312 order. 313 314 Args: 315 rpc_id: int, the id of this RPC. 316 rpc_func_name: str, the name of the snippet function to execute 317 on the server. 318 *args: any, the positional arguments of the RPC. 319 **kwargs: any, the keyword arguments of the RPC. 320 321 Returns: 322 A string of the JSON RPC request. 323 """ 324 data = {'id': rpc_id, 'method': rpc_func_name, 'params': args} 325 if kwargs: 326 data['kwargs'] = kwargs 327 return json.dumps(data, sort_keys=True) 328 329 @abc.abstractmethod 330 def send_rpc_request(self, request): 331 """Sends the JSON RPC request to the server and gets a response. 332 333 Note that the request and response are both in string format. So if the 334 connection with server provides interfaces in bytes format, please 335 transform them to string in the implementation of this function. 336 337 Args: 338 request: str, a string of the RPC request. 339 340 Returns: 341 A string of the RPC response. 342 343 Raises: 344 errors.ProtocolError: something went wrong when exchanging data with the 345 server. 346 """ 347 348 def _decode_response_string_and_validate_format(self, rpc_id, response): 349 """Decodes response JSON string to python dict and validates its format. 350 351 Args: 352 rpc_id: int, the actual id of this RPC. It should be the same with the id 353 in the response, otherwise throws an error. 354 response: str, the JSON string of the RPC response. 355 356 Returns: 357 A dict decoded from the response JSON string. 358 359 Raises: 360 errors.ProtocolError: if the response format is invalid. 361 """ 362 if not response: 363 raise errors.ProtocolError(self._device, 364 errors.ProtocolError.NO_RESPONSE_FROM_SERVER) 365 366 result = json.loads(response) 367 for field_name in RPC_RESPONSE_REQUIRED_FIELDS: 368 if field_name not in result: 369 raise errors.ProtocolError( 370 self._device, 371 errors.ProtocolError.RESPONSE_MISSING_FIELD % field_name) 372 373 if result['id'] != rpc_id: 374 raise errors.ProtocolError(self._device, 375 errors.ProtocolError.MISMATCHED_API_ID) 376 377 return result 378 379 def _handle_rpc_response(self, rpc_func_name, response): 380 """Handles the content of RPC response. 381 382 If the RPC response contains error information, it throws an error. If the 383 RPC is asynchronous, it creates and returns a callback handler 384 object. Otherwise, it returns the result field of the response. 385 386 Args: 387 rpc_func_name: str, the name of the snippet function that this RPC 388 triggered on the snippet server. 389 response: dict, the object decoded from the response JSON string. 390 391 Returns: 392 The result of the RPC. If synchronous RPC, it is the result field of the 393 response. If asynchronous RPC, it is the callback handler object. 394 395 Raises: 396 errors.ApiError: if the snippet function executed with errors. 397 """ 398 399 if response['error']: 400 raise errors.ApiError(self._device, response['error']) 401 if response['callback'] is not None: 402 return self.handle_callback(response['callback'], response['result'], 403 rpc_func_name) 404 return response['result'] 405 406 @abc.abstractmethod 407 def handle_callback(self, callback_id, ret_value, rpc_func_name): 408 """Creates a callback handler for the asynchronous RPC. 409 410 Args: 411 callback_id: str, the callback ID for creating a callback handler object. 412 ret_value: any, the result field of the RPC response. 413 rpc_func_name: str, the name of the snippet function executed on the 414 server. 415 416 Returns: 417 The callback handler object. 418 """ 419 420 @abc.abstractmethod 421 def stop(self): 422 """Releases all the resources acquired in `initialize`.""" 423 424 @abc.abstractmethod 425 def close_connection(self): 426 """Closes the connection to the snippet server on the device. 427 428 This is a unilateral closing from the client side, without tearing down 429 the snippet server running on the device. 430 431 The connection to the snippet server can be re-established by calling 432 `restore_server_connection`. 433 """ 434