2 * Copyright (c) 2015, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.ovsdb.hwvtepsouthbound;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
17 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
18 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
19 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
20 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
21 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
22 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
23 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
24 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
25 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.ovsdb.hwvtepsouthbound.events.ClientConnected;
29 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.ReconciliationManager;
30 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.ReconciliationTask;
31 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationTask;
32 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.connection.ConnectionReconciliationTask;
33 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.DependencyQueue;
34 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.HwvtepGlobalRemoveCommand;
35 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
36 import org.opendaylight.ovsdb.lib.OvsdbClient;
37 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
38 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
39 import org.opendaylight.ovsdb.lib.operations.Operation;
40 import org.opendaylight.ovsdb.lib.operations.OperationResult;
41 import org.opendaylight.ovsdb.lib.operations.Select;
42 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
43 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
44 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
45 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
46 import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionHistory;
47 import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionType;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
52 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 import javax.annotation.Nonnull;
59 import javax.annotation.Nullable;
60 import java.net.ConnectException;
61 import java.net.InetAddress;
62 import java.net.UnknownHostException;
63 import java.util.ArrayList;
64 import java.util.List;
66 import java.util.Objects;
67 import java.util.concurrent.ConcurrentHashMap;
68 import java.util.concurrent.ExecutionException;
69 import java.util.concurrent.TimeUnit;
70 import java.util.concurrent.TimeoutException;
72 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
74 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable{
75 private Map<ConnectionInfo, HwvtepConnectionInstance> clients = new ConcurrentHashMap<>();
76 private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionManager.class);
77 private static final String ENTITY_TYPE = "hwvtep";
78 private static final int DB_FETCH_TIMEOUT = 1000;
79 private static final int TRANSACTION_HISTORY_CAPACITY = 10000;
80 private static final int TRANSACTION_HISTORY_WATERMARK = 7500;
82 private DataBroker db;
83 private TransactionInvoker txInvoker;
84 private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers = new ConcurrentHashMap<>();
85 private Map<Entity, HwvtepConnectionInstance> entityConnectionMap = new ConcurrentHashMap<>();
86 private EntityOwnershipService entityOwnershipService;
87 private HwvtepDeviceEntityOwnershipListener hwvtepDeviceEntityOwnershipListener;
88 private final ReconciliationManager reconciliationManager;
89 private final Map<InstanceIdentifier<Node>, HwvtepConnectionInstance> nodeIidVsConnectionInstance =
90 new ConcurrentHashMap<>();
91 private HwvtepOperGlobalListener hwvtepOperGlobalListener;
92 private final Map<InstanceIdentifier<Node>, TransactionHistory> controllerTxHistory = new ConcurrentHashMap<>();
93 private final Map<InstanceIdentifier<Node>, TransactionHistory> deviceUpdateHistory = new ConcurrentHashMap<>();
95 public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
96 EntityOwnershipService entityOwnershipService) {
98 this.txInvoker = txInvoker;
99 this.entityOwnershipService = entityOwnershipService;
100 this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
101 this.reconciliationManager = new ReconciliationManager(db);
102 this.hwvtepOperGlobalListener = new HwvtepOperGlobalListener(db, this);
106 public void close() throws Exception {
107 if (hwvtepDeviceEntityOwnershipListener != null) {
108 hwvtepDeviceEntityOwnershipListener.close();
111 for (HwvtepConnectionInstance client: clients.values()) {
114 DependencyQueue.close();
118 public void connected(@Nonnull final OvsdbClient externalClient) {
119 LOG.info("Library connected {} from {}:{} to {}:{}",
120 externalClient.getConnectionInfo().getType(),
121 externalClient.getConnectionInfo().getRemoteAddress(),
122 externalClient.getConnectionInfo().getRemotePort(),
123 externalClient.getConnectionInfo().getLocalAddress(),
124 externalClient.getConnectionInfo().getLocalPort());
125 List<String> databases = new ArrayList<>();
127 databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
128 if(databases.contains(HwvtepSchemaConstants.HARDWARE_VTEP)) {
129 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(externalClient);
130 registerEntityForOwnership(hwClient);
132 } catch (InterruptedException | ExecutionException | TimeoutException e) {
133 LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
134 externalClient.getConnectionInfo().getRemoteAddress(), e);
135 externalClient.disconnect();
140 public void disconnected(OvsdbClient client) {
141 LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
142 client.getConnectionInfo().getType(),
143 client.getConnectionInfo().getRemoteAddress(),
144 client.getConnectionInfo().getRemotePort(),
145 client.getConnectionInfo().getLocalAddress(),
146 client.getConnectionInfo().getLocalPort());
147 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
148 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
149 if (hwvtepConnectionInstance != null) {
150 deviceUpdateHistory.get(hwvtepConnectionInstance.getInstanceIdentifier()).addToHistory(
151 TransactionType.DELETE, new ClientConnected(client.getConnectionInfo().getRemotePort()));
153 // Unregister Entity ownership as soon as possible ,so this instance should
154 // not be used as a candidate in Entity election (given that this instance is
155 // about to disconnect as well), if current owner get disconnected from
157 if (hwvtepConnectionInstance.getHasDeviceOwnership()) {
158 unregisterEntityForOwnership(hwvtepConnectionInstance);
159 txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
161 unregisterEntityForOwnership(hwvtepConnectionInstance);
162 //Do not delete if client disconnected from follower HwvtepGlobalRemoveCommand
165 removeConnectionInstance(key);
167 //Controller initiated connection can be terminated from switch side.
168 //So cleanup the instance identifier cache.
169 removeInstanceIdentifier(key);
170 removeConnectionInstance(hwvtepConnectionInstance.getInstanceIdentifier());
171 retryConnection(hwvtepConnectionInstance.getInstanceIdentifier(),
172 hwvtepConnectionInstance.getHwvtepGlobalAugmentation(),
173 ConnectionReconciliationTriggers.ON_DISCONNECT);
175 LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
177 LOG.trace("HwvtepConnectionManager exit disconnected client: {}", client);
180 public OvsdbClient connect(InstanceIdentifier<Node> iid,
181 HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException, ConnectException {
182 LOG.info("Connecting to {}", HwvtepSouthboundUtil.connectionInfoToString(hwvtepGlobal.getConnectionInfo()));
183 InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
184 OvsdbClient client = OvsdbConnectionService.getService()
185 .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
187 putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
188 HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
189 hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
190 hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
192 // Register Cluster Ownership for ConnectionInfo
193 registerEntityForOwnership(hwvtepConnectionInstance);
195 LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
199 public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
200 LOG.info("Diconnecting from {}", HwvtepSouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
201 HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
202 if (client != null) {
204 // Unregister Cluster Ownership for ConnectionInfo
205 unregisterEntityForOwnership(client);
206 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
210 public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
211 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
212 externalClient.getConnectionInfo().getRemotePort());
213 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
214 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
216 // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
217 // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
218 if (hwvtepConnectionInstance != null) {
219 if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
220 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
221 return hwvtepConnectionInstance;
223 LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
224 hwvtepConnectionInstance.disconnect();
226 // Unregister Cluster Ownership for ConnectionInfo
227 // Because the hwvtepConnectionInstance is about to be completely replaced!
228 unregisterEntityForOwnership(hwvtepConnectionInstance);
230 removeConnectionInstance(key);
233 hwvtepConnectionInstance = new HwvtepConnectionInstance(this, key, externalClient, getInstanceIdentifier(key),
235 hwvtepConnectionInstance.createTransactInvokers();
236 return hwvtepConnectionInstance;
239 private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
240 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
241 clients.put(connectionInfo, instance);
242 LOG.info("Clients after put: {}", clients);
245 public HwvtepConnectionInstance getConnectionInstance(final ConnectionInfo key) {
249 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
250 return clients.get(connectionInfo);
253 public HwvtepConnectionInstance getConnectionInstanceFromNodeIid(final InstanceIdentifier<Node> nodeIid) {
254 HwvtepConnectionInstance hwvtepConnectionInstance = nodeIidVsConnectionInstance.get(nodeIid);
255 if (hwvtepConnectionInstance != null) {
256 return hwvtepConnectionInstance;
258 InstanceIdentifier<Node> globalNodeIid = HwvtepSouthboundUtil.getGlobalNodeIid(nodeIid);
259 if (globalNodeIid != null) {
260 return nodeIidVsConnectionInstance.get(globalNodeIid);
265 public HwvtepConnectionInstance getConnectionInstance(Node node) {
266 Preconditions.checkNotNull(node);
267 HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
268 PhysicalSwitchAugmentation pSwitchNode = node.getAugmentation(PhysicalSwitchAugmentation.class);
269 if (hwvtepGlobal != null) {
270 if(hwvtepGlobal.getConnectionInfo() != null) {
271 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
273 //TODO: Case of user configured connection for now
274 //TODO: We could get it from Managers also.
278 else if(pSwitchNode != null){
279 return getConnectionInstance(pSwitchNode);
281 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
286 public HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
287 Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
288 if(optional.isPresent()) {
289 return getConnectionInstance(optional.get().getConnectionInfo());
295 public void stopConfigurationReconciliation(final InstanceIdentifier<Node> nodeIid) {
296 final ReconciliationTask task = new HwvtepReconciliationTask(
297 reconciliationManager, HwvtepConnectionManager.this, nodeIid, null, null, db);
299 reconciliationManager.dequeue(task);
302 public void reconcileConfigurations(final HwvtepConnectionInstance client, Node psNode) {
303 final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
304 final ReconciliationTask task = new HwvtepReconciliationTask(
305 reconciliationManager, HwvtepConnectionManager.this, nodeIid, psNode, client, db);
307 reconciliationManager.enqueue(task);
310 private void removeConnectionInstance(ConnectionInfo key) {
311 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
312 clients.remove(connectionInfo);
313 LOG.info("Clients after remove: {}", clients);
316 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
317 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
318 instanceIdentifiers.put(connectionInfo, iid);
321 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
322 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
323 return instanceIdentifiers.get(connectionInfo);
326 private void removeInstanceIdentifier(ConnectionInfo key) {
327 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
328 instanceIdentifiers.remove(connectionInfo);
331 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
332 return getConnectionInstance(connectionInfo).getOvsdbClient();
335 private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
337 Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
338 if (entityConnectionMap.get(candidateEntity) != null) {
339 disconnected(entityConnectionMap.get(candidateEntity).getOvsdbClient());
340 putConnectionInstance(hwvtepConnectionInstance.getInstanceIdentifier(), hwvtepConnectionInstance);
342 entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
343 hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
346 EntityOwnershipCandidateRegistration registration =
347 entityOwnershipService.registerCandidate(candidateEntity);
348 hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
349 LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
351 //If entity already has owner, it won't get notification from EntityOwnershipService
352 //so cache the connection instances.
353 handleOwnershipState(candidateEntity, hwvtepConnectionInstance);
354 } catch (CandidateAlreadyRegisteredException e) {
355 LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
360 private void handleOwnershipState(Entity candidateEntity, HwvtepConnectionInstance hwvtepConnectionInstance) {
361 //If entity already has owner, it won't get notification from EntityOwnershipService
362 //so cache the connection instances.
363 Optional<EntityOwnershipState> ownershipStateOpt =
364 entityOwnershipService.getOwnershipState(candidateEntity);
365 if (ownershipStateOpt.isPresent()) {
366 EntityOwnershipState ownershipState = ownershipStateOpt.get();
367 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
368 if (ownershipState.hasOwner()) {
369 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipState.isOwner());
370 if (!ownershipState.isOwner()) {
371 LOG.info("HWVTEP entity {} is already owned by other southbound plugin "
372 + "instance, so *this* instance is NOT an OWNER of the device",
373 hwvtepConnectionInstance.getConnectionInfo());
375 afterTakingOwnership(hwvtepConnectionInstance);
381 private void afterTakingOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
382 txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
383 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
384 hwvtepConnectionInstance.setHasDeviceOwnership(true);
385 hwvtepConnectionInstance.registerCallbacks();
388 private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
389 DatabaseSchema dbSchema = null;
390 Global globalRow = null;
393 dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
394 } catch (InterruptedException | ExecutionException e) {
395 LOG.warn("Not able to fetch schema for database {} from device {}",
396 HwvtepSchemaConstants.HARDWARE_VTEP,connectionInstance.getConnectionInfo(),e);
399 if (dbSchema != null) {
400 GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
402 List<String> hwvtepTableColumn = new ArrayList<>();
403 hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
404 Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
405 selectOperation.setColumns(hwvtepTableColumn);
407 ArrayList<Operation> operations = new ArrayList<>();
408 operations.add(selectOperation);
409 operations.add(op.comment("Fetching hardware_vtep table rows"));
412 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
413 if (results != null ) {
414 OperationResult selectResult = results.get(0);
415 globalRow = TyperUtils.getTypedRowWrapper(
416 dbSchema,Global.class,selectResult.getRows().get(0));
418 } catch (InterruptedException | ExecutionException e) {
419 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
420 connectionInstance.getConnectionInfo(),e);
423 LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
427 private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
428 InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
430 //TODO: Is Global the right one?
431 Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
432 iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
433 /* Let's set the iid now */
434 hwvtepConnectionInstance.setInstanceIdentifier(iid);
435 LOG.info("InstanceIdentifier {} generated for device "
436 + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
437 controllerTxHistory.putIfAbsent(iid,
438 new TransactionHistory(TRANSACTION_HISTORY_CAPACITY, TRANSACTION_HISTORY_WATERMARK));
439 deviceUpdateHistory.putIfAbsent(iid,
440 new TransactionHistory(TRANSACTION_HISTORY_CAPACITY, TRANSACTION_HISTORY_WATERMARK));
441 TransactionHistory controllerLog = controllerTxHistory.get(iid);
442 TransactionHistory deviceLog = deviceUpdateHistory.get(iid);
443 int port = hwvtepConnectionInstance.getOvsdbClient().getConnectionInfo().getRemotePort();
444 deviceLog.addToHistory(TransactionType.ADD, new ClientConnected(port));
445 hwvtepConnectionInstance.setControllerTxHistory(controllerLog);
446 hwvtepConnectionInstance.setDeviceUpdateHistory(deviceLog);
448 YangInstanceIdentifier entityId =
449 HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
450 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
451 LOG.debug("Entity {} created for device connection {}",
452 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
455 private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
456 hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
457 entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
460 public void reconcileConnection(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepNode) {
461 this.retryConnection(iid, hwvtepNode,
462 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
465 public void stopConnectionReconciliationIfActive(InstanceIdentifier<?> iid, HwvtepGlobalAugmentation hwvtepNode) {
466 final ReconciliationTask task = new ConnectionReconciliationTask(
467 reconciliationManager,
471 reconciliationManager.dequeue(task);
474 private void retryConnection(final InstanceIdentifier<Node> iid, final HwvtepGlobalAugmentation hwvtepNode,
475 ConnectionReconciliationTriggers trigger) {
476 final ReconciliationTask task = new ConnectionReconciliationTask(
477 reconciliationManager,
482 if(reconciliationManager.isEnqueued(task)){
486 case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
487 reconciliationManager.enqueueForRetry(task);
491 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
492 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
493 tx.read(LogicalDatastoreType.CONFIGURATION, iid);
495 final HwvtepConnectionManager connectionManager = this;
496 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
498 public void onSuccess(@Nullable Optional<Node> node) {
499 if (node.isPresent()) {
500 HwvtepGlobalAugmentation augmentation = node.get()
501 .getAugmentation(HwvtepGlobalAugmentation.class);
502 if (augmentation == null || augmentation.getConnectionInfo() == null) {
505 LOG.info("Disconnected/Failed connection {} was controller initiated, attempting " +
506 "reconnection", hwvtepNode.getConnectionInfo());
507 reconciliationManager.enqueue(task);
510 LOG.debug("Connection {} was switch initiated, no reconciliation is required"
511 , iid.firstKeyOf(Node.class).getNodeId());
516 public void onFailure(Throwable t) {
517 LOG.warn("Read Config/DS for Node failed! {}", iid, t);
527 public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
528 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
529 LOG.info("handleOwnershipChanged: {} event received for device {}",
530 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
531 : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
533 if (hwvtepConnectionInstance == null) {
534 if (ownershipChange.isOwner()) {
535 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
537 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
538 // that instance registered for the device ownership or not. It is to make sure that
539 // If all the controller instance that was connected to the device are down, so the
540 // running instance can clear up the operational data store even though it was not
541 // connected to the device.
542 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
545 // If entity has no owner, clean up the operational data store (it's possible because owner controller
546 // might went down abruptly and didn't get a chance to clean up the operational data store.
547 if (!ownershipChange.hasOwner()) {
548 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
549 // If first cleanEntityOperationalData() was called, this call will be no-op.
550 cleanEntityOperationalData(ownershipChange.getEntity());
554 //Connection detail need to be cached, irrespective of ownership result.
555 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
557 if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
558 LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
559 hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
563 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
564 // You were not an owner, but now you are
565 if (ownershipChange.isOwner()) {
566 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
567 hwvtepConnectionInstance.getConnectionInfo());
569 //*this* instance of southbound plugin is owner of the device,
570 //so register for monitor callbacks
571 afterTakingOwnership(hwvtepConnectionInstance);
574 //You were owner of the device, but now you are not. With the current ownership
575 //grant mechanism, this scenario should not occur. Because this scenario will occur
576 //when this controller went down or switch flap the connection, but in both the case
577 //it will go through the re-registration process. We need to implement this condition
578 //when clustering service implement a ownership grant strategy which can revoke the
579 //device ownership for load balancing the devices across the instances.
580 //Once this condition occur, we should unregister the callback.
581 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
582 hwvtepConnectionInstance.getNodeId().getValue());
586 private void cleanEntityOperationalData(Entity entity) {
587 @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
588 (InstanceIdentifier<Node>) HwvtepSouthboundUtil
589 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
590 txInvoker.invoke(new HwvtepGlobalRemoveCommand(nodeIid));
593 private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
594 return entityConnectionMap.get(entity);
597 void putConnectionInstance(final InstanceIdentifier<Node> nodeIid,
598 final HwvtepConnectionInstance connectionInstance) {
599 nodeIidVsConnectionInstance.put(nodeIid, connectionInstance);
602 private void removeConnectionInstance(final InstanceIdentifier<Node> nodeIid) {
603 if (nodeIid != null) {
604 nodeIidVsConnectionInstance.remove(nodeIid);
608 public Map<InstanceIdentifier<Node>, TransactionHistory> getControllerTxHistory() {
609 return controllerTxHistory;
612 public Map<InstanceIdentifier<Node>, TransactionHistory> getDeviceUpdateHistory() {
613 return deviceUpdateHistory;
616 private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
617 private HwvtepConnectionManager hcm;
618 private EntityOwnershipListenerRegistration listenerRegistration;
620 HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
622 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
624 public void close() {
625 listenerRegistration.close();
628 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
629 hcm.handleOwnershipChanged(ownershipChange);
633 private enum ConnectionReconciliationTriggers {
635 Reconciliation trigger for scenario where controller's attempt
636 to connect to switch fails on config data store notification
638 ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
641 Reconciliation trigger for the scenario where controller
642 initiated connection disconnects.