blob: 58afe1556103d4a0181b445050946f39cd476832 [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
Thomas Lee S9f0da512019-09-27 21:09:25 +053021import SocketServer
22
23from probe import Probe
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050024from twisted.internet import reactor
25from twisted.internet.defer import inlineCallbacks
26
William Kurkianfc0dcda2019-04-08 16:54:36 -040027from pyvoltha.common.structlog_setup import setup_logging
28from pyvoltha.common.utils.dockerhelpers import get_my_containers_name
29from pyvoltha.common.utils.nethelpers import get_my_primary_local_ipv4
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050030from connection_mgr import ConnectionManager
31
32defs = dict(
33 config=os.environ.get('CONFIG', './ofagent.yml'),
34 consul=os.environ.get('CONSUL', 'localhost:8500'),
35 controller=os.environ.get('CONTROLLER', 'localhost:6653'),
Thomas Lee S9f0da512019-09-27 21:09:25 +053036 probe=os.environ.get('PROBE', ':8080'),
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050037 external_host_address=os.environ.get('EXTERNAL_HOST_ADDRESS',
38 get_my_primary_local_ipv4()),
39 grpc_endpoint=os.environ.get('GRPC_ENDPOINT', 'localhost:50055'),
Richard Jankowski46464e92019-03-05 11:53:55 -050040 grpc_timeout=os.environ.get('GRPC_TIMEOUT', '10'),
41 core_binding_key=os.environ.get('CORE_BINDING_KEY', 'voltha_backend_name'),
khenaidoo43aa6bd2019-05-29 13:35:13 -040042 core_transaction_key=os.environ.get('CORE_TRANSACTION_KEY', 'voltha_serial_number'),
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050043 instance_id=os.environ.get('INSTANCE_ID', os.environ.get('HOSTNAME', '1')),
44 internal_host_address=os.environ.get('INTERNAL_HOST_ADDRESS',
45 get_my_primary_local_ipv4()),
46 work_dir=os.environ.get('WORK_DIR', '/tmp/ofagent'),
47 key_file=os.environ.get('KEY_FILE', '/ofagent/pki/voltha.key'),
48 cert_file=os.environ.get('CERT_FILE', '/ofagent/pki/voltha.crt')
49)
50
51
52def parse_args():
53
54 parser = argparse.ArgumentParser()
55
56 _help = ('Path to ofagent.yml config file (default: %s). '
57 'If relative, it is relative to main.py of ofagent.'
58 % defs['config'])
59 parser.add_argument('-c', '--config',
60 dest='config',
61 action='store',
62 default=defs['config'],
63 help=_help)
64
65 _help = '<hostname>:<port> to consul agent (default: %s)' % defs['consul']
66 parser.add_argument(
67 '-C', '--consul', dest='consul', action='store',
68 default=defs['consul'],
69 help=_help)
70
71 _help = '<hostname1>:<port1> <hostname2>:<port2> <hostname3>:<port3> ... <hostnamen>:<portn> to openflow controller (default: %s)' % \
72 defs['controller']
73 parser.add_argument(
74 '-O', '--controller',nargs = '*', dest='controller', action='store',
75 default=defs['controller'],
76 help=_help)
77
Thomas Lee S9f0da512019-09-27 21:09:25 +053078 _help = '<hostname>:<port> for liveness and readiness probes (default: %s)' % defs['probe']
79 parser.add_argument(
80 '-P', '--probe', dest='probe', action='store',
81 default=defs['probe'],
82 help=_help)
83
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050084 _help = ('<hostname> or <ip> at which ofagent is reachable from outside '
85 'the cluster (default: %s)' % defs['external_host_address'])
86 parser.add_argument('-E', '--external-host-address',
87 dest='external_host_address',
88 action='store',
89 default=defs['external_host_address'],
90 help=_help)
91
Richard Jankowski46464e92019-03-05 11:53:55 -050092 _help = ('gRPC end-point to connect to. It can either be a direct '
93 'definition in the form of <hostname>:<port>, or it can be an '
94 'indirect definition in the form of @<service-name> where '
95 '<service-name> is the name of the grpc service as registered '
96 'in consul (example: @voltha-grpc). (default: %s)'
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050097 % defs['grpc_endpoint'])
98 parser.add_argument('-G', '--grpc-endpoint',
99 dest='grpc_endpoint',
100 action='store',
101 default=defs['grpc_endpoint'],
102 help=_help)
103
Richard Jankowski46464e92019-03-05 11:53:55 -0500104 _help = 'gRPC timeout in seconds (default: %s)' % defs['grpc_timeout']
105 parser.add_argument('-T', '--grpc-timeout',
106 dest='grpc_timeout',
107 action='store',
108 default=defs['grpc_timeout'],
109 help=_help)
110
111 _help = ('The name of the meta-key whose value is the rw-core group '
112 'to which the ofagent\'s gRPC client is bound. '
113 '(default: %s)' % defs['core_binding_key'])
114 parser.add_argument('-B', '--core-binding-key',
115 dest='core_binding_key',
116 action='store',
117 default=defs['core_binding_key'],
118 help=_help)
119
khenaidoo43aa6bd2019-05-29 13:35:13 -0400120 _help = ('The name of the meta-key whose value is the transaction ID '
121 'used by the OFAgent to send requests to the Voltha RW Core. '
122 '(default: %s)' % defs['core_transaction_key'])
123 parser.add_argument('-ctk', '--core_transaction_key',
124 dest='core_transaction_key',
125 action='store',
126 default=defs['core_transaction_key'],
127 help=_help)
128
Richard Jankowski46464e92019-03-05 11:53:55 -0500129 _help = ('<hostname> or <ip> at which ofagent is reachable from inside '
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500130 'the cluster (default: %s)' % defs['internal_host_address'])
131 parser.add_argument('-H', '--internal-host-address',
132 dest='internal_host_address',
133 action='store',
134 default=defs['internal_host_address'],
135 help=_help)
136
137 _help = ('unique string id of this ofagent instance (default: %s)'
138 % defs['instance_id'])
139 parser.add_argument('-i', '--instance-id',
140 dest='instance_id',
141 action='store',
142 default=defs['instance_id'],
143 help=_help)
144
145 _help = 'omit startup banner log lines'
146 parser.add_argument('-n', '--no-banner',
147 dest='no_banner',
148 action='store_true',
149 default=False,
150 help=_help)
151
152 _help = "suppress debug and info logs"
153 parser.add_argument('-q', '--quiet',
154 dest='quiet',
155 action='count',
156 help=_help)
157
158 _help = 'enable verbose logging'
159 parser.add_argument('-v', '--verbose',
160 dest='verbose',
161 action='count',
162 help=_help)
163
164 _help = ('work dir to compile and assemble generated files (default=%s)'
165 % defs['work_dir'])
166 parser.add_argument('-w', '--work-dir',
167 dest='work_dir',
168 action='store',
169 default=defs['work_dir'],
170 help=_help)
171
172 _help = ('use docker container name as ofagent instance id'
173 ' (overrides -i/--instance-id option)')
174 parser.add_argument('--instance-id-is-container-name',
175 dest='instance_id_is_container_name',
176 action='store_true',
177 default=False,
178 help=_help)
179
180 _help = ('Specify this option to enable TLS security between ofagent \
181 and onos.')
182 parser.add_argument('-t', '--enable-tls',
183 dest='enable_tls',
184 action='store_true',
185 help=_help)
186
187 _help = ('key file to be used for tls security (default=%s)'
188 % defs['key_file'])
189 parser.add_argument('-k', '--key-file',
190 dest='key_file',
191 action='store',
192 default=defs['key_file'],
193 help=_help)
194
195 _help = ('certificate file to be used for tls security (default=%s)'
196 % defs['cert_file'])
197 parser.add_argument('-r', '--cert-file',
198 dest='cert_file',
199 action='store',
200 default=defs['cert_file'],
201 help=_help)
202
203 args = parser.parse_args()
204
205 # post-processing
206
207 if args.instance_id_is_container_name:
208 args.instance_id = get_my_containers_name()
209
210 return args
211
212
213def load_config(args):
214 path = args.config
215 if path.startswith('.'):
216 dir = os.path.dirname(os.path.abspath(__file__))
217 path = os.path.join(dir, path)
218 path = os.path.abspath(path)
219 with open(path) as fd:
220 config = yaml.load(fd)
221 return config
222
223banner = r'''
224 ___ _____ _ _
225 / _ \| ___/ \ __ _ ___ _ __ | |_
226| | | | |_ / _ \ / _` |/ _ \ '_ \| __|
227| |_| | _/ ___ \ (_| | __/ | | | |_
228 \___/|_|/_/ \_\__, |\___|_| |_|\__|
229 |___/
230'''
231
232def print_banner(log):
233 for line in banner.strip('\n').splitlines():
234 log.info(line)
235 log.info('(to stop: press Ctrl-C)')
236
237
238class Main(object):
239
240 def __init__(self):
241
242 self.args = args = parse_args()
243 self.config = load_config(args)
Richard Jankowski46464e92019-03-05 11:53:55 -0500244 self.grpc_timeout = int(self.args.grpc_timeout)
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500245
246 verbosity_adjust = (args.verbose or 0) - (args.quiet or 0)
247 self.log = setup_logging(self.config.get('logging', {}),
248 args.instance_id,
249 verbosity_adjust=verbosity_adjust)
250
251 # components
252 self.connection_manager = None
253
254 self.exiting = False
255
256 if not args.no_banner:
257 print_banner(self.log)
258
259 self.startup_components()
260
261 def start(self):
262 self.start_reactor() # will not return except Keyboard interrupt
263
264 @inlineCallbacks
265 def startup_components(self):
266 self.log.info('starting-internal-components')
267 args = self.args
268 self.connection_manager = yield ConnectionManager(
khenaidoo43aa6bd2019-05-29 13:35:13 -0400269 args.consul,
270 args.grpc_endpoint,
271 self.grpc_timeout,
272 args.core_binding_key,
273 args.core_transaction_key,
274 args.controller,
275 args.instance_id,
276 args.enable_tls,
277 args.key_file,
278 args.cert_file).start()
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500279 self.log.info('started-internal-services')
280
281 @inlineCallbacks
282 def shutdown_components(self):
283 """Execute before the reactor is shut down"""
284 self.log.info('exiting-on-keyboard-interrupt')
285 self.exiting = True
286 if self.connection_manager is not None:
287 yield self.connection_manager.stop()
288
289 def start_reactor(self):
290 reactor.callWhenRunning(
291 lambda: self.log.info('twisted-reactor-started'))
292
293 reactor.addSystemEventTrigger('before', 'shutdown',
294 self.shutdown_components)
Thomas Lee S9f0da512019-09-27 21:09:25 +0530295 reactor.callInThread(self.start_probe)
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500296 reactor.run()
297
Thomas Lee S9f0da512019-09-27 21:09:25 +0530298 def start_probe(self):
299 args = self.args
300 host = args.probe.split(':')[0]
301 port = args.probe.split(':')[1]
302 server = SocketServer.TCPServer((host, int(port)), Probe)
303 server.serve_forever()
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500304
305if __name__ == '__main__':
306 Main().start()