blob: dbbca2f0325940c66b9459c8cc97107e65ec16f6 [file] [log] [blame]
Zsolt Haraszti86be6f12016-09-27 09:56:49 -07001#!/usr/bin/env python
2#
3# Copyright 2016 the original author or authors.
4#
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
23import time
24import yaml
25from twisted.internet.defer import inlineCallbacks
26
27base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28sys.path.append(base_dir)
29
30from chameleon.structlog_setup import setup_logging
31from chameleon.nethelpers import get_my_primary_local_ipv4
32from chameleon.dockerhelpers import get_my_containers_name
33
34
35defs = dict(
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070036 config=os.environ.get('CONFIG', './chameleon.yml'),
Zsolt Haraszti553826c2016-09-27 10:24:27 -070037 consul=os.environ.get('CONSUL', 'localhost:8500'),
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070038 external_host_address=os.environ.get('EXTERNAL_HOST_ADDRESS',
39 get_my_primary_local_ipv4()),
Zsolt Haraszti553826c2016-09-27 10:24:27 -070040 grpc_endpoint=os.environ.get('GRPC_ENDPOINT', 'localhost:50055'),
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070041 fluentd=os.environ.get('FLUENTD', None),
Zsolt Haraszti553826c2016-09-27 10:24:27 -070042 instance_id=os.environ.get('INSTANCE_ID', os.environ.get('HOSTNAME', '1')),
43 internal_host_address=os.environ.get('INTERNAL_HOST_ADDRESS',
44 get_my_primary_local_ipv4()),
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070045 rest_port=os.environ.get('REST_PORT', 8881),
46)
47
48
49def parse_args():
50
51 parser = argparse.ArgumentParser()
52
53 _help = ('Path to chameleon.yml config file (default: %s). '
54 'If relative, it is relative to main.py of chameleon.'
55 % defs['config'])
56 parser.add_argument('-c', '--config',
57 dest='config',
58 action='store',
59 default=defs['config'],
60 help=_help)
61
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070062 _help = '<hostname>:<port> to consul agent (default: %s)' % defs['consul']
63 parser.add_argument(
64 '-C', '--consul', dest='consul', action='store',
65 default=defs['consul'],
66 help=_help)
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070067
68 _help = ('<hostname> or <ip> at which Chameleon is reachable from outside '
69 'the cluster (default: %s)' % defs['external_host_address'])
70 parser.add_argument('-E', '--external-host-address',
71 dest='external_host_address',
72 action='store',
73 default=defs['external_host_address'],
74 help=_help)
75
76 _help = ('<hostname>:<port> to fluentd server (default: %s). (If not '
77 'specified (None), the address from the config file is used'
78 % defs['fluentd'])
79 parser.add_argument('-F', '--fluentd',
80 dest='fluentd',
81 action='store',
82 default=defs['fluentd'],
83 help=_help)
84
85 _help = ('<hostname> or <ip> at which Chameleon is reachable from inside'
86 'the cluster (default: %s)' % defs['internal_host_address'])
87 parser.add_argument('-H', '--internal-host-address',
88 dest='internal_host_address',
89 action='store',
90 default=defs['internal_host_address'],
91 help=_help)
92
93 _help = ('unique string id of this Chameleon instance (default: %s)'
94 % defs['instance_id'])
95 parser.add_argument('-i', '--instance-id',
96 dest='instance_id',
97 action='store',
98 default=defs['instance_id'],
99 help=_help)
100
101 _help = 'omit startup banner log lines'
102 parser.add_argument('-n', '--no-banner',
103 dest='no_banner',
104 action='store_true',
105 default=False,
106 help=_help)
107
108 _help = ('port number for the rest service (default: %d)'
109 % defs['rest_port'])
110 parser.add_argument('-R', '--rest-port',
111 dest='rest_port',
112 action='store',
113 type=int,
114 default=defs['rest_port'],
115 help=_help)
116
117 _help = "suppress debug and info logs"
118 parser.add_argument('-q', '--quiet',
119 dest='quiet',
120 action='count',
121 help=_help)
122
123 _help = 'enable verbose logging'
124 parser.add_argument('-v', '--verbose',
125 dest='verbose',
126 action='count',
127 help=_help)
128
129 _help = ('use docker container name as Chameleon instance id'
130 ' (overrides -i/--instance-id option)')
131 parser.add_argument('--instance-id-is-container-name',
132 dest='instance_id_is_container_name',
133 action='store_true',
134 default=False,
135 help=_help)
136
137 args = parser.parse_args()
138
139 # post-processing
140
141 if args.instance_id_is_container_name:
142 args.instance_id = get_my_containers_name()
143
144 return args
145
146
147def load_config(args):
148 path = args.config
149 if path.startswith('.'):
150 dir = os.path.dirname(os.path.abspath(__file__))
151 path = os.path.join(dir, path)
152 path = os.path.abspath(path)
153 with open(path) as fd:
154 config = yaml.load(fd)
155 return config
156
157banner = r'''
158 ____ _ _
159 / ___| | |__ __ _ _ __ ___ ___ | | ___ ___ _ __
160 | | | '_ \ / _` | | '_ ` _ \ / _ \ | | / _ \ / _ \ | '_ \
161 | |___ | | | | | (_| | | | | | | | | __/ | | | __/ | (_) | | | | |
162 \____| |_| |_| \__,_| |_| |_| |_| \___| |_| \___| \___/ |_| |_|
163
164'''
165def print_banner(log):
166 for line in banner.strip('\n').splitlines():
167 log.info(line)
168 log.info('(to stop: press Ctrl-C)')
169
170
171class Main(object):
172
173 def __init__(self):
174
175 self.args = args = parse_args()
176 self.config = load_config(args)
177
178 verbosity_adjust = (args.verbose or 0) - (args.quiet or 0)
179 self.log = setup_logging(self.config.get('logging', {}),
180 args.instance_id,
181 verbosity_adjust=verbosity_adjust,
182 fluentd=args.fluentd)
183
184 # components
185 self.rest_server = None
186 self.grpc_client = None
187
188 if not args.no_banner:
189 print_banner(self.log)
190
191 self.startup_components()
192
193 def start(self):
194 self.start_reactor() # will not return except Keyboard interrupt
195
196 def startup_components(self):
197 self.log.info('starting-internal-components')
198
199 # TODO init client
200 # TODO init server
201
202 self.log.info('started-internal-services')
203
204 @inlineCallbacks
205 def shutdown_components(self):
206 """Execute before the reactor is shut down"""
207 self.log.info('exiting-on-keyboard-interrupt')
208 if self.rest_server is not None:
209 yield self.rest_server.shutdown()
210 if self.grpc_client is not None:
211 yield self.grpc_client.shutdown()
212
213 def start_reactor(self):
214 from twisted.internet import reactor
215 reactor.callWhenRunning(
216 lambda: self.log.info('twisted-reactor-started'))
217 reactor.addSystemEventTrigger('before', 'shutdown',
218 self.shutdown_components)
219 reactor.run()
220
221
222if __name__ == '__main__':
223 Main().start()