blob: 2528eae9863c2c0a85439634a95ab132ceb41c82 [file] [log] [blame]
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -07001#
Zsolt Harasztiaccad4a2017-01-03 21:56:48 -08002# Copyright 2017 the original author or authors.
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -07003#
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# limitations under the License.
15#
16
17"""
Zsolt Harasztie7b60762016-10-05 17:49:27 -070018gRPC client meant to connect to a gRPC server endpoint, and query the
Zsolt Haraszticba96de2016-11-06 14:04:55 -080019end-point's schema by calling SchemaService.Schema(Empty) and all of its
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070020semantics are derived from the recovered schema.
21"""
Zsolt Harasztie7b60762016-10-05 17:49:27 -070022
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070023import os
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070024import sys
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070025from random import randint
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070026from zlib import decompress
27
Scott Baker6ee1a292018-02-22 17:13:16 -080028import functools
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070029import grpc
30from consul import Consul
Zsolt Harasztie7b60762016-10-05 17:49:27 -070031from grpc._channel import _Rendezvous
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070032from structlog import get_logger
Zsolt Harasztie7b60762016-10-05 17:49:27 -070033from twisted.internet import reactor
Zsolt Haraszti2aac6232016-11-23 11:18:23 -080034from twisted.internet.defer import inlineCallbacks, returnValue
Zsolt Harasztie7b60762016-10-05 17:49:27 -070035from werkzeug.exceptions import ServiceUnavailable
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070036
Zsolt Haraszti21980762016-11-08 10:57:19 -080037from chameleon.protos import third_party
Zsolt Haraszticba96de2016-11-06 14:04:55 -080038from chameleon.protos.schema_pb2 import SchemaServiceStub
39from google.protobuf.empty_pb2 import Empty
40
alshabib6ca05622017-01-31 14:08:36 -080041from chameleon.utils.asleep import asleep
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070042
43log = get_logger()
44
45
46class GrpcClient(object):
Zsolt Harasztie7b60762016-10-05 17:49:27 -070047 """
48 Connect to a gRPC server, fetch its schema, and process the downloaded
49 schema files to drive the customization of the north-bound interface(s)
50 of Chameleon.
51 """
52 RETRY_BACKOFF = [0.05, 0.1, 0.2, 0.5, 1, 2, 5]
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070053
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070054 def __init__(self, consul_endpoint, work_dir, endpoint='localhost:50055',
Scott Baker73784f12018-02-20 12:05:35 -080055 reconnect_callback=None, credentials=None, restart_on_disconnect=False):
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070056 self.consul_endpoint = consul_endpoint
57 self.endpoint = endpoint
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070058 self.work_dir = work_dir
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070059 self.reconnect_callback = reconnect_callback
Scott Baker74548db2017-02-15 14:16:13 -080060 self.credentials = credentials
Scott Baker73784f12018-02-20 12:05:35 -080061 self.restart_on_disconnect = restart_on_disconnect
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070062
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070063 self.plugin_dir = os.path.abspath(os.path.join(
64 os.path.dirname(__file__), '../protoc_plugins'))
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070065
66 self.channel = None
67 self.schema = None
Zsolt Harasztie7b60762016-10-05 17:49:27 -070068 self.retries = 0
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070069 self.shutting_down = False
Zsolt Haraszti3cf36342016-10-05 20:40:19 -070070 self.connected = False
Scott Baker73784f12018-02-20 12:05:35 -080071 self.was_connected = False
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070072
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070073 def start(self):
74 log.debug('starting')
Zsolt Haraszti3cf36342016-10-05 20:40:19 -070075 if not self.connected:
76 reactor.callLater(0, self.connect)
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070077 log.info('started')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070078 return self
79
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070080 def stop(self):
81 log.debug('stopping')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070082 if self.shutting_down:
83 return
84 self.shutting_down = True
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070085 log.info('stopped')
86
87 def set_reconnect_callback(self, reconnect_callback):
88 self.reconnect_callback = reconnect_callback
89 return self
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070090
Scott Baker6ee1a292018-02-22 17:13:16 -080091 def connectivity_callback(self, client, connectivity):
Scott Baker73784f12018-02-20 12:05:35 -080092 if (self.was_connected) and (connectivity in [connectivity.TRANSIENT_FAILURE, connectivity.FATAL_FAILURE, connectivity.SHUTDOWN]):
93 log.info("connectivity lost -- restarting")
94 os.execv(sys.executable, ['python'] + sys.argv)
95
96 if (connectivity == connectivity.READY):
97 self.was_connected = True
98
Scott Baker6ee1a292018-02-22 17:13:16 -080099 # Sometimes gRPC transitions from READY to IDLE, skipping TRANSIENT_FAILURE even though a socket is
100 # disconnected. So on idle, force a connectivity check.
101 if (connectivity == connectivity.IDLE) and (self.was_connected):
102 connectivity = client.channel._channel.check_connectivity_state(True)
103 # The result will probably show IDLE, but passing in True has the side effect of reconnecting if the
104 # connection has been lost, which will trigger the TRANSIENT_FALURE we were looking for.
105
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700106 @inlineCallbacks
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700107 def connect(self):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700108 """
109 (Re-)Connect to end-point
110 """
111
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700112 if self.shutting_down or self.connected:
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700113 return
114
115 try:
116 if self.endpoint.startswith('@'):
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800117 _endpoint = yield self._get_endpoint_from_consul(
118 self.endpoint[1:])
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700119 else:
120 _endpoint = self.endpoint
121
Scott Baker74548db2017-02-15 14:16:13 -0800122 if self.credentials:
123 log.info('securely connecting', endpoint=_endpoint)
124 self.channel = grpc.secure_channel(_endpoint, self.credentials)
125 else:
126 log.info('insecurely connecting', endpoint=_endpoint)
127 self.channel = grpc.insecure_channel(_endpoint)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700128
Scott Baker73784f12018-02-20 12:05:35 -0800129 if self.restart_on_disconnect:
Scott Baker6ee1a292018-02-22 17:13:16 -0800130 connectivity_callback = functools.partial(self.connectivity_callback, self)
131 self.channel.subscribe(connectivity_callback)
Scott Baker73784f12018-02-20 12:05:35 -0800132
Zsolt Haraszti21980762016-11-08 10:57:19 -0800133 swagger_from = self._retrieve_schema()
134 self._compile_proto_files(swagger_from)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700135 self._clear_backoff()
136
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700137 self.connected = True
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700138 if self.reconnect_callback is not None:
139 reactor.callLater(0, self.reconnect_callback)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700140
141 return
142
143 except _Rendezvous, e:
144 if e.code() == grpc.StatusCode.UNAVAILABLE:
145 log.info('grpc-endpoint-not-available')
146 else:
Sapan Bhatiadd273342017-08-30 15:27:55 -0400147 log.exception('rendezvous error', e=e)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700148 yield self._backoff('not-available')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700149
150 except Exception, e:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700151 if not self.shutting_down:
152 log.exception('cannot-connect', endpoint=_endpoint)
153 yield self._backoff('unknown-error')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700154
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700155 reactor.callLater(0, self.connect)
156
157 def _backoff(self, msg):
158 wait_time = self.RETRY_BACKOFF[min(self.retries,
159 len(self.RETRY_BACKOFF) - 1)]
160 self.retries += 1
161 log.error(msg, retry_in=wait_time)
162 return asleep(wait_time)
163
164 def _clear_backoff(self):
165 if self.retries:
166 log.info('reconnected', after_retries=self.retries)
167 self.retries = 0
168
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800169 @inlineCallbacks
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700170 def _get_endpoint_from_consul(self, service_name):
171 """
172 Look up an appropriate grpc endpoint (host, port) from
173 consul, under the service name specified by service-name
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700174 """
175 host = self.consul_endpoint.split(':')[0].strip()
176 port = int(self.consul_endpoint.split(':')[1].strip())
177
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800178 while True:
179 log.debug('consul-lookup', host=host, port=port)
180 consul = Consul(host=host, port=port)
181 _, services = consul.catalog.service(service_name)
182 log.debug('consul-response', services=services)
183 if services:
184 break
185 log.warning('no-service', consul_host=host, consul_port=port,
186 service_name=service_name)
187 yield asleep(1.0)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700188
alshabibc8224902017-01-26 11:59:52 -0800189 # pick local addresses when resolving a service via consul
190 # see CORD-815 (https://jira.opencord.org/browse/CORD-815)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700191
192 service = services[randint(0, len(services) - 1)]
193 endpoint = '{}:{}'.format(service['ServiceAddress'],
194 service['ServicePort'])
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800195 returnValue(endpoint)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700196
197 def _retrieve_schema(self):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700198 """
199 Retrieve schema from gRPC end-point, and save all *.proto files in
200 the work directory.
201 """
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700202 assert isinstance(self.channel, grpc.Channel)
203 stub = SchemaServiceStub(self.channel)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700204 # try:
Zsolt Haraszticba96de2016-11-06 14:04:55 -0800205 schemas = stub.GetSchema(Empty())
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700206 # except _Rendezvous, e:
207 # if e.code == grpc.StatusCode.UNAVAILABLE:
208 #
209 # else:
210 # raise e
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700211
212 os.system('mkdir -p %s' % self.work_dir)
213 os.system('rm -fr /tmp/%s/*' %
214 self.work_dir.replace('/tmp/', '')) # safer
215
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700216 for proto_file in schemas.protos:
217 proto_fname = proto_file.file_name
218 proto_content = proto_file.proto
219 log.debug('saving-proto', fname=proto_fname, dir=self.work_dir,
220 length=len(proto_content))
221 with open(os.path.join(self.work_dir, proto_fname), 'w') as f:
222 f.write(proto_content)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700223
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700224 desc_content = decompress(proto_file.descriptor)
225 desc_fname = proto_fname.replace('.proto', '.desc')
226 log.debug('saving-descriptor', fname=desc_fname, dir=self.work_dir,
227 length=len(desc_content))
228 with open(os.path.join(self.work_dir, desc_fname), 'wb') as f:
229 f.write(desc_content)
Zsolt Haraszti21980762016-11-08 10:57:19 -0800230 return schemas.swagger_from
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700231
Zsolt Haraszti21980762016-11-08 10:57:19 -0800232 def _compile_proto_files(self, swagger_from):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700233 """
234 For each *.proto file in the work directory, compile the proto
235 file into the respective *_pb2.py file as well as generate the
236 web server gateway python file *_gw.py.
237 :return: None
238 """
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700239 google_api_dir = os.path.abspath(os.path.join(
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700240 os.path.dirname(__file__), '../protos/third_party'
241 ))
242
243 chameleon_base_dir = os.path.abspath(os.path.join(
244 os.path.dirname(__file__), '../..'
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700245 ))
246
247 for fname in [f for f in os.listdir(self.work_dir)
248 if f.endswith('.proto')]:
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700249
Zsolt Haraszti21980762016-11-08 10:57:19 -0800250 need_swagger = fname == swagger_from
251 log.debug('compiling', file=fname, need_swagger=need_swagger)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700252 cmd = (
253 'cd %s && '
Zsolt Haraszti05b837a2016-10-05 00:18:57 -0700254 'env PATH=%s PYTHONPATH=%s '
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700255 'python -m grpc.tools.protoc '
256 '-I. '
257 '-I%s '
258 '--python_out=. '
259 '--grpc_python_out=. '
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700260 '--plugin=protoc-gen-gw=%s/gw_gen.py '
261 '--gw_out=. '
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700262 '--plugin=protoc-gen-swagger=%s/swagger_gen.py '
Zsolt Haraszti21980762016-11-08 10:57:19 -0800263 '%s'
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700264 '%s' % (
265 self.work_dir,
266 ':'.join([os.environ['PATH'], self.plugin_dir]),
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700267 ':'.join([google_api_dir, chameleon_base_dir]),
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700268 google_api_dir,
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700269 self.plugin_dir,
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700270 self.plugin_dir,
Zsolt Haraszti21980762016-11-08 10:57:19 -0800271 '--swagger_out=. ' if need_swagger else '',
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700272 fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700273 )
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700274 log.debug('executing', cmd=cmd, file=fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700275 os.system(cmd)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700276 log.info('compiled', file=fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700277
278 # test-load each _pb2 file to see all is right
279 if self.work_dir not in sys.path:
280 sys.path.insert(0, self.work_dir)
281
282 for fname in [f for f in os.listdir(self.work_dir)
283 if f.endswith('_pb2.py')]:
284 modname = fname[:-len('.py')]
285 log.debug('test-import', modname=modname)
286 _ = __import__(modname)
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700287
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800288 @inlineCallbacks
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800289 def invoke(self, stub, method_name, request, metadata, retry=1):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700290 """
291 Invoke a gRPC call to the remote server and return the response.
292 :param stub: Reference to the *_pb2 service stub
293 :param method_name: The method name inside the service stub
294 :param request: The request protobuf message
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800295 :param metadata: [(str, str), (str, str), ...]
296 :return: The response protobuf message and returned trailing metadata
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700297 """
298
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700299 if not self.connected:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700300 raise ServiceUnavailable()
301
302 try:
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800303 method = getattr(stub(self.channel), method_name)
304 response, rendezvous = method.with_call(request, metadata=metadata)
305 returnValue((response, rendezvous.trailing_metadata()))
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700306
307 except grpc._channel._Rendezvous, e:
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800308 code = e.code()
309 if code == grpc.StatusCode.UNAVAILABLE:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700310 e = ServiceUnavailable()
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800311
312 if self.connected:
313 self.connected = False
314 yield self.connect()
315 if retry > 0:
316 response = yield self.invoke(stub, method_name,
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800317 request, metadata,
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800318 retry=retry - 1)
319 returnValue(response)
320
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800321 elif code in (
322 grpc.StatusCode.NOT_FOUND,
323 grpc.StatusCode.INVALID_ARGUMENT,
Matteo Scandolo92f7f1f2017-04-28 15:56:29 -0700324 grpc.StatusCode.ALREADY_EXISTS,
325 grpc.StatusCode.UNAUTHENTICATED,
326 grpc.StatusCode.PERMISSION_DENIED):
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800327
328 pass # don't log error, these occur naturally
329
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700330 else:
331 log.exception(e)
332
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700333 raise e