Do not use calendar time
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImpl.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.impl.statistics;
10
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import io.netty.util.HashedWheelTimer;
15 import io.netty.util.Timeout;
16 import io.netty.util.TimerTask;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.TimeUnit;
19 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
20 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
21 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
22 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Created by Martin Bobak <mbobak@cisco.com> on 1.4.2015.
28  */
29 public class StatisticsManagerImpl implements StatisticsManager {
30
31     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
32
33     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
34
35     private HashedWheelTimer hashedWheelTimer;
36
37     private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
38
39     private final TimeCounter timeCounter = new TimeCounter();
40
41     private static final long basicTimerDelay = 3000;
42     private static long currentTimerDelay = basicTimerDelay;
43     private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
44
45     @Override
46     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
47         deviceInitPhaseHandler = handler;
48     }
49
50     @Override
51     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
52
53         if (null == hashedWheelTimer) {
54             LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
55             hashedWheelTimer = deviceContext.getTimer();
56             pollStatistics();
57         }
58
59         final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
60         deviceContext.addDeviceContextClosedHandler(this);
61         final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
62         Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
63             @Override
64             public void onSuccess(final Boolean statisticsGathered) {
65                 if (statisticsGathered.booleanValue()) {
66                     //there are some statistics on device worth gathering
67                     contexts.put(deviceContext, statisticsContext);
68                 }
69                 LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
70                 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
71                 deviceContext.getDeviceState().setDeviceSynchronized(true);
72             }
73
74             @Override
75             public void onFailure(final Throwable throwable) {
76                 LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
77                 try {
78                     deviceContext.close();
79                 } catch (Exception e) {
80                     LOG.warn("Error closing device context.", e);
81                 }
82             }
83         });
84     }
85
86     private void pollStatistics() {
87         try {
88             timeCounter.markStart();
89             for (final StatisticsContext statisticsContext : contexts.values()) {
90                 ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
91                 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
92                     @Override
93                     public void onSuccess(final Boolean o) {
94                         timeCounter.addTimeMark();
95                     }
96
97                     @Override
98                     public void onFailure(final Throwable throwable) {
99                         timeCounter.addTimeMark();
100                         LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
101                         LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
102                     }
103                 });
104             }
105         } finally {
106             calculateTimerDelay();
107             if (null != hashedWheelTimer) {
108                 hashedWheelTimer.newTimeout(new TimerTask() {
109                     @Override
110                     public void run(final Timeout timeout) throws Exception {
111                         pollStatistics();
112                     }
113                 }, currentTimerDelay, TimeUnit.MILLISECONDS);
114             }
115         }
116     }
117
118     private void calculateTimerDelay() {
119         long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
120         int numberOfDevices = contexts.size();
121         if ((averageStatisticsGatheringTime * numberOfDevices) > currentTimerDelay) {
122             currentTimerDelay *= 2;
123             if (currentTimerDelay > maximumTimerDelay) {
124                 currentTimerDelay = maximumTimerDelay;
125             }
126         } else {
127             if (currentTimerDelay > basicTimerDelay) {
128                 currentTimerDelay /= 2;
129             }
130         }
131     }
132
133     @Override
134     public void onDeviceContextClosed(final DeviceContext deviceContext) {
135         StatisticsContext statisticsContext = contexts.remove(deviceContext);
136         if (null != statisticsContext) {
137             LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
138             try {
139                 statisticsContext.close();
140             } catch (Exception e) {
141                 LOG.debug("Error closing statistic context for node {}.", deviceContext.getDeviceState().getNodeId());
142             }
143         }
144     }
145
146     private final class TimeCounter {
147         private long beginningOfTime;
148         private long delta;
149         private int marksCount = 0;
150
151         public void markStart() {
152             beginningOfTime = System.nanoTime();
153             delta = 0;
154             marksCount = 0;
155         }
156
157         public void addTimeMark() {
158             delta += System.nanoTime() - beginningOfTime;
159             marksCount++;
160         }
161
162         public long getAverageTimeBetweenMarks() {
163             long average = 0;
164             if (marksCount > 0) {
165                 average = delta / marksCount;
166             }
167             return TimeUnit.NANOSECONDS.toMillis(average);
168         }
169
170     }
171 }