blob: a61f2ab70cd214065755cc5c0b6a08f915695c88 [file] [log] [blame]
Khen Nursimulu68b9be32016-10-25 11:57:04 -04001#
Zsolt Haraszti3eb27a52017-01-03 21:56:48 -08002# Copyright 2017 the original author or authors.
Khen Nursimulu68b9be32016-10-25 11:57:04 -04003#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
alshabib06b449c2017-01-15 17:33:16 -060016import os
Khen Nursimulu68b9be32016-10-25 11:57:04 -040017
18import sys
19
20from twisted.internet import reactor
21from twisted.internet.defer import Deferred, inlineCallbacks, returnValue
22
23from common.utils.asleep import asleep
24from common.utils.consulhelpers import get_endpoint_from_consul
25from structlog import get_logger
26import grpc
Rouzbahan Rashidi-Tabrizi34b7dd72017-03-13 17:45:20 -040027from grpc import StatusCode
28from grpc._channel import _Rendezvous
Zsolt Haraszti1edb8282016-11-08 10:57:19 -080029from ofagent.protos import third_party
Khen Nursimulu68b9be32016-10-25 11:57:04 -040030from protos import voltha_pb2
Stephane Barbarie2940dac2017-08-18 14:15:17 -040031from protos.voltha_pb2 import OfAgentSubscriber
Khen Nursimulu68b9be32016-10-25 11:57:04 -040032from grpc_client import GrpcClient
33
34from agent import Agent
Zsolt Haraszti7eeb2b32016-11-06 14:04:55 -080035from google.protobuf.empty_pb2 import Empty
Stephane Barbarie2940dac2017-08-18 14:15:17 -040036from common.utils.dockerhelpers import get_my_containers_name
Zsolt Haraszti7eeb2b32016-11-06 14:04:55 -080037
Khen Nursimulu68b9be32016-10-25 11:57:04 -040038
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070039log = get_logger()
Zsolt Haraszti7eeb2b32016-11-06 14:04:55 -080040# _ = third_party
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070041
Khen Nursimulu68b9be32016-10-25 11:57:04 -040042class ConnectionManager(object):
Stephane Barbarie2940dac2017-08-18 14:15:17 -040043 def __init__(self, consul_endpoint, vcore_endpoint, controller_endpoints,
Girishf6eeaea2017-11-13 10:53:57 +053044 enable_tls=False, key_file=None, cert_file=None,
Stephane Barbarie2940dac2017-08-18 14:15:17 -040045 vcore_retry_interval=0.5, devices_refresh_interval=5,
46 subscription_refresh_interval=5):
Khen Nursimulu68b9be32016-10-25 11:57:04 -040047
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070048 log.info('init-connection-manager')
Stephane Barbarie2940dac2017-08-18 14:15:17 -040049 log.info('list-of-controllers', controller_endpoints=controller_endpoints)
sgovindacc736782017-05-02 20:06:37 +053050 self.controller_endpoints = controller_endpoints
Khen Nursimulu68b9be32016-10-25 11:57:04 -040051 self.consul_endpoint = consul_endpoint
Stephane Barbarie2940dac2017-08-18 14:15:17 -040052 self.vcore_endpoint = vcore_endpoint
Girishf6eeaea2017-11-13 10:53:57 +053053 self.enable_tls = enable_tls
54 self.key_file = key_file
55 self.cert_file = cert_file
Khen Nursimulu68b9be32016-10-25 11:57:04 -040056
57 self.channel = None
Stephane Barbarie2940dac2017-08-18 14:15:17 -040058 self.grpc_client = None # single, shared gRPC client to vcore
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070059
sgovindacc736782017-05-02 20:06:37 +053060 self.agent_map = {} # (datapath_id, controller_endpoint) -> Agent()
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070061 self.device_id_to_datapath_id_map = {}
Khen Nursimulu68b9be32016-10-25 11:57:04 -040062
Stephane Barbarie2940dac2017-08-18 14:15:17 -040063 self.vcore_retry_interval = vcore_retry_interval
Khen Nursimulu68b9be32016-10-25 11:57:04 -040064 self.devices_refresh_interval = devices_refresh_interval
Stephane Barbarie2940dac2017-08-18 14:15:17 -040065 self.subscription_refresh_interval = subscription_refresh_interval
66 self.subscription = None
Khen Nursimulu68b9be32016-10-25 11:57:04 -040067
68 self.running = False
69
Zsolt Haraszti2bdb6b32016-11-03 16:56:17 -070070 def start(self):
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070071
Khen Nursimulu68b9be32016-10-25 11:57:04 -040072 if self.running:
73 return
74
Zsolt Haraszti2bdb6b32016-11-03 16:56:17 -070075 log.debug('starting')
Khen Nursimulu68b9be32016-10-25 11:57:04 -040076
77 self.running = True
78
Stephane Barbarie2940dac2017-08-18 14:15:17 -040079 # Start monitoring the vcore grpc channel
80 reactor.callInThread(self.monitor_vcore_grpc_channel)
Khen Nursimulu68b9be32016-10-25 11:57:04 -040081
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070082 # Start monitoring logical devices and manage agents accordingly
83 reactor.callLater(0, self.monitor_logical_devices)
Khen Nursimulu68b9be32016-10-25 11:57:04 -040084
Zsolt Haraszti2bdb6b32016-11-03 16:56:17 -070085 log.info('started')
86
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070087 return self
Khen Nursimulu68b9be32016-10-25 11:57:04 -040088
Zsolt Haraszti2bdb6b32016-11-03 16:56:17 -070089 def stop(self):
90 log.debug('stopping')
Khen Nursimulu68b9be32016-10-25 11:57:04 -040091 # clean up all controller connections
Zsolt Haraszti2bdb6b32016-11-03 16:56:17 -070092 for agent in self.agent_map.itervalues():
93 agent.stop()
Khen Nursimulu68b9be32016-10-25 11:57:04 -040094 self.running = False
Stephane Barbarie2940dac2017-08-18 14:15:17 -040095
96 self._reset_grpc_attributes()
97
Zsolt Haraszti2bdb6b32016-11-03 16:56:17 -070098 log.info('stopped')
Khen Nursimulu68b9be32016-10-25 11:57:04 -040099
100 def resolve_endpoint(self, endpoint):
101 ip_port_endpoint = endpoint
102 if endpoint.startswith('@'):
103 try:
104 ip_port_endpoint = get_endpoint_from_consul(
105 self.consul_endpoint, endpoint[1:])
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700106 log.info(
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400107 '{}-service-endpoint-found'.format(endpoint), address=ip_port_endpoint)
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400108 except Exception as e:
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400109 log.error('{}-service-endpoint-not-found'.format(endpoint), exception=repr(e))
110 log.error('committing-suicide')
alshabib06b449c2017-01-15 17:33:16 -0600111 # Committing suicide in order to let docker restart ofagent
112 os.system("kill -15 {}".format(os.getpid()))
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400113 if ip_port_endpoint:
114 host, port = ip_port_endpoint.split(':', 2)
115 return host, int(port)
116
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400117 def _reset_grpc_attributes(self):
118 log.debug('start-reset-grpc-attributes')
119
120 if self.grpc_client is not None:
121 self.grpc_client.stop()
122
123 if self.channel is not None:
124 del self.channel
125
126 self.is_alive = False
127 self.channel = None
128 self.subscription = None
129 self.grpc_client = None
130
131 log.debug('stop-reset-grpc-attributes')
132
133 def _assign_grpc_attributes(self):
134 log.debug('start-assign-grpc-attributes')
135
136 host, port = self.resolve_endpoint(self.vcore_endpoint)
137 log.info('revolved-vcore-endpoint', endpoint=self.vcore_endpoint, host=host, port=port)
138
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400139 assert host is not None
140 assert port is not None
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400141
142 # Establish a connection to the vcore GRPC server
143 self.channel = grpc.insecure_channel('{}:{}'.format(host, port))
144 self.is_alive = True
145
146 log.debug('stop-assign-grpc-attributes')
147
148 @inlineCallbacks
149 def monitor_vcore_grpc_channel(self):
150 log.debug('start-monitor-vcore-grpc-channel')
151
152 while self.running:
153 try:
154 # If a subscription is not yet assigned then establish new GRPC connection
155 # ... otherwise keep using existing connection details
156 if self.subscription is None:
157 self._assign_grpc_attributes()
158
159 # Send subscription request to register the current ofagent instance
160 container_name = get_my_containers_name()
161 stub = voltha_pb2.VolthaLocalServiceStub(self.channel)
162 subscription = stub.Subscribe(OfAgentSubscriber(ofagent_id=container_name))
163
164 # If the subscriber id matches the current instance
165 # ... then the subscription has succeeded
166 if subscription is not None and subscription.ofagent_id == container_name:
167 if self.subscription is None:
168 # Keep details on the current GRPC session and subscription
169 log.debug('subscription-with-vcore-successful', subscription=subscription)
170 self.subscription = subscription
171 self.grpc_client = GrpcClient(self, self.channel).start()
172
173 # Sleep a bit in between each subscribe
174 yield asleep(self.subscription_refresh_interval)
175
176 # Move on to next subscribe request
177 continue
178
179 # The subscription did not succeed, reset and move on
180 else:
181 log.info('subscription-with-vcore-unavailable', subscription=subscription)
182
183 except _Rendezvous, e:
184 log.error('subscription-with-vcore-terminated',exception=e, status=e.code())
185
186 except Exception as e:
187 log.exception('unexpected-subscription-termination-with-vcore', e=e)
188
189 # Reset grpc details
190 # The vcore instance is either not available for subscription
191 # or a failure occurred with the existing communication.
192 self._reset_grpc_attributes()
193
194 # Sleep for a short period and retry
195 yield asleep(self.vcore_retry_interval)
196
197 log.debug('stop-monitor-vcore-grpc-channel')
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400198
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400199 @inlineCallbacks
200 def get_list_of_logical_devices_from_voltha(self):
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700201
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400202 while self.running:
203 log.info('retrieve-logical-device-list')
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400204 try:
Zsolt Haraszti66862032016-11-28 14:28:39 -0800205 stub = voltha_pb2.VolthaLocalServiceStub(self.channel)
Zsolt Haraszti7eeb2b32016-11-06 14:04:55 -0800206 devices = stub.ListLogicalDevices(Empty()).items
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400207 for device in devices:
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400208 log.info("logical-device-entry", id=device.id, datapath_id=device.datapath_id)
209
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700210 returnValue(devices)
211
Rouzbahan Rashidi-Tabrizi34b7dd72017-03-13 17:45:20 -0400212 except _Rendezvous, e:
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400213 log.error('vcore-communication-failure', exception=e, status=e.code())
Rouzbahan Rashidi-Tabrizi34b7dd72017-03-13 17:45:20 -0400214 if e.code() == StatusCode.UNAVAILABLE:
215 os.system("kill -15 {}".format(os.getpid()))
216
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400217 except Exception as e:
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400218 log.exception('logical-devices-retrieval-failure', exception=e)
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400219
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400220 log.info('reconnect', after_delay=self.vcore_retry_interval)
221 yield asleep(self.vcore_retry_interval)
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400222
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700223 def refresh_agent_connections(self, devices):
224 """
225 Based on the new device list, update the following state in the class:
226 * agent_map
227 * datapath_map
228 * device_id_map
229 :param devices: full device list freshly received from Voltha
230 :return: None
231 """
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400232
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700233 # Use datapath ids for deciding what's new and what's obsolete
234 desired_datapath_ids = set(d.datapath_id for d in devices)
sgovindacc736782017-05-02 20:06:37 +0530235 current_datapath_ids = set(datapath_ids[0] for datapath_ids in self.agent_map.iterkeys())
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400236
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700237 # if identical, nothing to do
238 if desired_datapath_ids == current_datapath_ids:
239 return
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400240
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700241 # ... otherwise calculate differences
242 to_add = desired_datapath_ids.difference(current_datapath_ids)
243 to_del = current_datapath_ids.difference(desired_datapath_ids)
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400244
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700245 # remove what we don't need
246 for datapath_id in to_del:
247 self.delete_agent(datapath_id)
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400248
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700249 # start new agents as needed
250 for device in devices:
251 if device.datapath_id in to_add:
252 self.create_agent(device)
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400253
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700254 log.debug('updated-agent-list', count=len(self.agent_map))
255 log.debug('updated-device-id-to-datapath-id-map',
256 map=str(self.device_id_to_datapath_id_map))
257
258 def create_agent(self, device):
259 datapath_id = device.datapath_id
260 device_id = device.id
sgovindacc736782017-05-02 20:06:37 +0530261 for controller_endpoint in self.controller_endpoints:
262 agent = Agent(controller_endpoint, datapath_id,
Girishf6eeaea2017-11-13 10:53:57 +0530263 device_id, self.grpc_client, self.enable_tls,
264 self.key_file, self.cert_file)
sgovindacc736782017-05-02 20:06:37 +0530265 agent.start()
266 self.agent_map[(datapath_id,controller_endpoint)] = agent
267 self.device_id_to_datapath_id_map[device_id] = datapath_id
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700268
269 def delete_agent(self, datapath_id):
sgovindacc736782017-05-02 20:06:37 +0530270 for controller_endpoint in self.controller_endpoints:
271 agent = self.agent_map[(datapath_id,controller_endpoint)]
272 device_id = agent.get_device_id()
273 agent.stop()
274 del self.agent_map[(datapath_id,controller_endpoint)]
275 del self.device_id_to_datapath_id_map[device_id]
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400276
277 @inlineCallbacks
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700278 def monitor_logical_devices(self):
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400279 log.debug('start-monitor-logical-devices')
280
281 while self.running:
282 log.info('monitoring-logical-devices')
283
alshabibc3fb4942017-01-26 15:34:24 -0800284 # should change to a gRPC streaming call
285 # see https://jira.opencord.org/browse/CORD-821
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700286
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400287 try:
288 if self.channel is not None and self.grpc_client is not None:
289 # get current list from Voltha
290 devices = yield self.get_list_of_logical_devices_from_voltha()
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700291
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400292 # update agent list and mapping tables as needed
293 self.refresh_agent_connections(devices)
294 else:
295 log.info('vcore-communication-unavailable')
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700296
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400297 # wait before next poll
298 yield asleep(self.devices_refresh_interval)
299
300 except _Rendezvous, e:
301 log.error('vcore-communication-failure', exception=repr(e), status=e.code())
302
303 except Exception as e:
304 log.exception('unexpected-vcore-communication-failure', exception=repr(e))
305
306 log.debug('stop-monitor-logical-devices')
Khen Nursimulu68b9be32016-10-25 11:57:04 -0400307
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700308 def forward_packet_in(self, device_id, ofp_packet_in):
309 datapath_id = self.device_id_to_datapath_id_map.get(device_id, None)
310 if datapath_id:
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400311 for controller_endpoint in self.controller_endpoints:
312 agent = self.agent_map[(datapath_id, controller_endpoint)]
313 agent.forward_packet_in(ofp_packet_in)
Zsolt Haraszti217a12e2016-12-19 16:37:55 -0800314
315 def forward_change_event(self, device_id, event):
316 datapath_id = self.device_id_to_datapath_id_map.get(device_id, None)
317 if datapath_id:
Stephane Barbarie2940dac2017-08-18 14:15:17 -0400318 for controller_endpoint in self.controller_endpoints:
319 agent = self.agent_map[(datapath_id, controller_endpoint)]
320 agent.forward_change_event(event)