schedule next poll only after previous is done
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImpl.java
index 4d64c7f06b9b638405d2a877cad8be07ec10ee2e..ebcb995d30309b0f13a6968b266713a29a2db2e1 100644 (file)
@@ -16,7 +16,7 @@ import io.netty.util.Timeout;
 import io.netty.util.TimerTask;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+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.statistics.StatisticsContext;
@@ -35,7 +35,13 @@ public class StatisticsManagerImpl implements StatisticsManager {
 
     private HashedWheelTimer hashedWheelTimer;
 
-    private ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap();
+    private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
+
+    private final TimeCounter timeCounter = new TimeCounter();
+
+    private static final long basicTimerDelay = 3000;
+    private static long currentTimerDelay = basicTimerDelay;
+    private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
 
     @Override
     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
@@ -48,64 +54,91 @@ public class StatisticsManagerImpl implements StatisticsManager {
         if (null == hashedWheelTimer) {
             LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
             hashedWheelTimer = deviceContext.getTimer();
-            pollStatistics();
         }
 
         final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
         deviceContext.addDeviceContextClosedHandler(this);
-        /*final*/
-        ListenableFuture<Void> weHaveDynamicData = statisticsContext.gatherDynamicData();
-        weHaveDynamicData = Futures.immediateFuture(null);
-        Futures.addCallback(weHaveDynamicData, new FutureCallback<Void>() {
+        final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
+        Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
             @Override
-            public void onSuccess(final Void aVoid) {
-                // wake up RPC registration
-                LOG.trace("Device dynamic info collected. Going to announce raise to next level.");
-                contexts.put(deviceContext, statisticsContext);
-                deviceContext.getDeviceState().setDeviceSynchronized(true);
+            public void onSuccess(final Boolean statisticsGathered) {
+                if (statisticsGathered.booleanValue()) {
+                    //there are some statistics on device worth gathering
+                    contexts.put(deviceContext, statisticsContext);
+                    pollStatistics(deviceContext, statisticsContext);
+                }
+                LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
                 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
+                deviceContext.getDeviceState().setDeviceSynchronized(true);
             }
 
             @Override
             public void onFailure(final Throwable throwable) {
-                LOG.warn("Statistics manager was not able to collect dynamic info for device {}", deviceContext.getDeviceState().getNodeId(), throwable);
+                LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
+                try {
+                    deviceContext.close();
+                } catch (Exception e) {
+                    LOG.warn("Error closing device context.", e);
+                }
             }
         });
     }
 
-    private void pollStatistics() {
-        for (final StatisticsContext statisticsContext : contexts.values()) {
-            ListenableFuture deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
-            Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback() {
-                @Override
-                public void onSuccess(final Object o) {
-                    //nothing to do here
-                }
+    private void pollStatistics(final DeviceContext deviceContext, final StatisticsContext statisticsContext) {
+        timeCounter.markStart();
+        ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
+        Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
+            @Override
+            public void onSuccess(final Boolean o) {
+                timeCounter.addTimeMark();
+                calculateTimerDelay();
+                scheduleNextPolling(deviceContext, statisticsContext);
+            }
 
-                @Override
-                public void onFailure(final Throwable throwable) {
-                    LOG.info("Statistics gathering for single node was not successful.");
+            @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);
+                if (ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
+                    calculateTimerDelay();
+                    scheduleNextPolling(deviceContext, statisticsContext);
                 }
-            });
-        }
+            }
+        });
+    }
+
+    private void scheduleNextPolling(final DeviceContext deviceContext, final StatisticsContext statisticsContext) {
         if (null != hashedWheelTimer) {
             hashedWheelTimer.newTimeout(new TimerTask() {
                 @Override
                 public void run(final Timeout timeout) throws Exception {
-                    pollStatistics();
+                    pollStatistics(deviceContext, statisticsContext);
                 }
-            }, 3000, TimeUnit.MILLISECONDS);
+            }, currentTimerDelay, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    private void calculateTimerDelay() {
+        long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
+        int numberOfDevices = contexts.size();
+        if ((averageStatisticsGatheringTime * numberOfDevices) > currentTimerDelay) {
+            currentTimerDelay *= 2;
+            if (currentTimerDelay > maximumTimerDelay) {
+                currentTimerDelay = maximumTimerDelay;
+            }
+        } else {
+            if (currentTimerDelay > basicTimerDelay) {
+                currentTimerDelay /= 2;
+            }
         }
     }
 
     @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);
-            LOG.trace("Removing node {} from operational DS.", deviceContext.getDeviceState().getNodeId());
-            deviceContext.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, deviceContext.getDeviceState().getNodeInstanceIdentifier());
-            StatisticsContext statisticsContext = contexts.get(deviceContext);
             try {
                 statisticsContext.close();
             } catch (Exception e) {
@@ -113,4 +146,30 @@ public class StatisticsManagerImpl implements StatisticsManager {
             }
         }
     }
+
+    private final class TimeCounter {
+        private long beginningOfTime;
+        private long delta;
+        private int marksCount = 0;
+
+        public void markStart() {
+            beginningOfTime = System.nanoTime();
+            delta = 0;
+            marksCount = 0;
+        }
+
+        public void addTimeMark() {
+            delta += System.nanoTime() - beginningOfTime;
+            marksCount++;
+        }
+
+        public long getAverageTimeBetweenMarks() {
+            long average = 0;
+            if (marksCount > 0) {
+                average = delta / marksCount;
+            }
+            return TimeUnit.NANOSECONDS.toMillis(average);
+        }
+
+    }
 }