blob: d394c4ef41fc80b1183d5f4788124c60c31e2234 [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'),
51 swagger_url=os.environ.get('SWAGGER_URL', '/'),
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070052)
53
54
55def parse_args():
56
57 parser = argparse.ArgumentParser()
58
59 _help = ('Path to chameleon.yml config file (default: %s). '
60 'If relative, it is relative to main.py of chameleon.'
61 % defs['config'])
62 parser.add_argument('-c', '--config',
63 dest='config',
64 action='store',
65 default=defs['config'],
66 help=_help)
67
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070068 _help = '<hostname>:<port> to consul agent (default: %s)' % defs['consul']
69 parser.add_argument(
70 '-C', '--consul', dest='consul', action='store',
71 default=defs['consul'],
72 help=_help)
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -070073
74 _help = ('<hostname> or <ip> at which Chameleon is reachable from outside '
75 'the cluster (default: %s)' % defs['external_host_address'])
76 parser.add_argument('-E', '--external-host-address',
77 dest='external_host_address',
78 action='store',
79 default=defs['external_host_address'],
80 help=_help)
81
82 _help = ('<hostname>:<port> to fluentd server (default: %s). (If not '
83 'specified (None), the address from the config file is used'
84 % defs['fluentd'])
85 parser.add_argument('-F', '--fluentd',
86 dest='fluentd',
87 action='store',
88 default=defs['fluentd'],
89 help=_help)
90
Zsolt Harasztia9a12dc2016-09-27 13:48:35 -070091 _help = ('gRPC end-point to connect to. It can either be a direct'
92 'definition in the form of <hostname>:<port>, or it can be an'
93 'indirect definition in the form of @<service-name> where'
94 '<service-name> is the name of the grpc service as registered'
95 'in consul (example: @voltha-grpc). (default: %s'
96 % defs['grpc_endpoint'])
97 parser.add_argument('-G', '--grpc-endpoint',
98 dest='grpc_endpoint',
99 action='store',
100 default=defs['grpc_endpoint'],
101 help=_help)
102
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700103 _help = ('<hostname> or <ip> at which Chameleon is reachable from inside'
104 'the cluster (default: %s)' % defs['internal_host_address'])
105 parser.add_argument('-H', '--internal-host-address',
106 dest='internal_host_address',
107 action='store',
108 default=defs['internal_host_address'],
109 help=_help)
110
111 _help = ('unique string id of this Chameleon instance (default: %s)'
112 % defs['instance_id'])
113 parser.add_argument('-i', '--instance-id',
114 dest='instance_id',
115 action='store',
116 default=defs['instance_id'],
117 help=_help)
118
119 _help = 'omit startup banner log lines'
120 parser.add_argument('-n', '--no-banner',
121 dest='no_banner',
122 action='store_true',
123 default=False,
124 help=_help)
125
126 _help = ('port number for the rest service (default: %d)'
127 % defs['rest_port'])
128 parser.add_argument('-R', '--rest-port',
129 dest='rest_port',
130 action='store',
131 type=int,
132 default=defs['rest_port'],
133 help=_help)
134
135 _help = "suppress debug and info logs"
136 parser.add_argument('-q', '--quiet',
137 dest='quiet',
138 action='count',
139 help=_help)
140
141 _help = 'enable verbose logging'
142 parser.add_argument('-v', '--verbose',
143 dest='verbose',
144 action='count',
145 help=_help)
146
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700147 _help = ('work dir to compile and assemble generated files (default=%s)'
148 % defs['work_dir'])
149 parser.add_argument('-w', '--work-dir',
150 dest='work_dir',
151 action='store',
152 default=defs['work_dir'],
153 help=_help)
154
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700155 _help = ('use docker container name as Chameleon instance id'
156 ' (overrides -i/--instance-id option)')
157 parser.add_argument('--instance-id-is-container-name',
158 dest='instance_id_is_container_name',
159 action='store_true',
160 default=False,
161 help=_help)
162
Matteo Scandolo54356572017-04-24 18:52:28 -0700163 _help = ('override swagger url (default=%s)'
164 % defs['swagger_url'])
165 parser.add_argument('-S', '--swagger-url',
166 dest='swagger_url',
167 action='store',
168 default=defs['swagger_url'],
169 help=_help)
170
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700171 args = parser.parse_args()
172
173 # post-processing
174
175 if args.instance_id_is_container_name:
176 args.instance_id = get_my_containers_name()
177
178 return args
179
180
181def load_config(args):
182 path = args.config
183 if path.startswith('.'):
184 dir = os.path.dirname(os.path.abspath(__file__))
185 path = os.path.join(dir, path)
186 path = os.path.abspath(path)
187 with open(path) as fd:
188 config = yaml.load(fd)
189 return config
190
191banner = r'''
192 ____ _ _
193 / ___| | |__ __ _ _ __ ___ ___ | | ___ ___ _ __
194 | | | '_ \ / _` | | '_ ` _ \ / _ \ | | / _ \ / _ \ | '_ \
195 | |___ | | | | | (_| | | | | | | | | __/ | | | __/ | (_) | | | | |
196 \____| |_| |_| \__,_| |_| |_| |_| \___| |_| \___| \___/ |_| |_|
197
198'''
Zsolt Haraszti1189c302016-12-28 15:08:23 -0800199
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700200def print_banner(log):
201 for line in banner.strip('\n').splitlines():
202 log.info(line)
203 log.info('(to stop: press Ctrl-C)')
204
205
206class Main(object):
207
208 def __init__(self):
209
210 self.args = args = parse_args()
211 self.config = load_config(args)
212
213 verbosity_adjust = (args.verbose or 0) - (args.quiet or 0)
214 self.log = setup_logging(self.config.get('logging', {}),
215 args.instance_id,
216 verbosity_adjust=verbosity_adjust,
217 fluentd=args.fluentd)
218
219 # components
220 self.rest_server = None
221 self.grpc_client = None
222
223 if not args.no_banner:
224 print_banner(self.log)
225
226 self.startup_components()
227
228 def start(self):
229 self.start_reactor() # will not return except Keyboard interrupt
230
Zsolt Haraszti3d55ffc2016-10-03 22:26:41 -0700231 @inlineCallbacks
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700232 def startup_components(self):
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800233 try:
234 self.log.info('starting-internal-components')
235 args = self.args
236 self.grpc_client = yield \
237 GrpcClient(args.consul, args.work_dir, args.grpc_endpoint)
238 self.rest_server = yield \
Matteo Scandolo54356572017-04-24 18:52:28 -0700239 WebServer(args.rest_port, args.work_dir, args.swagger_url, self.grpc_client).start()
Zsolt Haraszti267a9062016-12-26 23:11:15 -0800240 self.grpc_client.set_reconnect_callback(
241 self.rest_server.reload_generated_routes).start()
242 self.log.info('started-internal-services')
243 except Exception, e:
244 self.log.exception('startup-failed', e=e)
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700245
246 @inlineCallbacks
247 def shutdown_components(self):
248 """Execute before the reactor is shut down"""
249 self.log.info('exiting-on-keyboard-interrupt')
250 if self.rest_server is not None:
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700251 yield self.rest_server.stop()
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700252 if self.grpc_client is not None:
Zsolt Harasztidca6fa12016-11-03 16:56:17 -0700253 yield self.grpc_client.stop()
Zsolt Harasztid7ae9d52016-09-27 09:56:49 -0700254
255 def start_reactor(self):
256 from twisted.internet import reactor
257 reactor.callWhenRunning(
258 lambda: self.log.info('twisted-reactor-started'))
259 reactor.addSystemEventTrigger('before', 'shutdown',
260 self.shutdown_components)
261 reactor.run()
262
263
264if __name__ == '__main__':
265 Main().start()