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( 131 'Making a connection to the snippet server of %s.', self.package 132 ) 133 self._make_connection() 134 135 except Exception: 136 self.log.error( 137 'Error occurred trying to start and connect to the snippet server ' 138 'of %s.', 139 self.package, 140 ) 141 try: 142 self.stop() 143 except Exception: # pylint: disable=broad-except 144 # Only prints this exception and re-raises the original exception 145 self.log.exception( 146 'Failed to stop the snippet package %s after failure to start ' 147 'and connect.', 148 self.package, 149 ) 150 151 raise 152 153 self.log.debug( 154 'Snippet package %s initialized after %.1fs.', 155 self.package, 156 time.perf_counter() - start_time, 157 ) 158 159 @abc.abstractmethod 160 def before_starting_server(self): 161 """Performs the preparation steps before starting the remote server. 162 163 For example, subclass can check or modify the device settings at this 164 stage. 165 166 NOTE: Any error at this stage will abort the initialization without cleanup. 167 So do not acquire resources in this function, or this function should 168 release the acquired resources if an error occurs. 169 170 Raises: 171 errors.ServerStartPreCheckError: when prechecks for starting the server 172 failed. 173 """ 174 175 @abc.abstractmethod 176 def start_server(self): 177 """Starts the server on the remote device. 178 179 The client has completed the preparations, so the client calls this 180 function to start the server. 181 """ 182 183 def _make_connection(self): 184 """Proxy function of make_connection. 185 186 This function resets the RPC id counter before calling `make_connection`. 187 """ 188 self._counter = self._id_counter() 189 self.make_connection() 190 191 @abc.abstractmethod 192 def make_connection(self): 193 """Makes a connection to the snippet server on the remote device. 194 195 This function makes a connection to the server and sends a handshake 196 request to ensure the server is available for upcoming RPCs. 197 198 There are two types of connections used by snippet clients: 199 * The client makes a new connection each time it needs to send an RPC. 200 * The client makes a connection in this stage and uses it for all the RPCs. 201 In this case, the client should implement `close_connection` to close 202 the connection. 203 204 Raises: 205 errors.ProtocolError: something went wrong when exchanging data with the 206 server. 207 """ 208 209 def __getattr__(self, name): 210 """Wrapper for python magic to turn method calls into RPCs.""" 211 212 def rpc_call(*args, **kwargs): 213 return self._rpc(name, *args, **kwargs) 214 215 return rpc_call 216 217 def _id_counter(self): 218 """Returns an id generator.""" 219 i = 0 220 while True: 221 yield i 222 i += 1 223 224 def set_snippet_client_verbose_logging(self, verbose): 225 """Switches verbose logging. True for logging full RPC responses. 226 227 By default it will write full messages returned from RPCs. Turning off the 228 verbose logging will result in writing no more than 229 _MAX_RPC_RESP_LOGGING_LENGTH characters per RPC returned string. 230 231 _MAX_RPC_RESP_LOGGING_LENGTH will be set to 1024 by default. The length 232 contains the full RPC response in JSON format, not just the RPC result 233 field. 234 235 Args: 236 verbose: bool, if True, turns on verbose logging, otherwise turns off. 237 """ 238 self.log.info('Sets verbose logging to %s.', verbose) 239 self.verbose_logging = verbose 240 241 @abc.abstractmethod 242 def restore_server_connection(self, port=None): 243 """Reconnects to the server after the device was disconnected. 244 245 Instead of creating a new instance of the client: 246 - Uses the given port (or finds a new available host port if 0 or None is 247 given). 248 - Tries to connect to the remote server with the selected port. 249 250 Args: 251 port: int, if given, this is the host port from which to connect to the 252 remote device port. Otherwise, finds a new available port as host 253 port. 254 255 Raises: 256 errors.ServerRestoreConnectionError: when failed to restore the connection 257 to the snippet server. 258 """ 259 260 def _rpc(self, rpc_func_name, *args, **kwargs): 261 """Sends an RPC to the server. 262 263 Args: 264 rpc_func_name: str, the name of the snippet function to execute on the 265 server. 266 *args: any, the positional arguments of the RPC request. 267 **kwargs: any, the keyword arguments of the RPC request. 268 269 Returns: 270 The result of the RPC. 271 272 Raises: 273 errors.ProtocolError: something went wrong when exchanging data with the 274 server. 275 errors.ApiError: the RPC went through, however executed with errors. 276 """ 277 try: 278 self.check_server_proc_running() 279 except Exception: 280 self.log.error( 281 'Server process running check failed, skip sending RPC method(%s).', 282 rpc_func_name, 283 ) 284 raise 285 286 with self._lock: 287 rpc_id = next(self._counter) 288 request = self._gen_rpc_request(rpc_id, rpc_func_name, *args, **kwargs) 289 290 self.log.debug('Sending RPC request %s.', request) 291 response = self.send_rpc_request(request) 292 self.log.debug('RPC request sent.') 293 294 if self.verbose_logging or _MAX_RPC_RESP_LOGGING_LENGTH >= len(response): 295 self.log.debug('Snippet received: %s', response) 296 else: 297 self.log.debug( 298 'Snippet received: %s... %d chars are truncated', 299 response[:_MAX_RPC_RESP_LOGGING_LENGTH], 300 len(response) - _MAX_RPC_RESP_LOGGING_LENGTH, 301 ) 302 303 response_decoded = self._decode_response_string_and_validate_format( 304 rpc_id, response 305 ) 306 return self._handle_rpc_response(rpc_func_name, response_decoded) 307 308 @abc.abstractmethod 309 def check_server_proc_running(self): 310 """Checks whether the server is still running. 311 312 If the server is not running, it throws an error. As this function is called 313 each time the client tries to send an RPC, this should be a quick check 314 without affecting performance. Otherwise it is fine to not check anything. 315 316 Raises: 317 errors.ServerDiedError: if the server died. 318 """ 319 320 def _gen_rpc_request(self, rpc_id, rpc_func_name, *args, **kwargs): 321 """Generates the JSON RPC request. 322 323 In the generated JSON string, the fields are sorted by keys in ascending 324 order. 325 326 Args: 327 rpc_id: int, the id of this RPC. 328 rpc_func_name: str, the name of the snippet function to execute 329 on the server. 330 *args: any, the positional arguments of the RPC. 331 **kwargs: any, the keyword arguments of the RPC. 332 333 Returns: 334 A string of the JSON RPC request. 335 """ 336 data = {'id': rpc_id, 'method': rpc_func_name, 'params': args} 337 if kwargs: 338 data['kwargs'] = kwargs 339 return json.dumps(data, sort_keys=True) 340 341 @abc.abstractmethod 342 def send_rpc_request(self, request): 343 """Sends the JSON RPC request to the server and gets a response. 344 345 Note that the request and response are both in string format. So if the 346 connection with server provides interfaces in bytes format, please 347 transform them to string in the implementation of this function. 348 349 Args: 350 request: str, a string of the RPC request. 351 352 Returns: 353 A string of the RPC response. 354 355 Raises: 356 errors.ProtocolError: something went wrong when exchanging data with the 357 server. 358 """ 359 360 def _decode_response_string_and_validate_format(self, rpc_id, response): 361 """Decodes response JSON string to python dict and validates its format. 362 363 Args: 364 rpc_id: int, the actual id of this RPC. It should be the same with the id 365 in the response, otherwise throws an error. 366 response: str, the JSON string of the RPC response. 367 368 Returns: 369 A dict decoded from the response JSON string. 370 371 Raises: 372 errors.ProtocolError: if the response format is invalid. 373 """ 374 if not response: 375 raise errors.ProtocolError( 376 self._device, errors.ProtocolError.NO_RESPONSE_FROM_SERVER 377 ) 378 379 result = json.loads(response) 380 for field_name in RPC_RESPONSE_REQUIRED_FIELDS: 381 if field_name not in result: 382 raise errors.ProtocolError( 383 self._device, 384 errors.ProtocolError.RESPONSE_MISSING_FIELD % field_name, 385 ) 386 387 if result['id'] != rpc_id: 388 raise errors.ProtocolError( 389 self._device, errors.ProtocolError.MISMATCHED_API_ID 390 ) 391 392 return result 393 394 def _handle_rpc_response(self, rpc_func_name, response): 395 """Handles the content of RPC response. 396 397 If the RPC response contains error information, it throws an error. If the 398 RPC is asynchronous, it creates and returns a callback handler 399 object. Otherwise, it returns the result field of the response. 400 401 Args: 402 rpc_func_name: str, the name of the snippet function that this RPC 403 triggered on the snippet server. 404 response: dict, the object decoded from the response JSON string. 405 406 Returns: 407 The result of the RPC. If synchronous RPC, it is the result field of the 408 response. If asynchronous RPC, it is the callback handler object. 409 410 Raises: 411 errors.ApiError: if the snippet function executed with errors. 412 """ 413 414 if response['error']: 415 raise errors.ApiError(self._device, response['error']) 416 if response['callback'] is not None: 417 return self.handle_callback( 418 response['callback'], response['result'], rpc_func_name 419 ) 420 return response['result'] 421 422 @abc.abstractmethod 423 def handle_callback(self, callback_id, ret_value, rpc_func_name): 424 """Creates a callback handler for the asynchronous RPC. 425 426 Args: 427 callback_id: str, the callback ID for creating a callback handler object. 428 ret_value: any, the result field of the RPC response. 429 rpc_func_name: str, the name of the snippet function executed on the 430 server. 431 432 Returns: 433 The callback handler object. 434 """ 435 436 @abc.abstractmethod 437 def stop(self): 438 """Releases all the resources acquired in `initialize`.""" 439 440 @abc.abstractmethod 441 def close_connection(self): 442 """Closes the connection to the snippet server on the device. 443 444 This is a unilateral closing from the client side, without tearing down 445 the snippet server running on the device. 446 447 The connection to the snippet server can be re-established by calling 448 `restore_server_connection`. 449 """ 450