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