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