Bug 6692: use non-deprecated firstKeyOf() variant
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionManager.java
index 4b783c0fa38f53018289fbf313355c7839af4232..be0ab7e042d9ef6c1d09cc0371b522b788a421b4 100644 (file)
@@ -9,6 +9,13 @@ package org.opendaylight.ovsdb.southbound;
 
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
+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 java.net.ConnectException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
@@ -16,12 +23,10 @@ import java.util.List;
 import java.util.Map;
 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 com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
 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;
@@ -47,6 +52,7 @@ import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationManager;
 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;
@@ -62,15 +68,12 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
-
 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
     private 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;
@@ -104,16 +107,18 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                 externalClient.getConnectionInfo().getLocalPort());
         List<String> databases = new ArrayList<>();
         try {
-            databases = externalClient.getDatabases().get();
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.warn("Unable to fetch database list");
+            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
+                registerEntityForOwnership(client);
+            }
+        } catch (InterruptedException | ExecutionException | TimeoutException e) {
+            LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
+                    externalClient.getConnectionInfo().getRemoteAddress(), e);
+            externalClient.disconnect();
         }
 
-        if(databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
-            OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
-            // Register Cluster Ownership for ConnectionInfo
-            registerEntityForOwnership(client);
-        }
     }
 
     public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
@@ -138,6 +143,8 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             ovsdbConnectionInstance.disconnect();
 
             removeConnectionInstance(key);
+
+            stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
         }
 
         ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
@@ -170,6 +177,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             //Controller initiated connection can be terminated from switch side.
             //So cleanup the instance identifier cache.
             removeInstanceIdentifier(key);
+            stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
             retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
                     ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
                     ConnectionReconciliationTriggers.ON_DISCONNECT);
@@ -177,11 +185,10 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
         }
         LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
-
     }
 
     public OvsdbClient connect(InstanceIdentifier<Node> iid,
-            OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
+            OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
         LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
 
         // TODO handle case where we already have a connection
@@ -215,6 +222,8 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             client.disconnect();
 
             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
+
+            stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
         } else {
             LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
         }
@@ -240,7 +249,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             ovsdbDeviceEntityOwnershipListener.close();
         }
 
-        for (OvsdbClient client: clients.values()) {
+        for (OvsdbConnectionInstance client: clients.values()) {
             client.disconnect();
         }
     }
@@ -265,14 +274,14 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         instanceIdentifiers.remove(connectionInfo);
     }
 
-    public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
+    public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
-        return clients.get(connectionInfo);
+        return instanceIdentifiers.get(connectionInfo);
     }
 
-    public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
+    public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
-        return instanceIdentifiers.get(connectionInfo);
+        return clients.get(connectionInfo);
     }
 
     public OvsdbConnectionInstance getConnectionInstance(OvsdbBridgeAttributes mn) {
@@ -305,28 +314,28 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                     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 (Exception e) {
+        } catch (InterruptedException | ExecutionException e) {
             LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
             return null;
         }
     }
 
     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
-        return getConnectionInstance(connectionInfo);
+        return getConnectionInstance(connectionInfo).getOvsdbClient();
     }
 
     public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
-        return getConnectionInstance(mn);
+        return getConnectionInstance(mn).getOvsdbClient();
     }
 
     public OvsdbClient getClient(Node node) {
-        return getConnectionInstance(node);
+        return getConnectionInstance(node).getOvsdbClient();
     }
 
     public Boolean getHasDeviceOwnership(ConnectionInfo connectionInfo) {
@@ -337,7 +346,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         return ovsdbConnectionInstance.getHasDeviceOwnership();
     }
 
-    public void reconcileConnection(InstanceIdentifier<Node> iid, OvsdbNodeAugmentation ovsdbNode){
+    public void reconcileConnection(InstanceIdentifier<Node> iid, OvsdbNodeAugmentation ovsdbNode) {
         this.retryConnection(iid, ovsdbNode,
                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
 
@@ -351,6 +360,17 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                 ovsdbNode);
         reconciliationManager.dequeue(task);
     }
+
+    public void stopBridgeConfigReconciliationIfActive(InstanceIdentifier<?> iid) {
+        final ReconciliationTask task = new BridgeConfigReconciliationTask(
+                reconciliationManager,
+                this,
+                iid,
+                null);
+        reconciliationManager.dequeue(task);
+        reconciliationManager.cancelTerminationPointReconciliation();
+    }
+
     private void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
         LOG.debug("handleOwnershipChanged: {} event received for device {}",
@@ -384,8 +404,8 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         if (ownershipChange.isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
             LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
                     ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
-                            ? SouthboundConstants.OWNERSHIPSTATES.OWNER.getState()
-                            : SouthboundConstants.OWNERSHIPSTATES.NONOWNER.getState());
+                            ? SouthboundConstants.OwnershipStates.OWNER.getState()
+                            : SouthboundConstants.OwnershipStates.NONOWNER.getState());
             return;
         }
 
@@ -399,6 +419,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             //so register for monitor callbacks
             ovsdbConnectionInstance.registerCallbacks();
 
+            reconcileBridgeConfigurations(ovsdbConnectionInstance);
         } else {
             //You were owner of the device, but now you are not. With the current ownership
             //grant mechanism, this scenario should not occur. Because this scenario will occur
@@ -451,10 +472,10 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         DatabaseSchema dbSchema = null;
         OpenVSwitch openVSwitchRow = null;
         try {
-            dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.databaseName).get();
+            dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
         } catch (InterruptedException | ExecutionException e) {
             LOG.warn("Not able to fetch schema for database {} from device {}",
-                    OvsdbSchemaContants.databaseName,connectionInstance.getConnectionInfo(),e);
+                    OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
         }
         if (dbSchema != null) {
             GenericTableSchema openVSwitchSchema = TyperUtils.getTableSchema(dbSchema, OpenVSwitch.class);
@@ -482,6 +503,7 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
         }
         return openVSwitchRow;
     }
+
     private Entity getEntityFromConnectionInstance(@Nonnull OvsdbConnectionInstance ovsdbConnectionInstance) {
         InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
         if ( iid == null ) {
@@ -549,10 +571,10 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                 iid,
                 ovsdbNode);
 
-        if(reconciliationManager.isEnqueued(task)){
+        if (reconciliationManager.isEnqueued(task)) {
             return;
         }
-        switch(trigger){
+        switch (trigger) {
             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
                 reconciliationManager.enqueueForRetry(task);
                 break;
@@ -567,19 +589,19 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
                     @Override
                     public void onSuccess(@Nullable Optional<Node> node) {
                         if (node.isPresent()) {
-                            LOG.info("Disconnected/Failed connection {} was controller initiated, attempting " +
-                                    "reconnection", ovsdbNode.getConnectionInfo());
+                            LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
+                                    "reconnection", ovsdbNode.getConnectionInfo());
                             reconciliationManager.enqueue(task);
 
                         } else {
-                            LOG.debug("Connection {} was switch initiated, no reconciliation is required"
-                                    iid.firstKeyOf(Node.class).getNodeId());
+                            LOG.debug("Connection {} was switch initiated, no reconciliation is required",
+                                    iid.firstKeyOf(Node.class).getNodeId());
                         }
                     }
 
                     @Override
-                    public void onFailure(Throwable t) {
-                        LOG.warn("Read Config/DS for Node failed! {}", iid, t);
+                    public void onFailure(Throwable throwable) {
+                        LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
                     }
                 });
                 break;
@@ -589,6 +611,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.enqueue(task);
+    }
+
     private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
         private OvsdbConnectionManager cm;
         private EntityOwnershipListenerRegistration listenerRegistration;
@@ -597,9 +627,11 @@ public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoClos
             this.cm = cm;
             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
         }
+
         public void close() {
             listenerRegistration.close();
         }
+
         @Override
         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
             cm.handleOwnershipChanged(ownershipChange);