blob: 9e7987c228fe6f45fc375254fcd3b3dce289030d [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
Scott Baker80a36b72018-03-12 18:55:53 -070037from chameleon.protos.schema_pb2_grpc import SchemaServiceStub
Zsolt Haraszticba96de2016-11-06 14:04:55 -080038from google.protobuf.empty_pb2 import Empty
39
alshabib6ca05622017-01-31 14:08:36 -080040from chameleon.utils.asleep import asleep
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070041
42log = get_logger()
43
44
45class GrpcClient(object):
Zsolt Harasztie7b60762016-10-05 17:49:27 -070046 """
47 Connect to a gRPC server, fetch its schema, and process the downloaded
48 schema files to drive the customization of the north-bound interface(s)
49 of Chameleon.
50 """
51 RETRY_BACKOFF = [0.05, 0.1, 0.2, 0.5, 1, 2, 5]
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070052
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070053 def __init__(self, consul_endpoint, work_dir, endpoint='localhost:50055',
Scott Baker73784f12018-02-20 12:05:35 -080054 reconnect_callback=None, credentials=None, restart_on_disconnect=False):
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070055 self.consul_endpoint = consul_endpoint
56 self.endpoint = endpoint
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070057 self.work_dir = work_dir
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070058 self.reconnect_callback = reconnect_callback
Scott Baker74548db2017-02-15 14:16:13 -080059 self.credentials = credentials
Scott Baker73784f12018-02-20 12:05:35 -080060 self.restart_on_disconnect = restart_on_disconnect
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070061
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070062 self.plugin_dir = os.path.abspath(os.path.join(
63 os.path.dirname(__file__), '../protoc_plugins'))
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070064
65 self.channel = None
66 self.schema = None
Zsolt Harasztie7b60762016-10-05 17:49:27 -070067 self.retries = 0
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070068 self.shutting_down = False
Zsolt Haraszti3cf36342016-10-05 20:40:19 -070069 self.connected = False
Scott Baker73784f12018-02-20 12:05:35 -080070 self.was_connected = False
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070071
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070072 def start(self):
73 log.debug('starting')
Zsolt Haraszti3cf36342016-10-05 20:40:19 -070074 if not self.connected:
75 reactor.callLater(0, self.connect)
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070076 log.info('started')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070077 return self
78
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070079 def stop(self):
80 log.debug('stopping')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070081 if self.shutting_down:
82 return
83 self.shutting_down = True
Zsolt Harasztidca6fa12016-11-03 16:56:17 -070084 log.info('stopped')
85
86 def set_reconnect_callback(self, reconnect_callback):
87 self.reconnect_callback = reconnect_callback
88 return self
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070089
Scott Baker6ee1a292018-02-22 17:13:16 -080090 def connectivity_callback(self, client, connectivity):
Scott Baker80a36b72018-03-12 18:55:53 -070091 if (self.was_connected) and (connectivity in [connectivity.TRANSIENT_FAILURE, connectivity.SHUTDOWN]):
Scott Baker73784f12018-02-20 12:05:35 -080092 log.info("connectivity lost -- restarting")
93 os.execv(sys.executable, ['python'] + sys.argv)
94
95 if (connectivity == connectivity.READY):
96 self.was_connected = True
97
Scott Baker6ee1a292018-02-22 17:13:16 -080098 # Sometimes gRPC transitions from READY to IDLE, skipping TRANSIENT_FAILURE even though a socket is
99 # disconnected. So on idle, force a connectivity check.
100 if (connectivity == connectivity.IDLE) and (self.was_connected):
101 connectivity = client.channel._channel.check_connectivity_state(True)
102 # The result will probably show IDLE, but passing in True has the side effect of reconnecting if the
103 # connection has been lost, which will trigger the TRANSIENT_FALURE we were looking for.
104
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700105 @inlineCallbacks
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700106 def connect(self):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700107 """
108 (Re-)Connect to end-point
109 """
110
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700111 if self.shutting_down or self.connected:
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700112 return
113
114 try:
115 if self.endpoint.startswith('@'):
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800116 _endpoint = yield self._get_endpoint_from_consul(
117 self.endpoint[1:])
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700118 else:
119 _endpoint = self.endpoint
120
Scott Baker74548db2017-02-15 14:16:13 -0800121 if self.credentials:
122 log.info('securely connecting', endpoint=_endpoint)
123 self.channel = grpc.secure_channel(_endpoint, self.credentials)
124 else:
125 log.info('insecurely connecting', endpoint=_endpoint)
126 self.channel = grpc.insecure_channel(_endpoint)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700127
Scott Baker73784f12018-02-20 12:05:35 -0800128 if self.restart_on_disconnect:
Scott Baker6ee1a292018-02-22 17:13:16 -0800129 connectivity_callback = functools.partial(self.connectivity_callback, self)
130 self.channel.subscribe(connectivity_callback)
Scott Baker73784f12018-02-20 12:05:35 -0800131
Zsolt Haraszti21980762016-11-08 10:57:19 -0800132 swagger_from = self._retrieve_schema()
133 self._compile_proto_files(swagger_from)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700134 self._clear_backoff()
135
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700136 self.connected = True
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700137 if self.reconnect_callback is not None:
138 reactor.callLater(0, self.reconnect_callback)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700139
140 return
141
142 except _Rendezvous, e:
143 if e.code() == grpc.StatusCode.UNAVAILABLE:
144 log.info('grpc-endpoint-not-available')
145 else:
Sapan Bhatiadd273342017-08-30 15:27:55 -0400146 log.exception('rendezvous error', e=e)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700147 yield self._backoff('not-available')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700148
149 except Exception, e:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700150 if not self.shutting_down:
151 log.exception('cannot-connect', endpoint=_endpoint)
152 yield self._backoff('unknown-error')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700153
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700154 reactor.callLater(0, self.connect)
155
156 def _backoff(self, msg):
157 wait_time = self.RETRY_BACKOFF[min(self.retries,
158 len(self.RETRY_BACKOFF) - 1)]
159 self.retries += 1
160 log.error(msg, retry_in=wait_time)
161 return asleep(wait_time)
162
163 def _clear_backoff(self):
164 if self.retries:
165 log.info('reconnected', after_retries=self.retries)
166 self.retries = 0
167
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800168 @inlineCallbacks
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700169 def _get_endpoint_from_consul(self, service_name):
170 """
171 Look up an appropriate grpc endpoint (host, port) from
172 consul, under the service name specified by service-name
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700173 """
174 host = self.consul_endpoint.split(':')[0].strip()
175 port = int(self.consul_endpoint.split(':')[1].strip())
176
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800177 while True:
178 log.debug('consul-lookup', host=host, port=port)
179 consul = Consul(host=host, port=port)
180 _, services = consul.catalog.service(service_name)
181 log.debug('consul-response', services=services)
182 if services:
183 break
184 log.warning('no-service', consul_host=host, consul_port=port,
185 service_name=service_name)
186 yield asleep(1.0)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700187
alshabibc8224902017-01-26 11:59:52 -0800188 # pick local addresses when resolving a service via consul
189 # see CORD-815 (https://jira.opencord.org/browse/CORD-815)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700190
191 service = services[randint(0, len(services) - 1)]
192 endpoint = '{}:{}'.format(service['ServiceAddress'],
193 service['ServicePort'])
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800194 returnValue(endpoint)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700195
196 def _retrieve_schema(self):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700197 """
198 Retrieve schema from gRPC end-point, and save all *.proto files in
199 the work directory.
200 """
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700201 assert isinstance(self.channel, grpc.Channel)
202 stub = SchemaServiceStub(self.channel)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700203 # try:
Scott Bakere958b962018-06-12 16:46:45 -0700204 schemas = stub.GetSchema(Empty(), timeout=120)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700205 # except _Rendezvous, e:
206 # if e.code == grpc.StatusCode.UNAVAILABLE:
207 #
208 # else:
209 # raise e
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700210
211 os.system('mkdir -p %s' % self.work_dir)
212 os.system('rm -fr /tmp/%s/*' %
213 self.work_dir.replace('/tmp/', '')) # safer
214
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700215 for proto_file in schemas.protos:
216 proto_fname = proto_file.file_name
217 proto_content = proto_file.proto
218 log.debug('saving-proto', fname=proto_fname, dir=self.work_dir,
219 length=len(proto_content))
220 with open(os.path.join(self.work_dir, proto_fname), 'w') as f:
221 f.write(proto_content)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700222
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700223 desc_content = decompress(proto_file.descriptor)
224 desc_fname = proto_fname.replace('.proto', '.desc')
225 log.debug('saving-descriptor', fname=desc_fname, dir=self.work_dir,
226 length=len(desc_content))
227 with open(os.path.join(self.work_dir, desc_fname), 'wb') as f:
228 f.write(desc_content)
Zsolt Haraszti21980762016-11-08 10:57:19 -0800229 return schemas.swagger_from
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700230
Zsolt Haraszti21980762016-11-08 10:57:19 -0800231 def _compile_proto_files(self, swagger_from):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700232 """
233 For each *.proto file in the work directory, compile the proto
234 file into the respective *_pb2.py file as well as generate the
235 web server gateway python file *_gw.py.
236 :return: None
237 """
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700238
239 chameleon_base_dir = os.path.abspath(os.path.join(
240 os.path.dirname(__file__), '../..'
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700241 ))
242
243 for fname in [f for f in os.listdir(self.work_dir)
244 if f.endswith('.proto')]:
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700245
Zsolt Haraszti21980762016-11-08 10:57:19 -0800246 need_swagger = fname == swagger_from
247 log.debug('compiling', file=fname, need_swagger=need_swagger)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700248 cmd = (
249 'cd %s && '
Zsolt Haraszti05b837a2016-10-05 00:18:57 -0700250 'env PATH=%s PYTHONPATH=%s '
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700251 'python -m grpc.tools.protoc '
252 '-I. '
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700253 '--python_out=. '
254 '--grpc_python_out=. '
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700255 '--plugin=protoc-gen-gw=%s/gw_gen.py '
256 '--gw_out=. '
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700257 '--plugin=protoc-gen-swagger=%s/swagger_gen.py '
Zsolt Haraszti21980762016-11-08 10:57:19 -0800258 '%s'
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700259 '%s' % (
260 self.work_dir,
261 ':'.join([os.environ['PATH'], self.plugin_dir]),
Zack Williamsf97bf092018-03-22 21:27:28 -0700262 chameleon_base_dir,
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700263 self.plugin_dir,
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700264 self.plugin_dir,
Zsolt Haraszti21980762016-11-08 10:57:19 -0800265 '--swagger_out=. ' if need_swagger else '',
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700266 fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700267 )
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700268 log.debug('executing', cmd=cmd, file=fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700269 os.system(cmd)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700270 log.info('compiled', file=fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700271
272 # test-load each _pb2 file to see all is right
273 if self.work_dir not in sys.path:
274 sys.path.insert(0, self.work_dir)
275
276 for fname in [f for f in os.listdir(self.work_dir)
277 if f.endswith('_pb2.py')]:
278 modname = fname[:-len('.py')]
279 log.debug('test-import', modname=modname)
280 _ = __import__(modname)
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700281
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800282 @inlineCallbacks
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800283 def invoke(self, stub, method_name, request, metadata, retry=1):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700284 """
285 Invoke a gRPC call to the remote server and return the response.
286 :param stub: Reference to the *_pb2 service stub
287 :param method_name: The method name inside the service stub
288 :param request: The request protobuf message
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800289 :param metadata: [(str, str), (str, str), ...]
290 :return: The response protobuf message and returned trailing metadata
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700291 """
292
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700293 if not self.connected:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700294 raise ServiceUnavailable()
295
296 try:
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800297 method = getattr(stub(self.channel), method_name)
298 response, rendezvous = method.with_call(request, metadata=metadata)
299 returnValue((response, rendezvous.trailing_metadata()))
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700300
301 except grpc._channel._Rendezvous, e:
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800302 code = e.code()
303 if code == grpc.StatusCode.UNAVAILABLE:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700304 e = ServiceUnavailable()
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800305
306 if self.connected:
307 self.connected = False
308 yield self.connect()
309 if retry > 0:
310 response = yield self.invoke(stub, method_name,
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800311 request, metadata,
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800312 retry=retry - 1)
313 returnValue(response)
314
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800315 elif code in (
316 grpc.StatusCode.NOT_FOUND,
317 grpc.StatusCode.INVALID_ARGUMENT,
Matteo Scandolo92f7f1f2017-04-28 15:56:29 -0700318 grpc.StatusCode.ALREADY_EXISTS,
319 grpc.StatusCode.UNAUTHENTICATED,
320 grpc.StatusCode.PERMISSION_DENIED):
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800321
322 pass # don't log error, these occur naturally
323
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700324 else:
325 log.exception(e)
326
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700327 raise e