blob: b960b6901c5842ab5b62fbf27e69f5371b56b862 [file] [log] [blame]
Stephane Barbarie6e1bd502018-11-05 22:44:45 -05001#
2# Copyright 2017 the original author or authors.
3#
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#
16import os
17
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
27from grpc import StatusCode
28from grpc._channel import _Rendezvous
29from ofagent.protos import third_party
30from protos import voltha_pb2
31from protos.voltha_pb2 import OfAgentSubscriber
32from grpc_client import GrpcClient
33
34from agent import Agent
35from common.utils.dockerhelpers import get_my_containers_name
36
37
38log = get_logger()
39# _ = third_party
40
41class ConnectionManager(object):
42 def __init__(self, consul_endpoint, vcore_endpoint, vcore_grpc_timeout,
43 controller_endpoints, instance_id,
44 enable_tls=False, key_file=None, cert_file=None,
45 vcore_retry_interval=0.5, devices_refresh_interval=5,
46 subscription_refresh_interval=5):
47
48 log.info('init-connection-manager')
49 log.info('list-of-controllers', controller_endpoints=controller_endpoints)
50 self.controller_endpoints = controller_endpoints
51 self.consul_endpoint = consul_endpoint
52 self.vcore_endpoint = vcore_endpoint
53 self.grpc_timeout = vcore_grpc_timeout
54 self.instance_id = instance_id
55 self.enable_tls = enable_tls
56 self.key_file = key_file
57 self.cert_file = cert_file
58
59 self.channel = None
60 self.grpc_client = None # single, shared gRPC client to vcore
61
62 self.agent_map = {} # (datapath_id, controller_endpoint) -> Agent()
63 self.device_id_to_datapath_id_map = {}
64
65 self.vcore_retry_interval = vcore_retry_interval
66 self.devices_refresh_interval = devices_refresh_interval
67 self.subscription_refresh_interval = subscription_refresh_interval
68 self.subscription = None
69
70 self.running = False
71
72 def start(self):
73
74 if self.running:
75 return
76
77 log.debug('starting')
78
79 self.running = True
80
81 # Get a subscription to vcore
82 reactor.callInThread(self.get_vcore_subscription)
83
84 # Start monitoring logical devices and manage agents accordingly
85 reactor.callLater(0, self.monitor_logical_devices)
86
87 log.info('started')
88
89 return self
90
91 def stop(self):
92 log.debug('stopping')
93 # clean up all controller connections
94 for agent in self.agent_map.itervalues():
95 agent.stop()
96 self.running = False
97
98 self._reset_grpc_attributes()
99
100 log.info('stopped')
101
102 def resolve_endpoint(self, endpoint):
103 ip_port_endpoint = endpoint
104 if endpoint.startswith('@'):
105 try:
106 ip_port_endpoint = get_endpoint_from_consul(
107 self.consul_endpoint, endpoint[1:])
108 log.info(
109 '{}-service-endpoint-found'.format(endpoint), address=ip_port_endpoint)
110 except Exception as e:
111 log.error('{}-service-endpoint-not-found'.format(endpoint), exception=repr(e))
112 log.error('committing-suicide')
113 # Committing suicide in order to let docker restart ofagent
114 os.system("kill -15 {}".format(os.getpid()))
115 if ip_port_endpoint:
116 host, port = ip_port_endpoint.split(':', 2)
117 return host, int(port)
118
119 def _reset_grpc_attributes(self):
120 log.debug('start-reset-grpc-attributes')
121
122 if self.grpc_client is not None:
123 self.grpc_client.stop()
124
125 if self.channel is not None:
126 del self.channel
127
128 self.is_alive = False
129 self.channel = None
130 self.subscription = None
131 self.grpc_client = None
132
133 log.debug('stop-reset-grpc-attributes')
134
135 def _assign_grpc_attributes(self):
136 log.debug('start-assign-grpc-attributes')
137
138 host, port = self.resolve_endpoint(self.vcore_endpoint)
139 log.info('revolved-vcore-endpoint', endpoint=self.vcore_endpoint, host=host, port=port)
140
141 assert host is not None
142 assert port is not None
143
144 # Establish a connection to the vcore GRPC server
145 self.channel = grpc.insecure_channel('{}:{}'.format(host, port))
146 self.is_alive = True
147
148 log.debug('stop-assign-grpc-attributes')
149
150 @inlineCallbacks
151 def get_vcore_subscription(self):
152 log.debug('start-get-vcore-subscription')
153
154 while self.running and self.subscription is None:
155 try:
156 # If a subscription is not yet assigned then establish new GRPC connection
157 # ... otherwise keep using existing connection details
158 if self.subscription is None:
159 self._assign_grpc_attributes()
160
161 # Send subscription request to register the current ofagent instance
162 container_name = self.instance_id
163 if self.grpc_client is None:
164 self.grpc_client = GrpcClient(self, self.channel, self.grpc_timeout)
165 subscription = yield self.grpc_client.subscribe(
166 OfAgentSubscriber(ofagent_id=container_name))
167
168 # If the subscriber id matches the current instance
169 # ... then the subscription has succeeded
170 if subscription is not None and subscription.ofagent_id == container_name:
171 if self.subscription is None:
172 # Keep details on the current GRPC session and subscription
173 log.debug('subscription-with-vcore-successful', subscription=subscription)
174 self.subscription = subscription
175 self.grpc_client.start()
176
177 # Sleep a bit in between each subscribe
178 yield asleep(self.subscription_refresh_interval)
179
180 # Move on to next subscribe request
181 continue
182
183 # The subscription did not succeed, reset and move on
184 else:
185 log.info('subscription-with-vcore-unavailable', subscription=subscription)
186
187 except _Rendezvous, e:
188 log.error('subscription-with-vcore-terminated',exception=e, status=e.code())
189
190 except Exception as e:
191 log.exception('unexpected-subscription-termination-with-vcore', e=e)
192
193 # Reset grpc details
194 # The vcore instance is either not available for subscription
195 # or a failure occurred with the existing communication.
196 self._reset_grpc_attributes()
197
198 # Sleep for a short period and retry
199 yield asleep(self.vcore_retry_interval)
200
201 log.debug('stop-get-vcore-subscription')
202
203 @inlineCallbacks
204 def get_list_of_logical_devices_from_voltha(self):
205
206 while self.running:
207 log.info('retrieve-logical-device-list')
208 try:
209 devices = yield \
210 self.grpc_client.list_logical_devices()
211
212 for device in devices:
213 log.info("logical-device-entry", id=device.id,
214 datapath_id=device.datapath_id)
215
216 returnValue(devices)
217
218 except _Rendezvous, e:
219 status = e.code()
220 log.error('vcore-communication-failure', exception=e, status=status)
221 if status == StatusCode.UNAVAILABLE or status == StatusCode.DEADLINE_EXCEEDED:
222 os.system("kill -15 {}".format(os.getpid()))
223
224 except Exception as e:
225 log.exception('logical-devices-retrieval-failure', exception=e)
226
227 log.info('reconnect', after_delay=self.vcore_retry_interval)
228 yield asleep(self.vcore_retry_interval)
229
230 def refresh_agent_connections(self, devices):
231 """
232 Based on the new device list, update the following state in the class:
233 * agent_map
234 * datapath_map
235 * device_id_map
236 :param devices: full device list freshly received from Voltha
237 :return: None
238 """
239
240 # Use datapath ids for deciding what's new and what's obsolete
241 desired_datapath_ids = set(d.datapath_id for d in devices)
242 current_datapath_ids = set(datapath_ids[0] for datapath_ids in self.agent_map.iterkeys())
243
244 # if identical, nothing to do
245 if desired_datapath_ids == current_datapath_ids:
246 return
247
248 # ... otherwise calculate differences
249 to_add = desired_datapath_ids.difference(current_datapath_ids)
250 to_del = current_datapath_ids.difference(desired_datapath_ids)
251
252 # remove what we don't need
253 for datapath_id in to_del:
254 self.delete_agent(datapath_id)
255
256 # start new agents as needed
257 for device in devices:
258 if device.datapath_id in to_add:
259 self.create_agent(device)
260
261 log.debug('updated-agent-list', count=len(self.agent_map))
262 log.debug('updated-device-id-to-datapath-id-map',
263 map=str(self.device_id_to_datapath_id_map))
264
265 def create_agent(self, device):
266 datapath_id = device.datapath_id
267 device_id = device.id
268 for controller_endpoint in self.controller_endpoints:
269 agent = Agent(controller_endpoint, datapath_id,
270 device_id, self.grpc_client, self.enable_tls,
271 self.key_file, self.cert_file)
272 agent.start()
273 self.agent_map[(datapath_id,controller_endpoint)] = agent
274 self.device_id_to_datapath_id_map[device_id] = datapath_id
275
276 def delete_agent(self, datapath_id):
277 for controller_endpoint in self.controller_endpoints:
278 agent = self.agent_map[(datapath_id,controller_endpoint)]
279 device_id = agent.get_device_id()
280 agent.stop()
281 del self.agent_map[(datapath_id,controller_endpoint)]
282 del self.device_id_to_datapath_id_map[device_id]
283
284 @inlineCallbacks
285 def monitor_logical_devices(self):
286 log.debug('start-monitor-logical-devices')
287
288 while self.running:
289 log.info('monitoring-logical-devices')
290
291 # should change to a gRPC streaming call
292 # see https://jira.opencord.org/browse/CORD-821
293
294 try:
295 if self.channel is not None and self.grpc_client is not None and \
296 self.subscription is not None:
297 # get current list from Voltha
298 devices = yield \
299 self.get_list_of_logical_devices_from_voltha()
300
301 # update agent list and mapping tables as needed
302 self.refresh_agent_connections(devices)
303 else:
304 log.info('vcore-communication-unavailable')
305
306 # wait before next poll
307 yield asleep(self.devices_refresh_interval)
308
309 except _Rendezvous, e:
310 log.error('vcore-communication-failure', exception=repr(e), status=e.code())
311
312 except Exception as e:
313 log.exception('unexpected-vcore-communication-failure', exception=repr(e))
314
315 log.debug('stop-monitor-logical-devices')
316
317 def forward_packet_in(self, device_id, ofp_packet_in):
318 datapath_id = self.device_id_to_datapath_id_map.get(device_id, None)
319 if datapath_id:
320 for controller_endpoint in self.controller_endpoints:
321 agent = self.agent_map[(datapath_id, controller_endpoint)]
322 agent.forward_packet_in(ofp_packet_in)
323
324 def forward_change_event(self, device_id, event):
325 datapath_id = self.device_id_to_datapath_id_map.get(device_id, None)
326 if datapath_id:
327 for controller_endpoint in self.controller_endpoints:
328 agent = self.agent_map[(datapath_id, controller_endpoint)]
329 agent.forward_change_event(event)