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