Statistics collection fix
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImpl.java
index 6e99aa76540234515686d309b530fc60f59858cb..b1cfd251cfad8792e68d60fb58da277ae24b95ea 100644 (file)
 
 package org.opendaylight.openflowplugin.impl.statistics;
 
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Optional;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.Timeout;
 import io.netty.util.TimerTask;
+import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
+import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
+import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * Created by Martin Bobak <mbobak@cisco.com> on 1.4.2015.
  */
-public class StatisticsManagerImpl implements StatisticsManager {
+public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
 
     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
+    private final RpcProviderRegistry rpcProviderRegistry;
 
     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
 
     private HashedWheelTimer hashedWheelTimer;
 
-    private ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap();
-
-    private final TimeCounter timeCounter = new TimeCounter();
+    private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
 
     private static final long basicTimerDelay = 3000;
     private static long currentTimerDelay = basicTimerDelay;
     private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
 
+    private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
+    private Semaphore workModeGuard = new Semaphore(1, true);
+    private boolean shuttingDownStatisticsPolling;
+    private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
+
     @Override
     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
         deviceInitPhaseHandler = handler;
     }
 
+    public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry) {
+        this.rpcProviderRegistry = rpcProviderRegistry;
+        controlServiceRegistration = rpcProviderRegistry.addRpcImplementation(StatisticsManagerControlService.class, this);
+    }
+
+    public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry, final boolean shuttingDownStatisticsPolling) {
+        this(rpcProviderRegistry);
+        this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
+    }
+
     @Override
     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
+        LOG.debug("Node:{}, deviceContext.getDeviceState().getRole():{}", deviceContext.getDeviceState().getNodeId(),
+                deviceContext.getDeviceState().getRole());
+        if (deviceContext.getDeviceState().getRole() == OfpRole.BECOMESLAVE) {
+            // if slave, we dont poll for statistics and jump to rpc initialization
+            LOG.info("Skipping Statistics for slave role for node:{}", deviceContext.getDeviceState().getNodeId());
+            deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
+            return;
+        }
 
         if (null == hashedWheelTimer) {
             LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
             hashedWheelTimer = deviceContext.getTimer();
-            pollStatistics();
         }
 
+        LOG.info("Starting Statistics for master role for node:{}", deviceContext.getDeviceState().getNodeId());
+
         final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
         deviceContext.addDeviceContextClosedHandler(this);
         final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
         Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
             @Override
             public void onSuccess(final Boolean statisticsGathered) {
-                if (statisticsGathered.booleanValue()) {
+                if (statisticsGathered) {
                     //there are some statistics on device worth gathering
                     contexts.put(deviceContext, statisticsContext);
+                    final TimeCounter timeCounter = new TimeCounter();
+                    scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
+                    LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
+                    deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
+                    deviceContext.getDeviceState().setDeviceSynchronized(true);
+                } else {
+                    final String deviceAdress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress().toString();
+                    try {
+                        deviceContext.close();
+                    } catch (Exception e) {
+                        LOG.info("Statistics for device {} could not be gathered. Closing its device context.", deviceAdress);
+                    }
                 }
-                LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
-                deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
-                deviceContext.getDeviceState().setDeviceSynchronized(true);
             }
 
             @Override
@@ -83,42 +133,51 @@ public class StatisticsManagerImpl implements StatisticsManager {
         });
     }
 
-    private void pollStatistics() {
-        try {
-            timeCounter.markStart();
-            for (final StatisticsContext statisticsContext : contexts.values()) {
-                ListenableFuture deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
-                Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback() {
-                    @Override
-                    public void onSuccess(final Object o) {
-                        timeCounter.addTimeMark();
-                    }
+    private void pollStatistics(final DeviceContext deviceContext,
+                                final StatisticsContext statisticsContext,
+                                final TimeCounter timeCounter) {
+        timeCounter.markStart();
+        ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
+        Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
+            @Override
+            public void onSuccess(final Boolean o) {
+                timeCounter.addTimeMark();
+                calculateTimerDelay(timeCounter);
+                scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
+            }
 
-                    @Override
-                    public void onFailure(final Throwable throwable) {
-                        timeCounter.addTimeMark();
-                        LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
-                        LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
-                    }
-                });
+            @Override
+            public void onFailure(final Throwable throwable) {
+                timeCounter.addTimeMark();
+                LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
+                LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
+                calculateTimerDelay(timeCounter);
+                scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
             }
-        } finally {
-            calculateTimerDelay();
-            if (null != hashedWheelTimer) {
-                hashedWheelTimer.newTimeout(new TimerTask() {
+        });
+    }
+
+    private void scheduleNextPolling(final DeviceContext deviceContext,
+                                     final StatisticsContext statisticsContext,
+                                     final TimeCounter timeCounter) {
+        if (null != hashedWheelTimer) {
+            if (!shuttingDownStatisticsPolling) {
+                Timeout pollTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
                     @Override
                     public void run(final Timeout timeout) throws Exception {
-                        pollStatistics();
+                        pollStatistics(deviceContext, statisticsContext, timeCounter);
                     }
                 }, currentTimerDelay, TimeUnit.MILLISECONDS);
+                statisticsContext.setPollTimeout(pollTimeout);
             }
         }
     }
 
-    private void calculateTimerDelay() {
+    @VisibleForTesting
+    protected void calculateTimerDelay(final TimeCounter timeCounter) {
+        // TODO: move into TimeCounter
         long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
-        int numberOfDevices = contexts.size();
-        if ((averageStatisticsGatheringTime * numberOfDevices) > currentTimerDelay) {
+        if (averageStatisticsGatheringTime > currentTimerDelay) {
             currentTimerDelay *= 2;
             if (currentTimerDelay > maximumTimerDelay) {
                 currentTimerDelay = maximumTimerDelay;
@@ -126,16 +185,22 @@ public class StatisticsManagerImpl implements StatisticsManager {
         } else {
             if (currentTimerDelay > basicTimerDelay) {
                 currentTimerDelay /= 2;
+            } else {
+                currentTimerDelay = basicTimerDelay;
             }
         }
     }
 
+    @VisibleForTesting
+    protected static long getCurrentTimerDelay() {
+        return currentTimerDelay;
+    }
+
     @Override
     public void onDeviceContextClosed(final DeviceContext deviceContext) {
-        if (contexts.containsKey(deviceContext)) {
+        StatisticsContext statisticsContext = contexts.remove(deviceContext);
+        if (null != statisticsContext) {
             LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
-            contexts.remove(deviceContext);
-            StatisticsContext statisticsContext = contexts.remove(deviceContext);
             try {
                 statisticsContext.close();
             } catch (Exception e) {
@@ -144,29 +209,62 @@ public class StatisticsManagerImpl implements StatisticsManager {
         }
     }
 
-    private final class TimeCounter {
-        private long beginningOfTime;
-        private long delta;
-        private int marksCount = 0;
-
-        public void markStart() {
-            beginningOfTime = System.currentTimeMillis();
-            delta = 0;
-            marksCount = 0;
-        }
-
-        public void addTimeMark() {
-            delta += System.currentTimeMillis() - beginningOfTime;
-            marksCount++;
-        }
+    @Override
+    public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
+        GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
+        smModeOutputBld.setMode(workMode);
+        return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
+    }
 
-        public long getAverageTimeBetweenMarks() {
-            long average = 0;
-            if (marksCount > 0) {
-                average = delta / marksCount;
+    @Override
+    public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
+        final Future<RpcResult<Void>> result;
+        // acquire exclusive access
+        if (workModeGuard.tryAcquire()) {
+            final StatisticsWorkMode targetWorkMode = input.getMode();
+            if (!workMode.equals(targetWorkMode)) {
+                shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
+                // iterate through stats-ctx: propagate mode
+                for (Map.Entry<DeviceContext, StatisticsContext> contextEntry : contexts.entrySet()) {
+                    final DeviceContext deviceContext = contextEntry.getKey();
+                    final StatisticsContext statisticsContext = contextEntry.getValue();
+                    switch (targetWorkMode) {
+                        case COLLECTALL:
+                            scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
+                            for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
+                                lifeCycleSource.setItemLifecycleListener(null);
+                            }
+                            break;
+                        case FULLYDISABLED:
+                            final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
+                            if (pollTimeout.isPresent()) {
+                                pollTimeout.get().cancel();
+                            }
+                            for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
+                                lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
+                            }
+                            break;
+                        default:
+                            LOG.warn("statistics work mode not supported: {}", targetWorkMode);
+                    }
+                }
+                workMode = targetWorkMode;
             }
-            return average;
+            workModeGuard.release();
+            result = RpcResultBuilder.<Void>success().buildFuture();
+        } else {
+            result = RpcResultBuilder.<Void>failed()
+                    .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
+                    .buildFuture();
         }
+        return result;
+    }
 
+    @Override
+    public void close() {
+        if (controlServiceRegistration != null) {
+            controlServiceRegistration.close();
+            controlServiceRegistration = null;
+        }
     }
 }