blob: 730887c9efee7e5cbb692e3179fb68126bf77d95 [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
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070028import grpc
29from consul import Consul
Zsolt Harasztie7b60762016-10-05 17:49:27 -070030from grpc._channel import _Rendezvous
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070031from structlog import get_logger
Zsolt Harasztie7b60762016-10-05 17:49:27 -070032from twisted.internet import reactor
Zsolt Haraszti2aac6232016-11-23 11:18:23 -080033from twisted.internet.defer import inlineCallbacks, returnValue
Zsolt Harasztie7b60762016-10-05 17:49:27 -070034from werkzeug.exceptions import ServiceUnavailable
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070035
Zsolt Haraszti21980762016-11-08 10:57:19 -080036from chameleon.protos import third_party
Zsolt Haraszticba96de2016-11-06 14:04:55 -080037from chameleon.protos.schema_pb2 import SchemaServiceStub
38from 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 Baker73784f12018-02-20 12:05:35 -080090 def connectivity_callback(self, connectivity):
91 if (self.was_connected) and (connectivity in [connectivity.TRANSIENT_FAILURE, connectivity.FATAL_FAILURE, connectivity.SHUTDOWN]):
92 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
Zsolt Harasztie7b60762016-10-05 17:49:27 -070098 @inlineCallbacks
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070099 def connect(self):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700100 """
101 (Re-)Connect to end-point
102 """
103
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700104 if self.shutting_down or self.connected:
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700105 return
106
107 try:
108 if self.endpoint.startswith('@'):
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800109 _endpoint = yield self._get_endpoint_from_consul(
110 self.endpoint[1:])
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700111 else:
112 _endpoint = self.endpoint
113
Scott Baker74548db2017-02-15 14:16:13 -0800114 if self.credentials:
115 log.info('securely connecting', endpoint=_endpoint)
116 self.channel = grpc.secure_channel(_endpoint, self.credentials)
117 else:
118 log.info('insecurely connecting', endpoint=_endpoint)
119 self.channel = grpc.insecure_channel(_endpoint)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700120
Scott Baker73784f12018-02-20 12:05:35 -0800121 if self.restart_on_disconnect:
122 self.channel.subscribe(self.connectivity_callback)
123
Zsolt Haraszti21980762016-11-08 10:57:19 -0800124 swagger_from = self._retrieve_schema()
125 self._compile_proto_files(swagger_from)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700126 self._clear_backoff()
127
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700128 self.connected = True
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700129 if self.reconnect_callback is not None:
130 reactor.callLater(0, self.reconnect_callback)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700131
132 return
133
134 except _Rendezvous, e:
135 if e.code() == grpc.StatusCode.UNAVAILABLE:
136 log.info('grpc-endpoint-not-available')
137 else:
Sapan Bhatiadd273342017-08-30 15:27:55 -0400138 log.exception('rendezvous error', e=e)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700139 yield self._backoff('not-available')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700140
141 except Exception, e:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700142 if not self.shutting_down:
143 log.exception('cannot-connect', endpoint=_endpoint)
144 yield self._backoff('unknown-error')
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700145
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700146 reactor.callLater(0, self.connect)
147
148 def _backoff(self, msg):
149 wait_time = self.RETRY_BACKOFF[min(self.retries,
150 len(self.RETRY_BACKOFF) - 1)]
151 self.retries += 1
152 log.error(msg, retry_in=wait_time)
153 return asleep(wait_time)
154
155 def _clear_backoff(self):
156 if self.retries:
157 log.info('reconnected', after_retries=self.retries)
158 self.retries = 0
159
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800160 @inlineCallbacks
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700161 def _get_endpoint_from_consul(self, service_name):
162 """
163 Look up an appropriate grpc endpoint (host, port) from
164 consul, under the service name specified by service-name
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700165 """
166 host = self.consul_endpoint.split(':')[0].strip()
167 port = int(self.consul_endpoint.split(':')[1].strip())
168
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800169 while True:
170 log.debug('consul-lookup', host=host, port=port)
171 consul = Consul(host=host, port=port)
172 _, services = consul.catalog.service(service_name)
173 log.debug('consul-response', services=services)
174 if services:
175 break
176 log.warning('no-service', consul_host=host, consul_port=port,
177 service_name=service_name)
178 yield asleep(1.0)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700179
alshabibc8224902017-01-26 11:59:52 -0800180 # pick local addresses when resolving a service via consul
181 # see CORD-815 (https://jira.opencord.org/browse/CORD-815)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700182
183 service = services[randint(0, len(services) - 1)]
184 endpoint = '{}:{}'.format(service['ServiceAddress'],
185 service['ServicePort'])
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800186 returnValue(endpoint)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700187
188 def _retrieve_schema(self):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700189 """
190 Retrieve schema from gRPC end-point, and save all *.proto files in
191 the work directory.
192 """
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700193 assert isinstance(self.channel, grpc.Channel)
194 stub = SchemaServiceStub(self.channel)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700195 # try:
Zsolt Haraszticba96de2016-11-06 14:04:55 -0800196 schemas = stub.GetSchema(Empty())
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700197 # except _Rendezvous, e:
198 # if e.code == grpc.StatusCode.UNAVAILABLE:
199 #
200 # else:
201 # raise e
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700202
203 os.system('mkdir -p %s' % self.work_dir)
204 os.system('rm -fr /tmp/%s/*' %
205 self.work_dir.replace('/tmp/', '')) # safer
206
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700207 for proto_file in schemas.protos:
208 proto_fname = proto_file.file_name
209 proto_content = proto_file.proto
210 log.debug('saving-proto', fname=proto_fname, dir=self.work_dir,
211 length=len(proto_content))
212 with open(os.path.join(self.work_dir, proto_fname), 'w') as f:
213 f.write(proto_content)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700214
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700215 desc_content = decompress(proto_file.descriptor)
216 desc_fname = proto_fname.replace('.proto', '.desc')
217 log.debug('saving-descriptor', fname=desc_fname, dir=self.work_dir,
218 length=len(desc_content))
219 with open(os.path.join(self.work_dir, desc_fname), 'wb') as f:
220 f.write(desc_content)
Zsolt Haraszti21980762016-11-08 10:57:19 -0800221 return schemas.swagger_from
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700222
Zsolt Haraszti21980762016-11-08 10:57:19 -0800223 def _compile_proto_files(self, swagger_from):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700224 """
225 For each *.proto file in the work directory, compile the proto
226 file into the respective *_pb2.py file as well as generate the
227 web server gateway python file *_gw.py.
228 :return: None
229 """
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700230 google_api_dir = os.path.abspath(os.path.join(
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700231 os.path.dirname(__file__), '../protos/third_party'
232 ))
233
234 chameleon_base_dir = os.path.abspath(os.path.join(
235 os.path.dirname(__file__), '../..'
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700236 ))
237
238 for fname in [f for f in os.listdir(self.work_dir)
239 if f.endswith('.proto')]:
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700240
Zsolt Haraszti21980762016-11-08 10:57:19 -0800241 need_swagger = fname == swagger_from
242 log.debug('compiling', file=fname, need_swagger=need_swagger)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700243 cmd = (
244 'cd %s && '
Zsolt Haraszti05b837a2016-10-05 00:18:57 -0700245 'env PATH=%s PYTHONPATH=%s '
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700246 'python -m grpc.tools.protoc '
247 '-I. '
248 '-I%s '
249 '--python_out=. '
250 '--grpc_python_out=. '
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700251 '--plugin=protoc-gen-gw=%s/gw_gen.py '
252 '--gw_out=. '
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700253 '--plugin=protoc-gen-swagger=%s/swagger_gen.py '
Zsolt Haraszti21980762016-11-08 10:57:19 -0800254 '%s'
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700255 '%s' % (
256 self.work_dir,
257 ':'.join([os.environ['PATH'], self.plugin_dir]),
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700258 ':'.join([google_api_dir, chameleon_base_dir]),
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700259 google_api_dir,
Zsolt Haraszti46c72002016-10-10 09:55:30 -0700260 self.plugin_dir,
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700261 self.plugin_dir,
Zsolt Haraszti21980762016-11-08 10:57:19 -0800262 '--swagger_out=. ' if need_swagger else '',
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700263 fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700264 )
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700265 log.debug('executing', cmd=cmd, file=fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700266 os.system(cmd)
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700267 log.info('compiled', file=fname)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -0700268
269 # test-load each _pb2 file to see all is right
270 if self.work_dir not in sys.path:
271 sys.path.insert(0, self.work_dir)
272
273 for fname in [f for f in os.listdir(self.work_dir)
274 if f.endswith('_pb2.py')]:
275 modname = fname[:-len('.py')]
276 log.debug('test-import', modname=modname)
277 _ = __import__(modname)
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700278
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800279 @inlineCallbacks
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800280 def invoke(self, stub, method_name, request, metadata, retry=1):
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700281 """
282 Invoke a gRPC call to the remote server and return the response.
283 :param stub: Reference to the *_pb2 service stub
284 :param method_name: The method name inside the service stub
285 :param request: The request protobuf message
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800286 :param metadata: [(str, str), (str, str), ...]
287 :return: The response protobuf message and returned trailing metadata
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700288 """
289
Zsolt Haraszti3cf36342016-10-05 20:40:19 -0700290 if not self.connected:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700291 raise ServiceUnavailable()
292
293 try:
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800294 method = getattr(stub(self.channel), method_name)
295 response, rendezvous = method.with_call(request, metadata=metadata)
296 returnValue((response, rendezvous.trailing_metadata()))
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700297
298 except grpc._channel._Rendezvous, e:
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800299 code = e.code()
300 if code == grpc.StatusCode.UNAVAILABLE:
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700301 e = ServiceUnavailable()
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800302
303 if self.connected:
304 self.connected = False
305 yield self.connect()
306 if retry > 0:
307 response = yield self.invoke(stub, method_name,
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800308 request, metadata,
Zsolt Haraszti2aac6232016-11-23 11:18:23 -0800309 retry=retry - 1)
310 returnValue(response)
311
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800312 elif code in (
313 grpc.StatusCode.NOT_FOUND,
314 grpc.StatusCode.INVALID_ARGUMENT,
Matteo Scandolo92f7f1f2017-04-28 15:56:29 -0700315 grpc.StatusCode.ALREADY_EXISTS,
316 grpc.StatusCode.UNAUTHENTICATED,
317 grpc.StatusCode.PERMISSION_DENIED):
Zsolt Harasztic8cfdf32016-11-28 14:28:39 -0800318
319 pass # don't log error, these occur naturally
320
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700321 else:
322 log.exception(e)
323
Zsolt Harasztie7b60762016-10-05 17:49:27 -0700324 raise e