blob: 06c2ae380dc9f3d2b36f34e5fa0ddce77a3068c8 [file] [log] [blame]
Stephane Barbarie6e1bd502018-11-05 22:44:45 -05001#!/usr/bin/env python
2#
3# Copyright 2017 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#
17import argparse
18import os
19
20import yaml
21from twisted.internet import reactor
22from twisted.internet.defer import inlineCallbacks
23
24from common.structlog_setup import setup_logging
25from common.utils.dockerhelpers import get_my_containers_name
26from common.utils.nethelpers import get_my_primary_local_ipv4
27from connection_mgr import ConnectionManager
28
29defs = dict(
30 config=os.environ.get('CONFIG', './ofagent.yml'),
31 consul=os.environ.get('CONSUL', 'localhost:8500'),
32 controller=os.environ.get('CONTROLLER', 'localhost:6653'),
33 external_host_address=os.environ.get('EXTERNAL_HOST_ADDRESS',
34 get_my_primary_local_ipv4()),
35 grpc_endpoint=os.environ.get('GRPC_ENDPOINT', 'localhost:50055'),
36 instance_id=os.environ.get('INSTANCE_ID', os.environ.get('HOSTNAME', '1')),
37 internal_host_address=os.environ.get('INTERNAL_HOST_ADDRESS',
38 get_my_primary_local_ipv4()),
39 work_dir=os.environ.get('WORK_DIR', '/tmp/ofagent'),
40 key_file=os.environ.get('KEY_FILE', '/ofagent/pki/voltha.key'),
41 cert_file=os.environ.get('CERT_FILE', '/ofagent/pki/voltha.crt')
42)
43
44
45def parse_args():
46
47 parser = argparse.ArgumentParser()
48
49 _help = ('Path to ofagent.yml config file (default: %s). '
50 'If relative, it is relative to main.py of ofagent.'
51 % defs['config'])
52 parser.add_argument('-c', '--config',
53 dest='config',
54 action='store',
55 default=defs['config'],
56 help=_help)
57
58 _help = '<hostname>:<port> to consul agent (default: %s)' % defs['consul']
59 parser.add_argument(
60 '-C', '--consul', dest='consul', action='store',
61 default=defs['consul'],
62 help=_help)
63
64 _help = '<hostname1>:<port1> <hostname2>:<port2> <hostname3>:<port3> ... <hostnamen>:<portn> to openflow controller (default: %s)' % \
65 defs['controller']
66 parser.add_argument(
67 '-O', '--controller',nargs = '*', dest='controller', action='store',
68 default=defs['controller'],
69 help=_help)
70
71 _help = ('<hostname> or <ip> at which ofagent is reachable from outside '
72 'the cluster (default: %s)' % defs['external_host_address'])
73 parser.add_argument('-E', '--external-host-address',
74 dest='external_host_address',
75 action='store',
76 default=defs['external_host_address'],
77 help=_help)
78
79 _help = ('gRPC end-point to connect to. It can either be a direct'
80 'definition in the form of <hostname>:<port>, or it can be an'
81 'indirect definition in the form of @<service-name> where'
82 '<service-name> is the name of the grpc service as registered'
83 'in consul (example: @voltha-grpc). (default: %s'
84 % defs['grpc_endpoint'])
85 parser.add_argument('-G', '--grpc-endpoint',
86 dest='grpc_endpoint',
87 action='store',
88 default=defs['grpc_endpoint'],
89 help=_help)
90
91 _help = ('<hostname> or <ip> at which ofagent is reachable from inside'
92 'the cluster (default: %s)' % defs['internal_host_address'])
93 parser.add_argument('-H', '--internal-host-address',
94 dest='internal_host_address',
95 action='store',
96 default=defs['internal_host_address'],
97 help=_help)
98
99 _help = ('unique string id of this ofagent instance (default: %s)'
100 % defs['instance_id'])
101 parser.add_argument('-i', '--instance-id',
102 dest='instance_id',
103 action='store',
104 default=defs['instance_id'],
105 help=_help)
106
107 _help = 'omit startup banner log lines'
108 parser.add_argument('-n', '--no-banner',
109 dest='no_banner',
110 action='store_true',
111 default=False,
112 help=_help)
113
114 _help = "suppress debug and info logs"
115 parser.add_argument('-q', '--quiet',
116 dest='quiet',
117 action='count',
118 help=_help)
119
120 _help = 'enable verbose logging'
121 parser.add_argument('-v', '--verbose',
122 dest='verbose',
123 action='count',
124 help=_help)
125
126 _help = ('work dir to compile and assemble generated files (default=%s)'
127 % defs['work_dir'])
128 parser.add_argument('-w', '--work-dir',
129 dest='work_dir',
130 action='store',
131 default=defs['work_dir'],
132 help=_help)
133
134 _help = ('use docker container name as ofagent instance id'
135 ' (overrides -i/--instance-id option)')
136 parser.add_argument('--instance-id-is-container-name',
137 dest='instance_id_is_container_name',
138 action='store_true',
139 default=False,
140 help=_help)
141
142 _help = ('Specify this option to enable TLS security between ofagent \
143 and onos.')
144 parser.add_argument('-t', '--enable-tls',
145 dest='enable_tls',
146 action='store_true',
147 help=_help)
148
149 _help = ('key file to be used for tls security (default=%s)'
150 % defs['key_file'])
151 parser.add_argument('-k', '--key-file',
152 dest='key_file',
153 action='store',
154 default=defs['key_file'],
155 help=_help)
156
157 _help = ('certificate file to be used for tls security (default=%s)'
158 % defs['cert_file'])
159 parser.add_argument('-r', '--cert-file',
160 dest='cert_file',
161 action='store',
162 default=defs['cert_file'],
163 help=_help)
164
165 args = parser.parse_args()
166
167 # post-processing
168
169 if args.instance_id_is_container_name:
170 args.instance_id = get_my_containers_name()
171
172 return args
173
174
175def load_config(args):
176 path = args.config
177 if path.startswith('.'):
178 dir = os.path.dirname(os.path.abspath(__file__))
179 path = os.path.join(dir, path)
180 path = os.path.abspath(path)
181 with open(path) as fd:
182 config = yaml.load(fd)
183 return config
184
185banner = r'''
186 ___ _____ _ _
187 / _ \| ___/ \ __ _ ___ _ __ | |_
188| | | | |_ / _ \ / _` |/ _ \ '_ \| __|
189| |_| | _/ ___ \ (_| | __/ | | | |_
190 \___/|_|/_/ \_\__, |\___|_| |_|\__|
191 |___/
192'''
193
194def print_banner(log):
195 for line in banner.strip('\n').splitlines():
196 log.info(line)
197 log.info('(to stop: press Ctrl-C)')
198
199
200class Main(object):
201
202 def __init__(self):
203
204 self.args = args = parse_args()
205 self.config = load_config(args)
206 # May want to specify the gRPC timeout as an arg (in future)
207 # Right now, set a default value
208 self.grpc_timeout = 10
209
210 verbosity_adjust = (args.verbose or 0) - (args.quiet or 0)
211 self.log = setup_logging(self.config.get('logging', {}),
212 args.instance_id,
213 verbosity_adjust=verbosity_adjust)
214
215 # components
216 self.connection_manager = None
217
218 self.exiting = False
219
220 if not args.no_banner:
221 print_banner(self.log)
222
223 self.startup_components()
224
225 def start(self):
226 self.start_reactor() # will not return except Keyboard interrupt
227
228 @inlineCallbacks
229 def startup_components(self):
230 self.log.info('starting-internal-components')
231 args = self.args
232 self.connection_manager = yield ConnectionManager(
233 args.consul, args.grpc_endpoint, self.grpc_timeout,
234 args.controller, args.instance_id,
235 args.enable_tls, args.key_file, args.cert_file).start()
236 self.log.info('started-internal-services')
237
238 @inlineCallbacks
239 def shutdown_components(self):
240 """Execute before the reactor is shut down"""
241 self.log.info('exiting-on-keyboard-interrupt')
242 self.exiting = True
243 if self.connection_manager is not None:
244 yield self.connection_manager.stop()
245
246 def start_reactor(self):
247 reactor.callWhenRunning(
248 lambda: self.log.info('twisted-reactor-started'))
249
250 reactor.addSystemEventTrigger('before', 'shutdown',
251 self.shutdown_components)
252 reactor.run()
253
254
255if __name__ == '__main__':
256 Main().start()