Bump odlparent to 5.0.0
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / lifecycle / ContextChainHolderImpl.java
index 1389e33a488aa45d355e31893817161d0e342e22..56045af70992f6ea48fdde65d4b9bb576efe3f8c 100644 (file)
@@ -11,6 +11,7 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.MoreExecutors;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -23,10 +24,9 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
 import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
 import org.opendaylight.openflowplugin.api.openflow.OFPManager;
 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
@@ -50,9 +50,9 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.mdsal.core.general.entity.rev150930.Entity;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -82,22 +82,22 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
         this.executorService = executorService;
         this.ownershipChangeListener = ownershipChangeListener;
         this.ownershipChangeListener.setMasterChecker(this);
-        this.eosListenerRegistration = Objects.requireNonNull(entityOwnershipService
-                .registerListener(ASYNC_SERVICE_ENTITY_TYPE, this));
+        this.eosListenerRegistration = Objects
+                .requireNonNull(entityOwnershipService.registerListener(ASYNC_SERVICE_ENTITY_TYPE, this));
     }
 
     @Override
     public <T extends OFPManager> void addManager(final T manager) {
-        if (Objects.isNull(deviceManager) && manager instanceof DeviceManager) {
+        if (deviceManager == null && manager instanceof DeviceManager) {
             LOG.trace("Context chain holder: Device manager OK.");
             deviceManager = (DeviceManager) manager;
-        } else if (Objects.isNull(rpcManager) && manager instanceof RpcManager) {
+        } else if (rpcManager == null && manager instanceof RpcManager) {
             LOG.trace("Context chain holder: RPC manager OK.");
             rpcManager = (RpcManager) manager;
-        } else if (Objects.isNull(statisticsManager) && manager instanceof StatisticsManager) {
+        } else if (statisticsManager == null && manager instanceof StatisticsManager) {
             LOG.trace("Context chain holder: Statistics manager OK.");
             statisticsManager = (StatisticsManager) manager;
-        } else if (Objects.isNull(roleManager) && manager instanceof RoleManager) {
+        } else if (roleManager == null && manager instanceof RoleManager) {
             LOG.trace("Context chain holder: Role manager OK.");
             roleManager = (RoleManager) manager;
         }
@@ -115,8 +115,8 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
         rpcContext.registerMastershipWatcher(this);
         LOG.debug("RPC" + CONTEXT_CREATED_FOR_CONNECTION, deviceInfo);
 
-        final StatisticsContext statisticsContext = statisticsManager.createContext(deviceContext,
-                ownershipChangeListener.isReconciliationFrameworkRegistered());
+        final StatisticsContext statisticsContext = statisticsManager
+                .createContext(deviceContext, ownershipChangeListener.isReconciliationFrameworkRegistered());
         statisticsContext.registerMastershipWatcher(this);
         LOG.debug("Statistics" + CONTEXT_CREATED_FOR_CONNECTION, deviceInfo);
 
@@ -124,8 +124,7 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
         roleContext.registerMastershipWatcher(this);
         LOG.debug("Role" + CONTEXT_CREATED_FOR_CONNECTION, deviceInfo);
 
-        final ContextChain contextChain = new ContextChainImpl(this, connectionContext,
-                executorService);
+        final ContextChain contextChain = new ContextChainImpl(this, connectionContext, executorService);
         contextChain.registerDeviceRemovedHandler(deviceManager);
         contextChain.registerDeviceRemovedHandler(rpcManager);
         contextChain.registerDeviceRemovedHandler(statisticsManager);
@@ -144,18 +143,16 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
     }
 
     @Override
-    public ConnectionStatus deviceConnected(final ConnectionContext connectionContext) throws Exception {
-
+    public ConnectionStatus deviceConnected(final ConnectionContext connectionContext) {
         final DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
         final ContextChain contextChain = contextChainMap.get(deviceInfo);
-
         final FeaturesReply featuresReply = connectionContext.getFeatures();
         final Short auxiliaryId = featuresReply != null ? featuresReply.getAuxiliaryId() : null;
 
         if (auxiliaryId != null && auxiliaryId != 0) {
             if (contextChain == null) {
                 LOG.warn("An auxiliary connection for device {}, but no primary connection. Refusing connection.",
-                        deviceInfo);
+                         deviceInfo);
                 return ConnectionStatus.REFUSING_AUXILIARY_CONNECTION;
             } else {
                 if (contextChain.addAuxiliaryConnection(connectionContext)) {
@@ -179,7 +176,7 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
             if (contextExists) {
                 if (isClosing) {
                     LOG.warn("Device {} is already in termination state, closing all incoming connections.",
-                            deviceInfo);
+                             deviceInfo);
                     return ConnectionStatus.CLOSING;
                 }
 
@@ -198,8 +195,7 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
     }
 
     @Override
-    public void onNotAbleToStartMastership(@Nonnull final DeviceInfo deviceInfo,
-                                           @Nonnull final String reason,
+    public void onNotAbleToStartMastership(@Nonnull final DeviceInfo deviceInfo, @Nonnull final String reason,
                                            final boolean mandatory) {
         LOG.warn("Not able to set MASTER role on device {}, reason: {}", deviceInfo, reason);
 
@@ -209,7 +205,7 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
 
         Optional.ofNullable(contextChainMap.get(deviceInfo)).ifPresent(contextChain -> {
             LOG.warn("This mastering is mandatory, destroying context chain and closing connection for device {}.",
-                    deviceInfo);
+                     deviceInfo);
             destroyContextChain(deviceInfo);
         });
     }
@@ -218,13 +214,12 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
     public void onMasterRoleAcquired(@Nonnull final DeviceInfo deviceInfo,
                                      @Nonnull final ContextChainMastershipState mastershipState) {
         Optional.ofNullable(contextChainMap.get(deviceInfo)).ifPresent(contextChain -> {
-            if (ownershipChangeListener.isReconciliationFrameworkRegistered() &&
-                    !ContextChainMastershipState.INITIAL_SUBMIT.equals(mastershipState)) {
+            if (ownershipChangeListener.isReconciliationFrameworkRegistered()
+                    && !ContextChainMastershipState.INITIAL_SUBMIT.equals(mastershipState)) {
                 if (contextChain.isMastered(mastershipState, true)) {
-                    Futures.addCallback(
-                            ownershipChangeListener.becomeMasterBeforeSubmittedDS(deviceInfo),
-                            reconciliationFrameworkCallback(deviceInfo, contextChain),
-                            MoreExecutors.directExecutor());
+                    Futures.addCallback(ownershipChangeListener.becomeMasterBeforeSubmittedDS(deviceInfo),
+                                        reconciliationFrameworkCallback(deviceInfo, contextChain),
+                                        MoreExecutors.directExecutor());
                 }
             } else if (contextChain.isMastered(mastershipState, false)) {
                 LOG.info("Role MASTER was granted to device {}", deviceInfo);
@@ -251,28 +246,28 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
     public void onDeviceDisconnected(final ConnectionContext connectionContext) {
         final DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
 
-        Optional.ofNullable(connectionContext.getDeviceInfo())
-                .map(contextChainMap::get)
-                .ifPresent(contextChain -> {
-                    if (contextChain.auxiliaryConnectionDropped(connectionContext)) {
-                        LOG.info("Auxiliary connection from device {} disconnected.", deviceInfo);
-                    } else {
-                        LOG.info("Device {} disconnected.", deviceInfo);
-                        destroyContextChain(deviceInfo);
-                    }
-                });
+        Optional.ofNullable(connectionContext.getDeviceInfo()).map(contextChainMap::get).ifPresent(contextChain -> {
+            if (contextChain.auxiliaryConnectionDropped(connectionContext)) {
+                LOG.info("Auxiliary connection from device {} disconnected.", deviceInfo);
+            } else {
+                LOG.info("Device {} disconnected.", deviceInfo);
+                destroyContextChain(deviceInfo);
+            }
+        });
     }
 
     @VisibleForTesting
     boolean checkAllManagers() {
-        return Objects.nonNull(deviceManager)
-                && Objects.nonNull(rpcManager)
-                && Objects.nonNull(statisticsManager)
-                && Objects.nonNull(roleManager);
+        return deviceManager != null && rpcManager != null && statisticsManager != null && roleManager != null;
+    }
+
+    @Override
+    public ContextChain getContextChain(final DeviceInfo deviceInfo) {
+        return contextChainMap.get(deviceInfo);
     }
 
     @Override
-    public void close() throws Exception {
+    public void close() {
         Map<DeviceInfo, ContextChain> copyOfChains = new HashMap<>(contextChainMap);
         copyOfChains.keySet().forEach(this::destroyContextChain);
         copyOfChains.clear();
@@ -281,30 +276,35 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
     }
 
     @Override
+    @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
     public void ownershipChanged(EntityOwnershipChange entityOwnershipChange) {
-        if (entityOwnershipChange.hasOwner()) {
+        if (entityOwnershipChange.getState().hasOwner()) {
             return;
         }
 
-        final String entityName = getEntityNameFromOwnershipChange(entityOwnershipChange);
+        // Findbugs flags a false violation for "Unchecked/unconfirmed cast" from GenericEntity to Entity hence the
+        // suppression above. The suppression is temporary until EntityOwnershipChange is modified to eliminate the
+        // violation.
+        final String entityName = entityOwnershipChange
+                .getEntity()
+                .getIdentifier()
+                .firstKeyOf(Entity.class)
+                .getName();
 
-        if (Objects.nonNull(entityName)) {
+        if (entityName != null) {
             LOG.debug("Entity {} has no owner", entityName);
-            final NodeId nodeId = new NodeId(entityName);
-
             try {
+                //TODO:Remove notifications
                 final KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier =
-                        DeviceStateUtil.createNodeInstanceIdentifier(nodeId);
-
+                        DeviceStateUtil.createNodeInstanceIdentifier(new NodeId(entityName));
                 deviceManager.sendNodeRemovedNotification(nodeInstanceIdentifier);
 
-                LOG.info("Try to remove device {} from operational DS", nodeId);
-                deviceManager
-                        .removeDeviceFromOperationalDS(nodeInstanceIdentifier)
+                LOG.info("Try to remove device {} from operational DS", entityName);
+                deviceManager.removeDeviceFromOperationalDS(nodeInstanceIdentifier)
                         .get(REMOVE_DEVICE_FROM_DS_TIMEOUT, TimeUnit.MILLISECONDS);
-                LOG.info("Removing device from operational DS {} was successful", nodeId);
+                LOG.info("Removing device from operational DS {} was successful", entityName);
             } catch (TimeoutException | ExecutionException | NullPointerException | InterruptedException e) {
-                LOG.warn("Not able to remove device {} from operational DS. ",nodeId, e);
+                LOG.warn("Not able to remove device {} from operational DS. ", entityName, e);
             }
         }
     }
@@ -314,45 +314,23 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
         Optional.ofNullable(contextChainMap.get(deviceInfo)).ifPresent(contextChain -> {
             deviceManager.sendNodeRemovedNotification(deviceInfo.getNodeInstanceIdentifier());
             contextChain.close();
+            connectingDevices.remove(deviceInfo);
         });
     }
 
     @Override
     public List<DeviceInfo> listOfMasteredDevices() {
-        return contextChainMap
-                .entrySet()
-                .stream()
-                .filter(deviceInfoContextChainEntry -> deviceInfoContextChainEntry
-                        .getValue()
-                        .isMastered(ContextChainMastershipState.CHECK, false))
-                .map(Map.Entry::getKey)
+        return contextChainMap.entrySet().stream()
+                .filter(deviceInfoContextChainEntry -> deviceInfoContextChainEntry.getValue()
+                        .isMastered(ContextChainMastershipState.CHECK, false)).map(Map.Entry::getKey)
                 .collect(Collectors.toList());
     }
 
     @Override
     public boolean isAnyDeviceMastered() {
-        return contextChainMap
-                .entrySet()
-                .stream()
-                .findAny()
+        return contextChainMap.entrySet().stream().findAny()
                 .filter(deviceInfoContextChainEntry -> deviceInfoContextChainEntry.getValue()
-                        .isMastered(ContextChainMastershipState.CHECK, false))
-                .isPresent();
-    }
-
-    private String getEntityNameFromOwnershipChange(final EntityOwnershipChange entityOwnershipChange) {
-        final YangInstanceIdentifier.NodeIdentifierWithPredicates lastIdArgument =
-                (YangInstanceIdentifier.NodeIdentifierWithPredicates) entityOwnershipChange
-                        .getEntity()
-                        .getId()
-                        .getLastPathArgument();
-
-        return lastIdArgument
-                .getKeyValues()
-                .values()
-                .iterator()
-                .next()
-                .toString();
+                        .isMastered(ContextChainMastershipState.CHECK, false)).isPresent();
     }
 
     @Override
@@ -361,12 +339,11 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
         LOG.debug("Context chain removed for node {}", deviceInfo);
     }
 
-    private FutureCallback<ResultState> reconciliationFrameworkCallback(
-            @Nonnull DeviceInfo deviceInfo,
-            ContextChain contextChain) {
+    private FutureCallback<ResultState> reconciliationFrameworkCallback(@Nonnull DeviceInfo deviceInfo,
+                                                                        ContextChain contextChain) {
         return new FutureCallback<ResultState>() {
             @Override
-            public void onSuccess(@Nullable ResultState result) {
+            public void onSuccess(ResultState result) {
                 if (ResultState.DONOTHING == result) {
                     LOG.info("Device {} connection is enabled by reconciliation framework.", deviceInfo);
                     contextChain.continueInitializationAfterReconciliation();
@@ -377,7 +354,7 @@ public class ContextChainHolderImpl implements ContextChainHolder, MasterChecker
             }
 
             @Override
-            public void onFailure(@Nonnull Throwable throwable) {
+            public void onFailure(Throwable throwable) {
                 LOG.warn("Reconciliation framework failure.");
                 destroyContextChain(deviceInfo);
             }