blob: a06e15d12e59c5a1960b2a878ab2675c7d511083 [file] [log] [blame]
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -07001#!/usr/bin/env python
2#
Zsolt Harasztiaccad4a2017-01-03 21:56:48 -08003# Copyright 2017 the original author or authors.
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -07004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18"""A REST protocol gateway to self-describing GRPC end-points"""
19
20import argparse
21import os
22import sys
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070023
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070024import yaml
25from twisted.internet.defer import inlineCallbacks
26
alshabib6ca05622017-01-31 14:08:36 -080027from chameleon.utils.dockerhelpers import get_my_containers_name
28from chameleon.utils.nethelpers import get_my_primary_local_ipv4
29from chameleon.utils.structlog_setup import setup_logging
30
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070031base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
32sys.path.append(base_dir)
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070033sys.path.append(os.path.join(base_dir, '/chameleon/protos/third_party'))
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070034
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070035from chameleon.grpc_client.grpc_client import GrpcClient
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -070036from chameleon.web_server.web_server import WebServer
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070037
38
39defs = dict(
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070040 config=os.environ.get('CONFIG', './chameleon.yml'),
Zsolt Haraszti58074322016-09-27 10:24:27 -070041 consul=os.environ.get('CONSUL', 'localhost:8500'),
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070042 external_host_address=os.environ.get('EXTERNAL_HOST_ADDRESS',
43 get_my_primary_local_ipv4()),
Zsolt Haraszti58074322016-09-27 10:24:27 -070044 grpc_endpoint=os.environ.get('GRPC_ENDPOINT', 'localhost:50055'),
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070045 fluentd=os.environ.get('FLUENTD', None),
Zsolt Haraszti58074322016-09-27 10:24:27 -070046 instance_id=os.environ.get('INSTANCE_ID', os.environ.get('HOSTNAME', '1')),
47 internal_host_address=os.environ.get('INTERNAL_HOST_ADDRESS',
48 get_my_primary_local_ipv4()),
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070049 rest_port=os.environ.get('REST_PORT', 8881),
Matteo Scandolo54356572017-04-24 18:52:28 -070050 work_dir=os.environ.get('WORK_DIR', '/tmp/chameleon'),
khenaidoo650ce812017-05-16 10:51:56 -040051 swagger_url=os.environ.get('SWAGGER_URL', ''),
ubuntu37975582017-07-01 17:53:19 -070052 enable_tls=os.environ.get('ENABLE_TLS',"True"),
53 key=os.environ.get('KEY','/chameleon/pki/voltha.key'),
54 cert=os.environ.get('CERT','/chameleon/pki/voltha.crt'),
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070055)
56
57
58def parse_args():
59
60 parser = argparse.ArgumentParser()
61
62 _help = ('Path to chameleon.yml config file (default: %s). '
63 'If relative, it is relative to main.py of chameleon.'
64 % defs['config'])
65 parser.add_argument('-c', '--config',
66 dest='config',
67 action='store',
68 default=defs['config'],
69 help=_help)
70
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070071 _help = '<hostname>:<port> to consul agent (default: %s)' % defs['consul']
72 parser.add_argument(
73 '-C', '--consul', dest='consul', action='store',
74 default=defs['consul'],
75 help=_help)
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070076
77 _help = ('<hostname> or <ip> at which Chameleon is reachable from outside '
78 'the cluster (default: %s)' % defs['external_host_address'])
79 parser.add_argument('-E', '--external-host-address',
80 dest='external_host_address',
81 action='store',
82 default=defs['external_host_address'],
83 help=_help)
84
85 _help = ('<hostname>:<port> to fluentd server (default: %s). (If not '
86 'specified (None), the address from the config file is used'
87 % defs['fluentd'])
88 parser.add_argument('-F', '--fluentd',
89 dest='fluentd',
90 action='store',
91 default=defs['fluentd'],
92 help=_help)
93
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070094 _help = ('gRPC end-point to connect to. It can either be a direct'
95 'definition in the form of <hostname>:<port>, or it can be an'
96 'indirect definition in the form of @<service-name> where'
97 '<service-name> is the name of the grpc service as registered'
98 'in consul (example: @voltha-grpc). (default: %s'
99 % defs['grpc_endpoint'])
100 parser.add_argument('-G', '--grpc-endpoint',
101 dest='grpc_endpoint',
102 action='store',
103 default=defs['grpc_endpoint'],
104 help=_help)
105
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700106 _help = ('<hostname> or <ip> at which Chameleon is reachable from inside'
107 'the cluster (default: %s)' % defs['internal_host_address'])
108 parser.add_argument('-H', '--internal-host-address',
109 dest='internal_host_address',
110 action='store',
111 default=defs['internal_host_address'],
112 help=_help)
113
114 _help = ('unique string id of this Chameleon instance (default: %s)'
115 % defs['instance_id'])
116 parser.add_argument('-i', '--instance-id',
117 dest='instance_id',
118 action='store',
119 default=defs['instance_id'],
120 help=_help)
121
122 _help = 'omit startup banner log lines'
123 parser.add_argument('-n', '--no-banner',
124 dest='no_banner',
125 action='store_true',
126 default=False,
127 help=_help)
128
129 _help = ('port number for the rest service (default: %d)'
130 % defs['rest_port'])
131 parser.add_argument('-R', '--rest-port',
132 dest='rest_port',
133 action='store',
134 type=int,
135 default=defs['rest_port'],
136 help=_help)
137
138 _help = "suppress debug and info logs"
139 parser.add_argument('-q', '--quiet',
140 dest='quiet',
141 action='count',
142 help=_help)
143
144 _help = 'enable verbose logging'
145 parser.add_argument('-v', '--verbose',
146 dest='verbose',
147 action='count',
148 help=_help)
149
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700150 _help = ('work dir to compile and assemble generated files (default=%s)'
151 % defs['work_dir'])
152 parser.add_argument('-w', '--work-dir',
153 dest='work_dir',
154 action='store',
155 default=defs['work_dir'],
156 help=_help)
157
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700158 _help = ('use docker container name as Chameleon instance id'
159 ' (overrides -i/--instance-id option)')
160 parser.add_argument('--instance-id-is-container-name',
161 dest='instance_id_is_container_name',
162 action='store_true',
163 default=False,
164 help=_help)
165
Matteo Scandolo54356572017-04-24 18:52:28 -0700166 _help = ('override swagger url (default=%s)'
167 % defs['swagger_url'])
168 parser.add_argument('-S', '--swagger-url',
169 dest='swagger_url',
170 action='store',
171 default=defs['swagger_url'],
172 help=_help)
173
ubuntu37975582017-07-01 17:53:19 -0700174 _help = ('Enable TLS or not (default: %s). '
175 % defs['enable_tls'])
176 parser.add_argument('-t', '--tls-enable',
177 dest='enable_tls',
178 action='store',
179 default=defs['enable_tls'],
180 help=_help)
181
182 _help = ('Path to chameleon ssl server private key (default: %s). '
183 'If relative, it is relative to main.py of chameleon.'
184 % defs['key'])
185 parser.add_argument('-k', '--key',
186 dest='key',
187 action='store',
188 default=defs['key'],
189 help=_help)
190
191 _help = ('Path to chameleon ssl server certificate file (default: %s). '
192 'If relative, it is relative to main.py of chameleon.'
193 % defs['cert'])
194 parser.add_argument('-f', '--cert-file',
195 dest='cert',
196 action='store',
197 default=defs['cert'],
198 help=_help)
199
200
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700201 args = parser.parse_args()
202
203 # post-processing
204
205 if args.instance_id_is_container_name:
206 args.instance_id = get_my_containers_name()
207
208 return args
209
210
211def load_config(args):
212 path = args.config
213 if path.startswith('.'):
214 dir = os.path.dirname(os.path.abspath(__file__))
215 path = os.path.join(dir, path)
216 path = os.path.abspath(path)
217 with open(path) as fd:
218 config = yaml.load(fd)
219 return config
220
221banner = r'''
222 ____ _ _
223 / ___| | |__ __ _ _ __ ___ ___ | | ___ ___ _ __
224 | | | '_ \ / _` | | '_ ` _ \ / _ \ | | / _ \ / _ \ | '_ \
225 | |___ | | | | | (_| | | | | | | | | __/ | | | __/ | (_) | | | | |
226 \____| |_| |_| \__,_| |_| |_| |_| \___| |_| \___| \___/ |_| |_|
227
228'''
Zsolt Haraszti1189c302016-12-28 15:08:23 -0800229
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700230def print_banner(log):
231 for line in banner.strip('\n').splitlines():
232 log.info(line)
233 log.info('(to stop: press Ctrl-C)')
234
235
236class Main(object):
237
238 def __init__(self):
239
240 self.args = args = parse_args()
241 self.config = load_config(args)
242
243 verbosity_adjust = (args.verbose or 0) - (args.quiet or 0)
244 self.log = setup_logging(self.config.get('logging', {}),
245 args.instance_id,
246 verbosity_adjust=verbosity_adjust,
247 fluentd=args.fluentd)
248
249 # components
250 self.rest_server = None
251 self.grpc_client = None
252
253 if not args.no_banner:
254 print_banner(self.log)
255
256 self.startup_components()
257
258 def start(self):
259 self.start_reactor() # will not return except Keyboard interrupt
260
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700261 @inlineCallbacks
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700262 def startup_components(self):
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800263 try:
264 self.log.info('starting-internal-components')
265 args = self.args
266 self.grpc_client = yield \
267 GrpcClient(args.consul, args.work_dir, args.grpc_endpoint)
ubuntu37975582017-07-01 17:53:19 -0700268
269 if args.enable_tls == "False":
270 self.log.info('tls-disabled-through-configuration')
271 self.rest_server = yield \
272 WebServer(args.rest_port, args.work_dir, args.swagger_url,\
273 self.grpc_client).start()
274 else:
275 # If TLS is enabled, but the server key or cert is not found,
276 # then automatically disable TLS
277 if not os.path.exists(args.key) or \
278 not os.path.exists(args.cert):
279 if not os.path.exists(args.key):
280 self.log.error('key-not-found')
281 if not os.path.exists(args.cert):
282 self.log.error('cert-not-found')
283 self.log.info('disabling-tls-due-to-missing-pki-files')
284 self.rest_server = yield \
285 WebServer(args.rest_port, args.work_dir,\
286 args.swagger_url,\
287 self.grpc_client).start()
288 else:
289 self.log.info('tls-enabled')
290 self.rest_server = yield \
291 WebServer(args.rest_port, args.work_dir,\
292 args.swagger_url,\
293 self.grpc_client, args.key,\
294 args.cert).start()
295
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800296 self.grpc_client.set_reconnect_callback(
297 self.rest_server.reload_generated_routes).start()
298 self.log.info('started-internal-services')
299 except Exception, e:
300 self.log.exception('startup-failed', e=e)
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700301
302 @inlineCallbacks
303 def shutdown_components(self):
304 """Execute before the reactor is shut down"""
305 self.log.info('exiting-on-keyboard-interrupt')
306 if self.rest_server is not None:
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700307 yield self.rest_server.stop()
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700308 if self.grpc_client is not None:
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700309 yield self.grpc_client.stop()
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700310
311 def start_reactor(self):
312 from twisted.internet import reactor
313 reactor.callWhenRunning(
314 lambda: self.log.info('twisted-reactor-started'))
315 reactor.addSystemEventTrigger('before', 'shutdown',
316 self.shutdown_components)
317 reactor.run()
318
319
320if __name__ == '__main__':
321 Main().start()