Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 1 | # |
| 2 | # Copyright 2016 the original author or authors. |
| 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 | # limitations under the License. |
| 15 | # |
| 16 | |
| 17 | """ |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 18 | gRPC client meant to connect to a gRPC server endpoint, and query the |
Zsolt Haraszti | cba96de | 2016-11-06 14:04:55 -0800 | [diff] [blame] | 19 | end-point's schema by calling SchemaService.Schema(Empty) and all of its |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 20 | semantics are derived from the recovered schema. |
| 21 | """ |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 22 | |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 23 | import os |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 24 | import sys |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 25 | from random import randint |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 26 | from zlib import decompress |
| 27 | |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 28 | import grpc |
| 29 | from consul import Consul |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 30 | from grpc._channel import _Rendezvous |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 31 | from structlog import get_logger |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 32 | from twisted.internet import reactor |
Zsolt Haraszti | 2aac623 | 2016-11-23 11:18:23 -0800 | [diff] [blame^] | 33 | from twisted.internet.defer import inlineCallbacks, returnValue |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 34 | from werkzeug.exceptions import ServiceUnavailable |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 35 | |
Zsolt Haraszti | abae591 | 2016-10-16 19:30:34 -0700 | [diff] [blame] | 36 | from common.utils.asleep import asleep |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 37 | from chameleon.protos import third_party |
Zsolt Haraszti | cba96de | 2016-11-06 14:04:55 -0800 | [diff] [blame] | 38 | from chameleon.protos.schema_pb2 import SchemaServiceStub |
| 39 | from google.protobuf.empty_pb2 import Empty |
| 40 | |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 41 | |
| 42 | log = get_logger() |
| 43 | |
| 44 | |
| 45 | class GrpcClient(object): |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 46 | """ |
| 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 Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 52 | |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 53 | def __init__(self, consul_endpoint, work_dir, endpoint='localhost:50055', |
| 54 | reconnect_callback=None): |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 55 | self.consul_endpoint = consul_endpoint |
| 56 | self.endpoint = endpoint |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 57 | self.work_dir = work_dir |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 58 | self.reconnect_callback = reconnect_callback |
| 59 | |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 60 | self.plugin_dir = os.path.abspath(os.path.join( |
| 61 | os.path.dirname(__file__), '../protoc_plugins')) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 62 | |
| 63 | self.channel = None |
| 64 | self.schema = None |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 65 | self.retries = 0 |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 66 | self.shutting_down = False |
Zsolt Haraszti | 3cf3634 | 2016-10-05 20:40:19 -0700 | [diff] [blame] | 67 | self.connected = False |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 68 | |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 69 | def start(self): |
| 70 | log.debug('starting') |
Zsolt Haraszti | 3cf3634 | 2016-10-05 20:40:19 -0700 | [diff] [blame] | 71 | if not self.connected: |
| 72 | reactor.callLater(0, self.connect) |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 73 | log.info('started') |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 74 | return self |
| 75 | |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 76 | def stop(self): |
| 77 | log.debug('stopping') |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 78 | if self.shutting_down: |
| 79 | return |
| 80 | self.shutting_down = True |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 81 | log.info('stopped') |
| 82 | |
| 83 | def set_reconnect_callback(self, reconnect_callback): |
| 84 | self.reconnect_callback = reconnect_callback |
| 85 | return self |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 86 | |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 87 | @inlineCallbacks |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 88 | def connect(self): |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 89 | """ |
| 90 | (Re-)Connect to end-point |
| 91 | """ |
| 92 | |
Zsolt Haraszti | 3cf3634 | 2016-10-05 20:40:19 -0700 | [diff] [blame] | 93 | if self.shutting_down or self.connected: |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 94 | return |
| 95 | |
| 96 | try: |
| 97 | if self.endpoint.startswith('@'): |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 98 | _endpoint = self._get_endpoint_from_consul(self.endpoint[1:]) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 99 | else: |
| 100 | _endpoint = self.endpoint |
| 101 | |
| 102 | log.info('connecting', endpoint=_endpoint) |
| 103 | self.channel = grpc.insecure_channel(_endpoint) |
| 104 | |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 105 | swagger_from = self._retrieve_schema() |
| 106 | self._compile_proto_files(swagger_from) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 107 | self._clear_backoff() |
| 108 | |
Zsolt Haraszti | 3cf3634 | 2016-10-05 20:40:19 -0700 | [diff] [blame] | 109 | self.connected = True |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 110 | if self.reconnect_callback is not None: |
| 111 | reactor.callLater(0, self.reconnect_callback) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 112 | |
| 113 | return |
| 114 | |
| 115 | except _Rendezvous, e: |
| 116 | if e.code() == grpc.StatusCode.UNAVAILABLE: |
| 117 | log.info('grpc-endpoint-not-available') |
| 118 | else: |
| 119 | log.exception(e) |
| 120 | yield self._backoff('not-available') |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 121 | |
| 122 | except Exception, e: |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 123 | if not self.shutting_down: |
| 124 | log.exception('cannot-connect', endpoint=_endpoint) |
| 125 | yield self._backoff('unknown-error') |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 126 | |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 127 | reactor.callLater(0, self.connect) |
| 128 | |
| 129 | def _backoff(self, msg): |
| 130 | wait_time = self.RETRY_BACKOFF[min(self.retries, |
| 131 | len(self.RETRY_BACKOFF) - 1)] |
| 132 | self.retries += 1 |
| 133 | log.error(msg, retry_in=wait_time) |
| 134 | return asleep(wait_time) |
| 135 | |
| 136 | def _clear_backoff(self): |
| 137 | if self.retries: |
| 138 | log.info('reconnected', after_retries=self.retries) |
| 139 | self.retries = 0 |
| 140 | |
| 141 | def _get_endpoint_from_consul(self, service_name): |
| 142 | """ |
| 143 | Look up an appropriate grpc endpoint (host, port) from |
| 144 | consul, under the service name specified by service-name |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 145 | """ |
| 146 | host = self.consul_endpoint.split(':')[0].strip() |
| 147 | port = int(self.consul_endpoint.split(':')[1].strip()) |
| 148 | |
| 149 | consul = Consul(host=host, port=port) |
| 150 | _, services = consul.catalog.service(service_name) |
| 151 | |
| 152 | if len(services) == 0: |
| 153 | raise Exception('Cannot find service %s in consul' % service_name) |
| 154 | |
| 155 | # pick a random entry |
| 156 | # TODO should we prefer local IP addresses? Probably. |
| 157 | |
| 158 | service = services[randint(0, len(services) - 1)] |
| 159 | endpoint = '{}:{}'.format(service['ServiceAddress'], |
| 160 | service['ServicePort']) |
| 161 | return endpoint |
| 162 | |
| 163 | def _retrieve_schema(self): |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 164 | """ |
| 165 | Retrieve schema from gRPC end-point, and save all *.proto files in |
| 166 | the work directory. |
| 167 | """ |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 168 | assert isinstance(self.channel, grpc.Channel) |
| 169 | stub = SchemaServiceStub(self.channel) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 170 | # try: |
Zsolt Haraszti | cba96de | 2016-11-06 14:04:55 -0800 | [diff] [blame] | 171 | schemas = stub.GetSchema(Empty()) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 172 | # except _Rendezvous, e: |
| 173 | # if e.code == grpc.StatusCode.UNAVAILABLE: |
| 174 | # |
| 175 | # else: |
| 176 | # raise e |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 177 | |
| 178 | os.system('mkdir -p %s' % self.work_dir) |
| 179 | os.system('rm -fr /tmp/%s/*' % |
| 180 | self.work_dir.replace('/tmp/', '')) # safer |
| 181 | |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 182 | for proto_file in schemas.protos: |
| 183 | proto_fname = proto_file.file_name |
| 184 | proto_content = proto_file.proto |
| 185 | log.debug('saving-proto', fname=proto_fname, dir=self.work_dir, |
| 186 | length=len(proto_content)) |
| 187 | with open(os.path.join(self.work_dir, proto_fname), 'w') as f: |
| 188 | f.write(proto_content) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 189 | |
Zsolt Haraszti | dca6fa1 | 2016-11-03 16:56:17 -0700 | [diff] [blame] | 190 | desc_content = decompress(proto_file.descriptor) |
| 191 | desc_fname = proto_fname.replace('.proto', '.desc') |
| 192 | log.debug('saving-descriptor', fname=desc_fname, dir=self.work_dir, |
| 193 | length=len(desc_content)) |
| 194 | with open(os.path.join(self.work_dir, desc_fname), 'wb') as f: |
| 195 | f.write(desc_content) |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 196 | return schemas.swagger_from |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 197 | |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 198 | def _compile_proto_files(self, swagger_from): |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 199 | """ |
| 200 | For each *.proto file in the work directory, compile the proto |
| 201 | file into the respective *_pb2.py file as well as generate the |
| 202 | web server gateway python file *_gw.py. |
| 203 | :return: None |
| 204 | """ |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 205 | google_api_dir = os.path.abspath(os.path.join( |
Zsolt Haraszti | 46c7200 | 2016-10-10 09:55:30 -0700 | [diff] [blame] | 206 | os.path.dirname(__file__), '../protos/third_party' |
| 207 | )) |
| 208 | |
| 209 | chameleon_base_dir = os.path.abspath(os.path.join( |
| 210 | os.path.dirname(__file__), '../..' |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 211 | )) |
| 212 | |
| 213 | for fname in [f for f in os.listdir(self.work_dir) |
| 214 | if f.endswith('.proto')]: |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 215 | |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 216 | need_swagger = fname == swagger_from |
| 217 | log.debug('compiling', file=fname, need_swagger=need_swagger) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 218 | cmd = ( |
| 219 | 'cd %s && ' |
Zsolt Haraszti | 05b837a | 2016-10-05 00:18:57 -0700 | [diff] [blame] | 220 | 'env PATH=%s PYTHONPATH=%s ' |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 221 | 'python -m grpc.tools.protoc ' |
| 222 | '-I. ' |
| 223 | '-I%s ' |
| 224 | '--python_out=. ' |
| 225 | '--grpc_python_out=. ' |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 226 | '--plugin=protoc-gen-gw=%s/gw_gen.py ' |
| 227 | '--gw_out=. ' |
Zsolt Haraszti | 46c7200 | 2016-10-10 09:55:30 -0700 | [diff] [blame] | 228 | '--plugin=protoc-gen-swagger=%s/swagger_gen.py ' |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 229 | '%s' |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 230 | '%s' % ( |
| 231 | self.work_dir, |
| 232 | ':'.join([os.environ['PATH'], self.plugin_dir]), |
Zsolt Haraszti | 46c7200 | 2016-10-10 09:55:30 -0700 | [diff] [blame] | 233 | ':'.join([google_api_dir, chameleon_base_dir]), |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 234 | google_api_dir, |
Zsolt Haraszti | 46c7200 | 2016-10-10 09:55:30 -0700 | [diff] [blame] | 235 | self.plugin_dir, |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 236 | self.plugin_dir, |
Zsolt Haraszti | 2198076 | 2016-11-08 10:57:19 -0800 | [diff] [blame] | 237 | '--swagger_out=. ' if need_swagger else '', |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 238 | fname) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 239 | ) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 240 | log.debug('executing', cmd=cmd, file=fname) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 241 | os.system(cmd) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 242 | log.info('compiled', file=fname) |
Zsolt Haraszti | a9a12dc | 2016-09-27 13:48:35 -0700 | [diff] [blame] | 243 | |
| 244 | # test-load each _pb2 file to see all is right |
| 245 | if self.work_dir not in sys.path: |
| 246 | sys.path.insert(0, self.work_dir) |
| 247 | |
| 248 | for fname in [f for f in os.listdir(self.work_dir) |
| 249 | if f.endswith('_pb2.py')]: |
| 250 | modname = fname[:-len('.py')] |
| 251 | log.debug('test-import', modname=modname) |
| 252 | _ = __import__(modname) |
Zsolt Haraszti | 3d55ffc | 2016-10-03 22:26:41 -0700 | [diff] [blame] | 253 | |
Zsolt Haraszti | 2aac623 | 2016-11-23 11:18:23 -0800 | [diff] [blame^] | 254 | @inlineCallbacks |
| 255 | def invoke(self, stub, method_name, request, retry=1): |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 256 | """ |
| 257 | Invoke a gRPC call to the remote server and return the response. |
| 258 | :param stub: Reference to the *_pb2 service stub |
| 259 | :param method_name: The method name inside the service stub |
| 260 | :param request: The request protobuf message |
| 261 | :return: The response protobuf message |
| 262 | """ |
| 263 | |
Zsolt Haraszti | 3cf3634 | 2016-10-05 20:40:19 -0700 | [diff] [blame] | 264 | if not self.connected: |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 265 | raise ServiceUnavailable() |
| 266 | |
| 267 | try: |
| 268 | response = getattr(stub(self.channel), method_name)(request) |
Zsolt Haraszti | 2aac623 | 2016-11-23 11:18:23 -0800 | [diff] [blame^] | 269 | returnValue(response) |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 270 | |
| 271 | except grpc._channel._Rendezvous, e: |
| 272 | if e.code() == grpc.StatusCode.UNAVAILABLE: |
| 273 | e = ServiceUnavailable() |
Zsolt Haraszti | 2aac623 | 2016-11-23 11:18:23 -0800 | [diff] [blame^] | 274 | |
| 275 | if self.connected: |
| 276 | self.connected = False |
| 277 | yield self.connect() |
| 278 | if retry > 0: |
| 279 | response = yield self.invoke(stub, method_name, |
| 280 | request, |
| 281 | retry=retry - 1) |
| 282 | returnValue(response) |
| 283 | |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 284 | else: |
| 285 | log.exception(e) |
| 286 | |
Zsolt Haraszti | e7b6076 | 2016-10-05 17:49:27 -0700 | [diff] [blame] | 287 | raise e |