Fix OvsdbConnectionManagerTest
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionManager.java
index 3a5067c7237ded66f2fd813b8c8bb77e3ee06133..f6c963aa53c3a055b92d526ae76deec9492efc5d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright © 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,12 +9,13 @@ package org.opendaylight.ovsdb.southbound;
 
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
-
+import com.google.common.util.concurrent.MoreExecutors;
 import java.net.ConnectException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
@@ -25,21 +26,19 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
+import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
-import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.mdsal.eos.binding.api.Entity;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
+import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
+import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
 import org.opendaylight.ovsdb.lib.OvsdbClient;
 import org.opendaylight.ovsdb.lib.OvsdbConnection;
 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
@@ -55,7 +54,6 @@ import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationTask;
 import org.opendaylight.ovsdb.southbound.reconciliation.configuration.BridgeConfigReconciliationTask;
 import org.opendaylight.ovsdb.southbound.reconciliation.connection.ConnectionReconciliationTask;
 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
-import org.opendaylight.ovsdb.southbound.transactions.md.TransactionCommand;
 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
@@ -64,50 +62,53 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.re
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
-    private Map<ConnectionInfo, OvsdbConnectionInstance> clients =
+    private final Map<ConnectionInfo, OvsdbConnectionInstance> clients =
             new ConcurrentHashMap<>();
     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
     private static final String ENTITY_TYPE = "ovsdb";
     private static final int DB_FETCH_TIMEOUT = 1000;
 
-    private DataBroker db;
-    private TransactionInvoker txInvoker;
-    private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
+    private final DataBroker db;
+    private final TransactionInvoker txInvoker;
+    private final Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
+            new ConcurrentHashMap<>();
+    private final Map<InstanceIdentifier<Node>, OvsdbConnectionInstance> nodeIdVsConnectionInstance =
             new ConcurrentHashMap<>();
-    private Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
+    private final Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
             new ConcurrentHashMap<>();
-    private EntityOwnershipService entityOwnershipService;
-    private OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
-    private OvsdbConnection ovsdbConnection;
+    private final EntityOwnershipService entityOwnershipService;
+    private final OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
+    private final OvsdbConnection ovsdbConnection;
     private final ReconciliationManager reconciliationManager;
+    private final InstanceIdentifierCodec instanceIdentifierCodec;
 
     public OvsdbConnectionManager(DataBroker db,TransactionInvoker txInvoker,
                                   EntityOwnershipService entityOwnershipService,
-                                  OvsdbConnection ovsdbConnection) {
+                                  OvsdbConnection ovsdbConnection,
+                                  InstanceIdentifierCodec instanceIdentifierCodec) {
         this.db = db;
         this.txInvoker = txInvoker;
         this.entityOwnershipService = entityOwnershipService;
         this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
         this.ovsdbConnection = ovsdbConnection;
-        this.reconciliationManager = new ReconciliationManager(db);
+        this.reconciliationManager = new ReconciliationManager(db, instanceIdentifierCodec);
+        this.instanceIdentifierCodec = instanceIdentifierCodec;
     }
 
     @Override
-    public void connected(@Nonnull final OvsdbClient externalClient) {
+    public void connected(@NonNull final OvsdbClient externalClient) {
         LOG.info("Library connected {} from {}:{} to {}:{}",
                 externalClient.getConnectionInfo().getType(),
                 externalClient.getConnectionInfo().getRemoteAddress(),
                 externalClient.getConnectionInfo().getRemotePort(),
                 externalClient.getConnectionInfo().getLocalAddress(),
                 externalClient.getConnectionInfo().getLocalPort());
-        List<String> databases = new ArrayList<>();
         try {
-            databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
+            List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
             if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
                 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
                 // Register Cluster Ownership for ConnectionInfo
@@ -168,15 +169,20 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             // not be used as a candidate in Entity election (given that this instance is
             // about to disconnect as well), if current owner get disconnected from
             // OVSDB device.
-            unregisterEntityForOwnership(ovsdbConnectionInstance);
-
-            txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null));
-
+            if (ovsdbConnectionInstance.getHasDeviceOwnership()) {
+                LOG.info("Library disconnected {} this controller instance has ownership", key);
+                deleteOperNodeAndReleaseOwnership(ovsdbConnectionInstance);
+            } else {
+                LOG.info("Library disconnected {} this controller does not have ownership", key);
+                unregisterEntityForOwnership(ovsdbConnectionInstance);
+            }
             removeConnectionInstance(key);
 
             //Controller initiated connection can be terminated from switch side.
             //So cleanup the instance identifier cache.
             removeInstanceIdentifier(key);
+            nodeIdVsConnectionInstance.remove(ovsdbConnectionInstance.getInstanceIdentifier(),
+                    ovsdbConnectionInstance);
             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
             retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
                     ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
@@ -187,6 +193,29 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
     }
 
+    private void deleteOperNodeAndReleaseOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
+        ovsdbConnectionInstance.setHasDeviceOwnership(false);
+        final InstanceIdentifier nodeIid = ovsdbConnectionInstance.getInstanceIdentifier();
+        //remove the node from oper only if it has ownership
+        txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null) {
+
+            @Override
+            public void onSuccess() {
+                super.onSuccess();
+                LOG.debug("Successfully removed node {} from oper", nodeIid);
+                //Giveup the ownership only after cleanup is done
+                unregisterEntityForOwnership(ovsdbConnectionInstance);
+            }
+
+            @Override
+            public void onFailure(Throwable throwable) {
+                LOG.debug("Failed to remove node {} from oper", nodeIid);
+                super.onFailure(throwable);
+                unregisterEntityForOwnership(ovsdbConnectionInstance);
+            }
+        });
+    }
+
     public OvsdbClient connect(InstanceIdentifier<Node> iid,
             OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
         LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
@@ -217,7 +246,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
         if (client != null) {
             // Unregister Cluster Onwership for ConnectionInfo
-            unregisterEntityForOwnership(client);
+            deleteOperNodeAndReleaseOwnership(client);
 
             client.disconnect();
 
@@ -254,7 +283,8 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         }
     }
 
-    private void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
+    @VisibleForTesting
+    void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
         clients.put(connectionInfo, instance);
     }
@@ -264,7 +294,8 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         clients.remove(connectionInfo);
     }
 
-    private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
+    @VisibleForTesting
+    void putInstanceIdentifier(ConnectionInfo key, InstanceIdentifier<Node> iid) {
         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
         instanceIdentifiers.put(connectionInfo, iid);
     }
@@ -295,8 +326,8 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
 
     public OvsdbConnectionInstance getConnectionInstance(Node node) {
         Preconditions.checkNotNull(node);
-        OvsdbNodeAugmentation ovsdbNode = node.getAugmentation(OvsdbNodeAugmentation.class);
-        OvsdbBridgeAugmentation ovsdbManagedNode = node.getAugmentation(OvsdbBridgeAugmentation.class);
+        OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
+        OvsdbBridgeAugmentation ovsdbManagedNode = node.augmentation(OvsdbBridgeAugmentation.class);
         if (ovsdbNode != null) {
             return getConnectionInstance(ovsdbNode.getConnectionInfo());
         } else if (ovsdbManagedNode != null) {
@@ -308,16 +339,19 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
     }
 
     public OvsdbConnectionInstance getConnectionInstance(InstanceIdentifier<Node> nodePath) {
+        if (nodeIdVsConnectionInstance.get(nodePath) != null) {
+            return nodeIdVsConnectionInstance.get(nodePath);
+        }
         try {
             ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
             CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
                     LogicalDatastoreType.OPERATIONAL, nodePath);
             transaction.close();
             Optional<Node> optional = nodeFuture.get();
-            if (optional != null && optional.isPresent() && optional.get() != null) {
+            if (optional.isPresent()) {
                 return this.getConnectionInstance(optional.get());
             } else {
-                LOG.warn("Found non-topological node {} on path {}",optional);
+                LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
                 return null;
             }
         } catch (InterruptedException | ExecutionException e) {
@@ -327,7 +361,11 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
     }
 
     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
-        return getConnectionInstance(connectionInfo).getOvsdbClient();
+        OvsdbConnectionInstance connectionInstance = getConnectionInstance(connectionInfo);
+        if (connectionInstance != null) {
+            return connectionInstance.getOvsdbClient();
+        }
+        return null;
     }
 
     public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
@@ -362,12 +400,10 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
     }
 
     public void stopBridgeConfigReconciliationIfActive(InstanceIdentifier<?> iid) {
-        final ReconciliationTask task = new BridgeConfigReconciliationTask(
-                reconciliationManager,
-                this,
-                iid,
-                null);
+        final ReconciliationTask task =
+                new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
         reconciliationManager.dequeue(task);
+        reconciliationManager.cancelTerminationPointReconciliation();
     }
 
     private void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
@@ -377,7 +413,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                         : "that's currently NOT registered by *this* southbound plugin instance");
 
         if (ovsdbConnectionInstance == null) {
-            if (ownershipChange.isOwner()) {
+            if (ownershipChange.getState().isOwner()) {
                 LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
                         + "is NOT registered for ownership", ownershipChange.getEntity());
             } else {
@@ -391,7 +427,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
 
             // If entity has no owner, clean up the operational data store (it's possible because owner controller
             // might went down abruptly and didn't get a chance to clean up the operational data store.
-            if (!ownershipChange.hasOwner()) {
+            if (!ownershipChange.getState().hasOwner()) {
                 LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
                 cleanEntityOperationalData(ownershipChange.getEntity());
             }
@@ -400,7 +436,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         //Connection detail need to be cached, irrespective of ownership result.
         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
 
-        if (ownershipChange.isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
+        if (ownershipChange.getState().isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
             LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
                     ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
                             ? SouthboundConstants.OwnershipStates.OWNER.getState()
@@ -408,15 +444,15 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             return;
         }
 
-        ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
+        ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
         // You were not an owner, but now you are
-        if (ownershipChange.isOwner()) {
+        if (ownershipChange.getState().isOwner()) {
             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
                     ovsdbConnectionInstance.getConnectionInfo());
 
             //*this* instance of southbound plugin is owner of the device,
             //so register for monitor callbacks
-            ovsdbConnectionInstance.registerCallbacks();
+            ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
 
             reconcileBridgeConfigurations(ovsdbConnectionInstance);
         } else {
@@ -439,29 +475,25 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         // are chances that other controller instance went down abruptly and it does
         // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
 
-        @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
-                (InstanceIdentifier<Node>) SouthboundUtil
-                        .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
-
-        txInvoker.invoke(new TransactionCommand() {
-            @Override
-            public void execute(ReadWriteTransaction transaction) {
-                Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
-                if (ovsdbNodeOpt.isPresent()) {
-                    Node ovsdbNode = ovsdbNodeOpt.get();
-                    OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
-                    if (nodeAugmentation != null) {
-                        if (nodeAugmentation.getManagedNodeEntry() != null) {
-                            for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
-                                transaction.delete(
-                                        LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
-                            }
-                        } else {
-                            LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
+        @SuppressWarnings("unchecked")
+        final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
+
+        txInvoker.invoke(transaction -> {
+            Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
+            if (ovsdbNodeOpt.isPresent()) {
+                Node ovsdbNode = ovsdbNodeOpt.get();
+                OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
+                if (nodeAugmentation != null) {
+                    if (nodeAugmentation.getManagedNodeEntry() != null) {
+                        for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
+                            transaction.delete(
+                                    LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
                         }
+                    } else {
+                        LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
                     }
-                    transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
                 }
+                transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
             }
         });
 
@@ -489,7 +521,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             operations.add(op.comment("Fetching Open_VSwitch table rows"));
             try {
                 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
-                if (results != null ) {
+                if (results != null) {
                     OperationResult selectResult = results.get(0);
                     openVSwitchRow = TyperUtils.getTypedRowWrapper(
                             dbSchema,OpenVSwitch.class,selectResult.getRows().get(0));
@@ -503,21 +535,20 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         return openVSwitchRow;
     }
 
-    private Entity getEntityFromConnectionInstance(@Nonnull OvsdbConnectionInstance ovsdbConnectionInstance) {
+    private Entity getEntityFromConnectionInstance(@NonNull OvsdbConnectionInstance ovsdbConnectionInstance) {
         InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
-        if ( iid == null ) {
+        if (iid == null) {
             /* Switch initiated connection won't have iid, till it gets OpenVSwitch
              * table update but update callback is always registered after ownership
              * is granted. So we are explicitly fetch the row here to get the iid.
              */
             OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
-            iid = SouthboundMapper.getInstanceIdentifier(openvswitchRow);
+            iid = SouthboundMapper.getInstanceIdentifier(instanceIdentifierCodec, openvswitchRow);
             LOG.info("InstanceIdentifier {} generated for device "
                     + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
             ovsdbConnectionInstance.setInstanceIdentifier(iid);
         }
-        YangInstanceIdentifier entityId = SouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
-        Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
+        Entity deviceEntity = new Entity(ENTITY_TYPE, iid);
         LOG.debug("Entity {} created for device connection {}",
                 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
         return deviceEntity;
@@ -528,8 +559,16 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
     }
 
     private void registerEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
+        putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(), ovsdbConnectionInstance);
 
         Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
+        if (entityConnectionMap.containsKey(candidateEntity)) {
+            LOG.error("Old connection still hanging for {}", candidateEntity);
+            disconnected(ovsdbConnectionInstance.getOvsdbClient());
+            //TODO do cleanup for old connection or stale check
+        }
+        nodeIdVsConnectionInstance.put((InstanceIdentifier<Node>) candidateEntity.getIdentifier(),
+                ovsdbConnectionInstance);
         entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
         ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
         try {
@@ -538,28 +577,26 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
             LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
 
-            //If entity already has owner, it won't get notification from EntityOwnershipService
-            //so cache the connection instances.
-            Optional<EntityOwnershipState> ownershipStateOpt =
-                    entityOwnershipService.getOwnershipState(candidateEntity);
-            if (ownershipStateOpt.isPresent()) {
-                EntityOwnershipState ownershipState = ownershipStateOpt.get();
-                if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
-                    LOG.info("OVSDB entity {} is already owned by other southbound plugin "
-                                    + "instance, so *this* instance is NOT an OWNER of the device",
-                            ovsdbConnectionInstance.getConnectionInfo());
-                    putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
-                }
-            }
         } catch (CandidateAlreadyRegisteredException e) {
             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
         }
-
+        //If entity already has owner, it won't get notification from EntityOwnershipService
+        java.util.Optional<EntityOwnershipState> ownershipStateOpt =
+                entityOwnershipService.getOwnershipState(candidateEntity);
+        if (ownershipStateOpt.isPresent()) {
+            EntityOwnershipState ownershipState = ownershipStateOpt.get();
+            if (ownershipState == EntityOwnershipState.OWNED_BY_OTHER) {
+                ovsdbConnectionInstance.setHasDeviceOwnership(false);
+            } else if (ownershipState == EntityOwnershipState.IS_OWNER) {
+                ovsdbConnectionInstance.setHasDeviceOwnership(true);
+                ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
+            }
+        }
     }
 
     private void unregisterEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
         ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
-        entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity());
+        entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity(), ovsdbConnectionInstance);
     }
 
     private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
@@ -577,16 +614,14 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
                 reconciliationManager.enqueueForRetry(task);
                 break;
-            case ON_DISCONNECT:
-            {
-                ReadOnlyTransaction tx = db.newReadOnlyTransaction();
-                CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
-                        tx.read(LogicalDatastoreType.CONFIGURATION, iid);
-
-                final OvsdbConnectionManager connectionManager = this;
+            case ON_DISCONNECT: {
+                CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture;
+                try (ReadOnlyTransaction tx = db.newReadOnlyTransaction()) {
+                    readNodeFuture = tx.read(LogicalDatastoreType.CONFIGURATION, iid);
+                }
                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
                     @Override
-                    public void onSuccess(@Nullable Optional<Node> node) {
+                    public void onSuccess(@NonNull Optional<Node> node) {
                         if (node.isPresent()) {
                             LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
                                     + "reconnection", ovsdbNode.getConnectionInfo());
@@ -602,7 +637,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                     public void onFailure(Throwable throwable) {
                         LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
                     }
-                });
+                }, MoreExecutors.directExecutor());
                 break;
             }
             default:
@@ -613,14 +648,14 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
     private void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
         final ReconciliationTask task = new BridgeConfigReconciliationTask(
-                reconciliationManager, OvsdbConnectionManager.this, nodeIid, client);
+                reconciliationManager, OvsdbConnectionManager.this, nodeIid, client, instanceIdentifierCodec);
 
         reconciliationManager.enqueue(task);
     }
 
-    private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
-        private OvsdbConnectionManager cm;
-        private EntityOwnershipListenerRegistration listenerRegistration;
+    private static class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
+        private final OvsdbConnectionManager cm;
+        private final EntityOwnershipListenerRegistration listenerRegistration;
 
         OvsdbDeviceEntityOwnershipListener(OvsdbConnectionManager cm, EntityOwnershipService entityOwnershipService) {
             this.cm = cm;