Martin Cosyns | 0efdc87 | 2021-09-27 16:24:30 +0000 | [diff] [blame] | 1 | # Copyright 2020-present Open Networking Foundation |
| 2 | # Original copyright 2020-present ADTRAN, Inc. |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | import grpc |
| 15 | from grpc import _channel, ChannelConnectivity |
| 16 | from decorator import decorator |
| 17 | |
| 18 | from ..tools.protobuf_to_dict import protobuf_to_dict, dict_to_protobuf |
| 19 | from ..tools.robot_tools import Collections |
| 20 | from google.protobuf import empty_pb2 |
| 21 | |
| 22 | |
| 23 | # decorator to check if connection is open |
| 24 | @decorator |
| 25 | def is_connected(library_function, *args, **kwargs): |
| 26 | try: |
| 27 | assert args[0].ctx.grpc_channel is not None |
| 28 | grpc.channel_ready_future(args[0].ctx.grpc_channel).result(timeout=10) |
| 29 | except (AssertionError, grpc.FutureTimeoutError): |
| 30 | raise ConnectionError('not connected to a gRPC channel') |
| 31 | |
| 32 | return library_function(*args, **kwargs) |
| 33 | |
| 34 | |
| 35 | # unfortunately conversation from snake-case to camel-case does not work for all keyword names, so we define a mapping dict |
| 36 | kw_name_mapping = { |
| 37 | 'GetHwComponentInfo': 'GetHWComponentInfo', |
| 38 | 'SetHwComponentInfo': 'SetHWComponentInfo' |
| 39 | } |
| 40 | |
| 41 | one_of_note = """*Note*: Bold dictionary keys are cases of an ONEOF type that is not transmitted in gRPC.\n""" |
| 42 | named_parameters_note = """*Named parameters*:\n |
| 43 | - return_enum_integer: <bool> or <string>; Whether or not to return the enum values as integer values rather than their labels. Default: _${FALSE}_ or _false_.\n |
| 44 | - return_defaults: <bool> or <string>; Whether or not to return the default values. Default: _${FALSE}_ or _false_.\n |
| 45 | - timeout: <int> or <string>; Number of seconds to wait for the response. Default: The timeout value set by keywords _Connection Open_ and _Connection Parameters Set_.""" |
| 46 | |
| 47 | |
| 48 | class Service(object): |
| 49 | |
| 50 | prefix = '' |
| 51 | |
| 52 | def __init__(self, ctx, stub=None): |
| 53 | super().__init__() |
| 54 | self.ctx = ctx |
| 55 | |
| 56 | try: |
| 57 | self.stub = stub(channel=ctx.grpc_channel) |
| 58 | except AttributeError: |
| 59 | self.stub = None |
| 60 | |
| 61 | def get_next_type_def(self, type_name, module): |
| 62 | |
| 63 | next_type_defs = [d for d in self.ctx.protobuf['data_types'] if d['name'] == type_name] |
| 64 | |
| 65 | if not next_type_defs: |
| 66 | return None |
| 67 | |
| 68 | if len(next_type_defs) > 1: |
| 69 | next_type_def = [d for d in next_type_defs if d['module'] == module] |
| 70 | |
| 71 | if next_type_def: |
| 72 | return next_type_def[0] |
| 73 | |
| 74 | else: |
| 75 | return next_type_defs[0] |
| 76 | |
| 77 | else: |
| 78 | return next_type_defs[0] |
| 79 | |
| 80 | def lookup_type_def(self, _type_def, _indent='', _lookup_table=None, enum_indent=''): |
| 81 | |
| 82 | _lookup_table = _lookup_table or [] |
| 83 | |
| 84 | if _type_def['name'] in _lookup_table: |
| 85 | return '< recursive type: ' + _type_def['name'] + ' >' |
| 86 | else: |
| 87 | _lookup_table.append(_type_def['name']) |
| 88 | |
| 89 | if _type_def['type'] == 'message': |
| 90 | |
| 91 | doc_string = '{ # type: %s\n' % _type_def['name'] |
| 92 | _indent += ' ' |
| 93 | |
| 94 | for field in _type_def['fields']: |
| 95 | if field.get('is_choice', False): |
| 96 | doc_string += self.get_field_doc(field, _indent, _lookup_table[:], _type_def['module'], field['name']) |
| 97 | else: |
| 98 | doc_string += "%s'%s': %s\n" % (_indent, field['name'], self.get_field_doc(field, _indent, _lookup_table[:], _type_def['module'])) |
| 99 | |
| 100 | return doc_string + _indent[:-2] + '}' |
| 101 | |
| 102 | if _type_def['type'] == 'enum': |
| 103 | |
| 104 | try: |
| 105 | k_len = 0 |
| 106 | for k, v in _type_def['values'].items(): |
| 107 | k_len = max(len(k), k_len) |
| 108 | enum = (' |\n %s%s' % (_indent, enum_indent)).join(['%s%s - %s' % ((k_len - len(k)) * ' ', k, v) for k, v in _type_def['values'].items()]) |
| 109 | |
| 110 | except AttributeError: |
| 111 | enum = ' | '.join(_type_def['values']) |
| 112 | |
| 113 | return '< %s >' % enum |
| 114 | |
| 115 | return '' |
| 116 | |
| 117 | def get_field_doc(self, _type_def, _indent, _lookup_table, module, choice_name=''): |
| 118 | |
| 119 | doc_string = '' |
| 120 | |
| 121 | _indent = (_indent + ' ') if _type_def.get('repeated', False) else _indent |
| 122 | |
| 123 | if _type_def.get('is_choice', False): |
| 124 | for case in _type_def['cases']: |
| 125 | # doc_string += "%s'*%s*' (ONEOF _%s_): %s\n" % (_indent, case['name'], choice_name, self.get_field_doc(case, _indent, _lookup_table[:], module)) |
| 126 | doc_string += "%s'_ONEOF %s_: *%s*': %s\n" % (_indent, choice_name, case['name'], self.get_field_doc(case, _indent, _lookup_table[:], module)) |
| 127 | |
| 128 | elif _type_def.get('lookup', False): |
| 129 | try: |
| 130 | next_type_def = self.get_next_type_def(_type_def['type'], module=module) |
| 131 | if next_type_def is not None: |
| 132 | doc_string += self.lookup_type_def(next_type_def, _indent, _lookup_table, (len(_type_def['name']) + 5) * ' ') |
| 133 | else: |
| 134 | doc_string += "<%s>," % _type_def['type'] |
| 135 | |
| 136 | except KeyError: |
| 137 | doc_string += _type_def['type'] |
| 138 | else: |
| 139 | doc_string += "<%s>," % _type_def['type'] |
| 140 | |
| 141 | if _type_def.get('repeated', False): |
| 142 | doc_string = '[ # list of:\n' + _indent + doc_string + '\n' + _indent[:-2] + ']' |
| 143 | |
| 144 | return doc_string |
| 145 | |
| 146 | def get_rpc_documentation(self, type_def, module): |
| 147 | |
| 148 | indent = ' ' if type_def['is_stream'] else '' |
| 149 | |
| 150 | if type_def['lookup']: |
| 151 | next_type_def = self.get_next_type_def(type_def['type'], module) |
| 152 | if next_type_def is not None: |
| 153 | doc_string = self.lookup_type_def(next_type_def, indent) |
| 154 | else: |
| 155 | doc_string = type_def['type'] + '\n' |
| 156 | else: |
| 157 | doc_string = type_def['type'] + '\n' |
| 158 | |
| 159 | if type_def['is_stream']: |
| 160 | return '[ # list of:\n' + indent + doc_string + '\n]' |
| 161 | else: |
| 162 | return doc_string |
| 163 | |
| 164 | def get_documentation(self, keyword_name): |
| 165 | |
| 166 | keyword_name = Collections.to_camel_case(keyword_name.replace(self.prefix, ''), True) |
| 167 | keyword_name = kw_name_mapping.get(keyword_name, keyword_name) |
| 168 | |
| 169 | try: |
| 170 | service = Collections.list_get_dict_by_value(self.ctx.protobuf.get('services', []), 'name', self.__class__.__name__) |
| 171 | except KeyError: |
| 172 | return 'no documentation available' |
| 173 | |
| 174 | rpc = Collections.list_get_dict_by_value(service.get('rpcs', []), 'name', keyword_name) |
| 175 | |
| 176 | doc_string = 'RPC _%s_ from _%s_.\n' % (rpc['name'], service['name']) |
| 177 | doc_string += '\n\n*Parameters*:\n' |
| 178 | |
| 179 | for attr, attr_str in [('request', '- param_dict'), ('named_params', None), ('response', '*Return*')]: |
| 180 | |
| 181 | if rpc.get(attr) is not None: |
| 182 | rpc_doc = '\n'.join(['| %s' % line for line in self.get_rpc_documentation(rpc.get(attr), service['module']).splitlines()]) |
| 183 | |
| 184 | if rpc_doc == '| google.protobuf.Empty': |
| 185 | doc_string += '_none_\n\n' |
| 186 | continue |
| 187 | |
| 188 | doc_string += '\n%s:\n' % attr_str if '_ONEOF' not in rpc_doc else '\n%s: %s\n' % (attr_str, one_of_note) |
| 189 | doc_string += rpc_doc + '\n' |
| 190 | |
| 191 | elif attr == 'named_params': |
| 192 | doc_string += named_parameters_note |
| 193 | |
| 194 | return doc_string |
| 195 | |
| 196 | @staticmethod |
| 197 | def to_protobuf(type_def, param_dict): |
| 198 | try: |
| 199 | return dict_to_protobuf(type_def or empty_pb2.Empty, param_dict or {}) |
| 200 | except Exception as e: |
| 201 | raise ValueError('parameter dictionary does not match the ProtoBuf type definition: %s' % e) |
| 202 | |
| 203 | def _process_response(self, response, index=None, **kwargs): |
| 204 | |
| 205 | debug_text = 'RESPONSE' if index is None else 'RESPONSE-NEXT ' if index else 'RESPONSE-STREAM' |
| 206 | |
| 207 | return_enum_integer = bool(str(kwargs.get('return_enum_integer', False)).lower() == 'true') |
| 208 | return_defaults = bool(str(kwargs.get('return_defaults', False)).lower() == 'true') |
| 209 | |
| 210 | self.ctx.logger.debug('%s : data=%s' % (debug_text, response)) |
| 211 | _response = protobuf_to_dict(response, use_enum_labels=not return_enum_integer, including_default_value_fields=return_defaults) |
| 212 | |
| 213 | return _response |
| 214 | |
| 215 | def _grpc_helper(self, func, arg_type=None, param_dict=None, **kwargs): |
| 216 | |
| 217 | def generate_stream(arg, data_list): |
| 218 | |
| 219 | for idx, data in enumerate(data_list): |
| 220 | _protobuf = self.to_protobuf(arg, data) |
| 221 | debug_text = 'REQUEST-NEXT :' if idx else 'REQUEST-STREAM : method=%s;' % func._method.decode() |
| 222 | self.ctx.logger.debug('%s data=%s' % (debug_text, _protobuf)) |
| 223 | yield _protobuf |
| 224 | |
| 225 | if isinstance(param_dict, list): |
| 226 | response = func(generate_stream(arg_type, param_dict), timeout=int(kwargs.get('timeout') or self.ctx.timeout)) |
| 227 | else: |
| 228 | protobuf = self.to_protobuf(arg_type, param_dict) |
| 229 | self.ctx.logger.debug('REQUEST : method=%s; data=%s' % (func._method.decode(), protobuf)) |
| 230 | response = func(protobuf, timeout=int(kwargs.get('timeout') or self.ctx.timeout)) |
| 231 | |
| 232 | try: |
| 233 | |
| 234 | # streamed response is of type <grpc._channel._MultiThreadedRendezvous> and must be handle as list |
| 235 | if isinstance(response, _channel._MultiThreadedRendezvous): |
| 236 | |
| 237 | return_list = [] |
| 238 | for idx, list_item in enumerate(response): |
| 239 | return_list.append(self._process_response(list_item, index=idx, **kwargs)) |
| 240 | |
| 241 | return return_list |
| 242 | |
| 243 | else: |
| 244 | |
| 245 | return self._process_response(response, **kwargs) |
| 246 | |
| 247 | except grpc.RpcError as e: |
| 248 | if e.code().name == 'DEADLINE_EXCEEDED': |
| 249 | self.ctx.logger.error('TimeoutError (%ss): %s' % (kwargs.get('timeout') or self.ctx.timeout, e)) |
| 250 | raise TimeoutError('no response within %s seconds' % (kwargs.get('timeout') or self.ctx.timeout)) |
| 251 | else: |
| 252 | self.ctx.logger.error(e) |
| 253 | raise e |
| 254 | |