Merge "Bug 6110: Fixed bugs in statistics manager due to race condition." into stable...
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsContextImpl.java
index eafdc7a4aaf53c144ca115520458f5b870accd3f..3002b8e632d83e53bb23b5d0f6f6376c92605cf0 100644 (file)
@@ -9,7 +9,7 @@
 package org.opendaylight.openflowplugin.impl.statistics;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
+import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterators;
@@ -23,28 +23,35 @@ import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
-import javax.annotation.CheckForNull;
+import java.util.Objects;
+import java.util.Optional;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.mdsal.common.api.TransactionChainClosedException;
+import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.openflowplugin.api.ConnectionException;
 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
-import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
+import org.opendaylight.openflowplugin.api.openflow.device.handlers.ClusterInitializationPhaseHandler;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
+import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
 import org.opendaylight.openflowplugin.impl.rpc.listener.ItemLifecycleListenerImpl;
 import org.opendaylight.openflowplugin.impl.services.RequestContextUtil;
 import org.opendaylight.openflowplugin.impl.statistics.services.dedicated.StatisticsGatheringOnTheFlyService;
 import org.opendaylight.openflowplugin.impl.statistics.services.dedicated.StatisticsGatheringService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class StatisticsContextImpl implements StatisticsContext {
+class StatisticsContextImpl implements StatisticsContext {
 
     private static final Logger LOG = LoggerFactory.getLogger(StatisticsContextImpl.class);
     private static final String CONNECTION_CLOSED = "Connection closed.";
@@ -54,34 +61,50 @@ public class StatisticsContextImpl implements StatisticsContext {
     private final DeviceContext deviceContext;
     private final DeviceState devState;
     private final ListenableFuture<Boolean> emptyFuture;
-    private final boolean shuttingDownStatisticsPolling;
-    private final Object COLLECTION_STAT_TYPE_LOCK = new Object();
-    @GuardedBy("COLLECTION_STAT_TYPE_LOCK")
+    private final boolean isStatisticsPollingOn;
+    private final SinglePurposeMultipartReplyTranslator multipartReplyTranslator;
+    private final Object collectionStatTypeLock = new Object();
+    @GuardedBy("collectionStatTypeLock")
     private List<MultipartType> collectingStatType;
 
     private StatisticsGatheringService statisticsGatheringService;
     private StatisticsGatheringOnTheFlyService statisticsGatheringOnTheFlyService;
     private Timeout pollTimeout;
+    private final DeviceInfo deviceInfo;
+    private final StatisticsManager myManager;
+    private final LifecycleService lifecycleService;
 
-    private final LifecycleConductor conductor;
     private volatile boolean schedulingEnabled;
-
-    public StatisticsContextImpl(@CheckForNull final NodeId nodeId, final boolean shuttingDownStatisticsPolling, final LifecycleConductor lifecycleConductor) {
-        this.conductor = lifecycleConductor;
-        this.deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
+    private volatile CONTEXT_STATE state;
+    private ClusterInitializationPhaseHandler clusterInitializationPhaseHandler;
+    private ClusterInitializationPhaseHandler initialSubmitHandler;
+
+    private ListenableFuture<Boolean> lastDataGathering;
+
+    StatisticsContextImpl(@Nonnull final DeviceInfo deviceInfo,
+                          final boolean isStatisticsPollingOn,
+                          @Nonnull final LifecycleService lifecycleService,
+                          @Nonnull final ConvertorExecutor convertorExecutor,
+                          @Nonnull final StatisticsManager myManager) {
+        this.lifecycleService = lifecycleService;
+        this.deviceContext = lifecycleService.getDeviceContext();
         this.devState = Preconditions.checkNotNull(deviceContext.getDeviceState());
-        this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
+        this.isStatisticsPollingOn = isStatisticsPollingOn;
+        multipartReplyTranslator = new SinglePurposeMultipartReplyTranslator(convertorExecutor);
         emptyFuture = Futures.immediateFuture(false);
         statisticsGatheringService = new StatisticsGatheringService(this, deviceContext);
-        statisticsGatheringOnTheFlyService = new StatisticsGatheringOnTheFlyService(this, deviceContext);
+        statisticsGatheringOnTheFlyService = new StatisticsGatheringOnTheFlyService(this, deviceContext, convertorExecutor);
         itemLifeCycleListener = new ItemLifecycleListenerImpl(deviceContext);
         statListForCollectingInitialization();
-        this.deviceContext.setStatisticsContext(StatisticsContextImpl.this);
+        this.state = CONTEXT_STATE.INITIALIZATION;
+        this.deviceInfo = deviceInfo;
+        this.myManager = myManager;
+        this.lastDataGathering = null;
     }
 
     @Override
     public void statListForCollectingInitialization() {
-        synchronized (COLLECTION_STAT_TYPE_LOCK) {
+        synchronized (collectionStatTypeLock) {
             final List<MultipartType> statListForCollecting = new ArrayList<>();
             if (devState.isTableStatisticsAvailable()) {
                 statListForCollecting.add(MultipartType.OFPMPTABLE);
@@ -107,24 +130,35 @@ public class StatisticsContextImpl implements StatisticsContext {
         }
     }
 
+
+    @Override
+    public ListenableFuture<Boolean> initialGatherDynamicData() {
+        return gatherDynamicData(true);
+    }
+
     @Override
-    public ListenableFuture<Boolean> gatherDynamicData() {
-        if (shuttingDownStatisticsPolling) {
-            LOG.debug("Statistics for device {} is not enabled.", deviceContext.getDeviceState().getNodeId());
+    public ListenableFuture<Boolean> gatherDynamicData(){
+        return gatherDynamicData(false);
+    }
+
+    private ListenableFuture<Boolean> gatherDynamicData(final boolean initial) {
+        this.lastDataGathering = null;
+        if (!isStatisticsPollingOn) {
+            LOG.debug("Statistics for device {} is not enabled.", getDeviceInfo().getNodeId().getValue());
             return Futures.immediateFuture(Boolean.TRUE);
         }
         final ListenableFuture<Boolean> errorResultFuture = deviceConnectionCheck();
         if (errorResultFuture != null) {
             return errorResultFuture;
         }
-        synchronized (COLLECTION_STAT_TYPE_LOCK) {
+        synchronized (collectionStatTypeLock) {
             final Iterator<MultipartType> statIterator = collectingStatType.iterator();
             final SettableFuture<Boolean> settableStatResultFuture = SettableFuture.create();
 
             // write start timestamp to state snapshot container
             StatisticsGatheringUtils.markDeviceStateSnapshotStart(deviceContext);
 
-            statChainFuture(statIterator, settableStatResultFuture);
+            statChainFuture(statIterator, settableStatResultFuture, initial);
 
             // write end timestamp to state snapshot container
             Futures.addCallback(settableStatResultFuture, new FutureCallback<Boolean>() {
@@ -134,41 +168,55 @@ public class StatisticsContextImpl implements StatisticsContext {
                 }
                 @Override
                 public void onFailure(final Throwable t) {
-                    StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceContext, false);
+                    if (!(t instanceof TransactionChainClosedException)) {
+                        StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceContext, false);
+                    }
                 }
             });
+            this.lastDataGathering = settableStatResultFuture;
             return settableStatResultFuture;
         }
     }
 
-    private ListenableFuture<Boolean> chooseStat(final MultipartType multipartType){
+    private ListenableFuture<Boolean> chooseStat(final MultipartType multipartType, final boolean initial){
+        ListenableFuture<Boolean> result = Futures.immediateCheckedFuture(Boolean.TRUE);
+
         switch (multipartType) {
             case OFPMPFLOW:
-                return collectFlowStatistics(multipartType);
+                result = collectFlowStatistics(multipartType, initial);
+                break;
             case OFPMPTABLE:
-                return collectTableStatistics(multipartType);
+                result = collectTableStatistics(multipartType);
+                break;
             case OFPMPPORTSTATS:
-                return collectPortStatistics(multipartType);
+                result = collectPortStatistics(multipartType);
+                break;
             case OFPMPQUEUE:
-                return collectQueueStatistics(multipartType);
+                result = collectQueueStatistics(multipartType);
+                break;
             case OFPMPGROUPDESC:
-                return collectGroupDescStatistics(multipartType);
+                result = collectGroupDescStatistics(multipartType);
+                break;
             case OFPMPGROUP:
-                return collectGroupStatistics(multipartType);
+                result = collectGroupStatistics(multipartType);
+                break;
             case OFPMPMETERCONFIG:
-                return collectMeterConfigStatistics(multipartType);
+                result = collectMeterConfigStatistics(multipartType);
+                break;
             case OFPMPMETER:
-                return collectMeterStatistics(multipartType);
+                result = collectMeterStatistics(multipartType);
+                break;
             default:
-                LOG.warn("Unsuported Statistics type {}", multipartType);
-                return Futures.immediateCheckedFuture(Boolean.TRUE);
+                LOG.warn("Unsupported Statistics type {}", multipartType);
         }
+
+        return result;
     }
 
 
     @Override
     public <T> RequestContext<T> createRequestContext() {
-        final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceContext.reserveXidForDeviceMessage()) {
+        final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceInfo.reserveXidForDeviceMessage()) {
             @Override
             public void close() {
                 requestContexts.remove(this);
@@ -180,13 +228,27 @@ public class StatisticsContextImpl implements StatisticsContext {
 
     @Override
     public void close() {
-        schedulingEnabled = false;
-        for (final Iterator<RequestContext<?>> iterator = Iterators.consumingIterator(requestContexts.iterator());
-                iterator.hasNext();) {
-            RequestContextUtil.closeRequestContextWithRpcError(iterator.next(), CONNECTION_CLOSED);
-        }
-        if (null != pollTimeout && !pollTimeout.isExpired()) {
-            pollTimeout.cancel();
+        if (CONTEXT_STATE.TERMINATION.equals(getState())) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("StatisticsContext for node {} is already in TERMINATION state.", getDeviceInfo().getLOGValue());
+            }
+        } else {
+            try {
+                stopClusterServices().get();
+            } catch (Exception e) {
+                LOG.debug("Failed to close StatisticsContext for node {} with exception: ", getDeviceInfo().getLOGValue(), e);
+            }
+
+            this.state = CONTEXT_STATE.TERMINATION;
+
+            for (final Iterator<RequestContext<?>> iterator = Iterators.consumingIterator(requestContexts.iterator());
+                 iterator.hasNext(); ) {
+                RequestContextUtil.closeRequestContextWithRpcError(iterator.next(), CONNECTION_CLOSED);
+            }
+
+            if (null != pollTimeout && !pollTimeout.isExpired()) {
+                pollTimeout.cancel();
+            }
         }
     }
 
@@ -207,31 +269,31 @@ public class StatisticsContextImpl implements StatisticsContext {
 
     @Override
     public Optional<Timeout> getPollTimeout() {
-        return Optional.fromNullable(pollTimeout);
+        return Optional.ofNullable(pollTimeout);
     }
 
-    private void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture) {
+    private void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture, final boolean initial) {
         if (ConnectionContext.CONNECTION_STATE.RIP.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
             final String errMsg = String.format("Device connection is closed for Node : %s.",
-                    deviceContext.getDeviceState().getNodeId());
+                    getDeviceInfo().getNodeId());
             LOG.debug(errMsg);
-            resultFuture.setException(new IllegalStateException(errMsg));
+            resultFuture.setException(new ConnectionException(errMsg));
             return;
         }
         if ( ! iterator.hasNext()) {
             resultFuture.set(Boolean.TRUE);
-            LOG.debug("Stats collection successfully finished for node {}", deviceContext.getDeviceState().getNodeId());
+            LOG.debug("Stats collection successfully finished for node {}", getDeviceInfo().getLOGValue());
             return;
         }
 
         final MultipartType nextType = iterator.next();
-        LOG.debug("Stats iterating to next type for node {} of type {}", deviceContext.getDeviceState().getNodeId(), nextType);
+        LOG.debug("Stats iterating to next type for node {} of type {}", getDeviceInfo().getLOGValue(), nextType);
 
-        final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType);
+        final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType, initial);
         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
             @Override
             public void onSuccess(final Boolean result) {
-                statChainFuture(iterator, resultFuture);
+                statChainFuture(iterator, resultFuture, initial);
             }
             @Override
             public void onFailure(@Nonnull final Throwable t) {
@@ -249,7 +311,7 @@ public class StatisticsContextImpl implements StatisticsContext {
     @VisibleForTesting
     ListenableFuture<Boolean> deviceConnectionCheck() {
         if (!ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
-            ListenableFuture<Boolean> resultingFuture = SettableFuture.create();
+            ListenableFuture<Boolean> resultingFuture;
             switch (deviceContext.getPrimaryConnectionContext().getConnectionState()) {
                 case RIP:
                     final String errMsg = String.format("Device connection doesn't exist anymore. Primary connection status : %s",
@@ -265,44 +327,85 @@ public class StatisticsContextImpl implements StatisticsContext {
         return null;
     }
 
-    private ListenableFuture<Boolean> collectFlowStatistics(final MultipartType multipartType) {
+    //TODO: Refactor twice sending deviceContext into gatheringStatistics
+    private ListenableFuture<Boolean> collectFlowStatistics(final MultipartType multipartType, final boolean initial) {
         return devState.isFlowStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringOnTheFlyService, deviceContext, /*MultipartType.OFPMPFLOW*/ multipartType) : emptyFuture;
+                statisticsGatheringOnTheFlyService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPFLOW*/ multipartType,
+                deviceContext,
+                deviceContext,
+                initial, multipartReplyTranslator) : emptyFuture;
     }
 
     private ListenableFuture<Boolean> collectTableStatistics(final MultipartType multipartType) {
         return devState.isTableStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPTABLE*/ multipartType) : emptyFuture;
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPTABLE*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator) : emptyFuture;
     }
 
     private ListenableFuture<Boolean> collectPortStatistics(final MultipartType multipartType) {
         return devState.isPortStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPPORTSTATS*/ multipartType) : emptyFuture;
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPPORTSTATS*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator) : emptyFuture;
     }
 
     private ListenableFuture<Boolean> collectQueueStatistics(final MultipartType multipartType) {
-        return devState.isQueueStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPQUEUE*/ multipartType) : emptyFuture;
+        return !devState.isQueueStatisticsAvailable() ? emptyFuture : StatisticsGatheringUtils.gatherStatistics(
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPQUEUE*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator);
     }
 
     private ListenableFuture<Boolean> collectGroupDescStatistics(final MultipartType multipartType) {
         return devState.isGroupAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPGROUPDESC*/ multipartType) : emptyFuture;
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPGROUPDESC*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator) : emptyFuture;
     }
 
     private ListenableFuture<Boolean> collectGroupStatistics(final MultipartType multipartType) {
         return devState.isGroupAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPGROUP*/ multipartType) : emptyFuture;
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPGROUP*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator) : emptyFuture;
     }
 
     private ListenableFuture<Boolean> collectMeterConfigStatistics(final MultipartType multipartType) {
         return devState.isMetersAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPMETERCONFIG*/ multipartType) : emptyFuture;
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPMETERCONFIG*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator) : emptyFuture;
     }
 
     private ListenableFuture<Boolean> collectMeterStatistics(final MultipartType multipartType) {
         return devState.isMetersAvailable() ? StatisticsGatheringUtils.gatherStatistics(
-                statisticsGatheringService, deviceContext, /*MultipartType.OFPMPMETER*/ multipartType) : emptyFuture;
+                statisticsGatheringService,
+                getDeviceInfo(),
+                /*MultipartType.OFPMPMETER*/ multipartType,
+                deviceContext,
+                deviceContext,
+                false, multipartReplyTranslator) : emptyFuture;
     }
 
     @VisibleForTesting
@@ -321,9 +424,97 @@ public class StatisticsContextImpl implements StatisticsContext {
         return itemLifeCycleListener;
     }
 
+    @Override
+    public CONTEXT_STATE getState() {
+        return this.state;
+    }
+
+    @Override
+    public ServiceGroupIdentifier getServiceIdentifier() {
+        return this.deviceInfo.getServiceIdentifier();
+    }
+
+    @Override
+    public DeviceInfo getDeviceInfo() {
+        return this.deviceInfo;
+    }
+
+    @Override
+    public ListenableFuture<Void> stopClusterServices() {
+        if (CONTEXT_STATE.TERMINATION.equals(getState())) {
+            return Futures.immediateCancelledFuture();
+        }
+
+        return Futures.transform(Futures.immediateFuture(null), new Function<Object, Void>() {
+            @Nullable
+            @Override
+            public Void apply(@Nullable Object input) {
+                schedulingEnabled = false;
+                stopGatheringData();
+                return null;
+            }
+        });
+    }
+
+    @Override
+    public DeviceState gainDeviceState() {
+        return gainDeviceContext().getDeviceState();
+    }
+
+    @Override
+    public DeviceContext gainDeviceContext() {
+        return this.lifecycleService.getDeviceContext();
+    }
+
+    @Override
+    public void stopGatheringData() {
+        if (Objects.nonNull(this.lastDataGathering)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Stop the running statistics gathering for node {}", this.deviceInfo.getLOGValue());
+            }
+
+            lastDataGathering.cancel(true);
+        }
+    }
+
+    @Override
+    public void setLifecycleInitializationPhaseHandler(final ClusterInitializationPhaseHandler handler) {
+        this.clusterInitializationPhaseHandler = handler;
+    }
+
+    @Override
+    public boolean onContextInstantiateService(final ConnectionContext connectionContext) {
+        if (connectionContext.getConnectionState().equals(ConnectionContext.CONNECTION_STATE.RIP)) {
+            LOG.warn("Connection on device {} was interrupted, will stop starting master services.", deviceInfo.getLOGValue());
+            return false;
+        }
+
+        LOG.info("Starting statistics context cluster services for node {}", deviceInfo.getLOGValue());
+
+        this.statListForCollectingInitialization();
+        Futures.addCallback(this.initialGatherDynamicData(), new FutureCallback<Boolean>() {
+
+            @Override
+            public void onSuccess(@Nullable Boolean aBoolean) {
+                initialSubmitHandler.initialSubmitTransaction();
+            }
+
+            @Override
+            public void onFailure(Throwable throwable) {
+                LOG.warn("Initial gathering statistics unsuccessful for node {}", deviceInfo.getLOGValue());
+                lifecycleService.closeConnection();
+            }
+        });
+
+        if (this.isStatisticsPollingOn) {
+            myManager.startScheduling(deviceInfo);
+        }
+
+        return this.clusterInitializationPhaseHandler.onContextInstantiateService(connectionContext);
+    }
 
     @Override
-    public DeviceContext getDeviceContext() {
-        return deviceContext;
+    public void setInitialSubmitHandler(final ClusterInitializationPhaseHandler initialSubmitHandler) {
+        this.initialSubmitHandler = initialSubmitHandler;
     }
-}
+}
\ No newline at end of file