Removed unused fields
[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.connection.ConnectionContext;
20 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
21 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
22 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
23 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Created by Martin Bobak <mbobak@cisco.com> on 1.4.2015.
29  */
30 public class StatisticsManagerImpl implements StatisticsManager {
31
32     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
33
34     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
35
36     private HashedWheelTimer hashedWheelTimer;
37
38     private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
39
40     private static final long basicTimerDelay = 3000;
41     private static long currentTimerDelay = basicTimerDelay;
42     private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
43
44     @Override
45     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
46         deviceInitPhaseHandler = handler;
47     }
48
49     @Override
50     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
51
52         if (null == hashedWheelTimer) {
53             LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
54             hashedWheelTimer = deviceContext.getTimer();
55         }
56
57         final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
58         deviceContext.addDeviceContextClosedHandler(this);
59         final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
60         Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
61             @Override
62             public void onSuccess(final Boolean statisticsGathered) {
63                 if (statisticsGathered) {
64                     //there are some statistics on device worth gathering
65                     contexts.put(deviceContext, statisticsContext);
66                     final TimeCounter timeCounter = new TimeCounter();
67                     scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
68                     LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
69                     deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
70                     deviceContext.getDeviceState().setDeviceSynchronized(true);
71                 } else {
72                     final String deviceAdress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress().toString();
73                     try {
74                         deviceContext.close();
75                     } catch (Exception e) {
76                         LOG.info("Statistics for device {} could not be gathered. Closing its device context.", deviceAdress);
77                     }
78                 }
79             }
80
81             @Override
82             public void onFailure(final Throwable throwable) {
83                 LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
84                 try {
85                     deviceContext.close();
86                 } catch (Exception e) {
87                     LOG.warn("Error closing device context.", e);
88                 }
89             }
90         });
91     }
92
93     private void pollStatistics(final DeviceContext deviceContext,
94                                 final StatisticsContext statisticsContext,
95                                 final TimeCounter timeCounter) {
96         timeCounter.markStart();
97         ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
98         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
99             @Override
100             public void onSuccess(final Boolean o) {
101                 timeCounter.addTimeMark();
102                 calculateTimerDelay(timeCounter);
103                 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
104             }
105
106             @Override
107             public void onFailure(final Throwable throwable) {
108                 timeCounter.addTimeMark();
109                 LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
110                 LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
111                 if (ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
112                     calculateTimerDelay(timeCounter);
113                     scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
114                 }
115             }
116         });
117     }
118
119     private void scheduleNextPolling(final DeviceContext deviceContext,
120                                      final StatisticsContext statisticsContext,
121                                      final TimeCounter timeCounter) {
122         if (null != hashedWheelTimer) {
123             Timeout pollTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
124                 @Override
125                 public void run(final Timeout timeout) throws Exception {
126                     pollStatistics(deviceContext, statisticsContext, timeCounter);
127                 }
128             }, currentTimerDelay, TimeUnit.MILLISECONDS);
129             statisticsContext.setPollTimeout(pollTimeout);
130         }
131     }
132
133     private void calculateTimerDelay(final TimeCounter timeCounter) {
134         long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
135         if (averageStatisticsGatheringTime > currentTimerDelay) {
136             currentTimerDelay *= 2;
137             if (currentTimerDelay > maximumTimerDelay) {
138                 currentTimerDelay = maximumTimerDelay;
139             }
140         } else {
141             if (currentTimerDelay > basicTimerDelay) {
142                 currentTimerDelay /= 2;
143             } else {
144                 currentTimerDelay = basicTimerDelay;
145             }
146         }
147     }
148
149     @Override
150     public void onDeviceContextClosed(final DeviceContext deviceContext) {
151         StatisticsContext statisticsContext = contexts.remove(deviceContext);
152         if (null != statisticsContext) {
153             LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
154             try {
155                 statisticsContext.close();
156             } catch (Exception e) {
157                 LOG.debug("Error closing statistic context for node {}.", deviceContext.getDeviceState().getNodeId());
158             }
159         }
160     }
161
162     private final class TimeCounter {
163         private long beginningOfTime;
164         private long delta;
165         private int marksCount = 0;
166
167         public void markStart() {
168             beginningOfTime = System.nanoTime();
169             delta = 0;
170             marksCount = 0;
171         }
172
173         public void addTimeMark() {
174             delta += System.nanoTime() - beginningOfTime;
175             marksCount++;
176         }
177
178         public long getAverageTimeBetweenMarks() {
179             long average = 0;
180             if (marksCount > 0) {
181                 average = delta / marksCount;
182             }
183             return TimeUnit.NANOSECONDS.toMillis(average);
184         }
185
186     }
187 }