Merge "Cleanup IpConversionUtil"
[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 final TimeCounter timeCounter = new TimeCounter();
41
42     private static final long basicTimerDelay = 3000;
43     private static long currentTimerDelay = basicTimerDelay;
44     private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
45
46     @Override
47     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
48         deviceInitPhaseHandler = handler;
49     }
50
51     @Override
52     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
53
54         if (null == hashedWheelTimer) {
55             LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
56             hashedWheelTimer = deviceContext.getTimer();
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                     pollStatistics(deviceContext, statisticsContext);
69                 }
70                 LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
71                 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
72                 deviceContext.getDeviceState().setDeviceSynchronized(true);
73             }
74
75             @Override
76             public void onFailure(final Throwable throwable) {
77                 LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
78                 try {
79                     deviceContext.close();
80                 } catch (Exception e) {
81                     LOG.warn("Error closing device context.", e);
82                 }
83             }
84         });
85     }
86
87     private void pollStatistics(final DeviceContext deviceContext, final StatisticsContext statisticsContext) {
88         timeCounter.markStart();
89         ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
90         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
91             @Override
92             public void onSuccess(final Boolean o) {
93                 timeCounter.addTimeMark();
94                 calculateTimerDelay();
95                 scheduleNextPolling(deviceContext, statisticsContext);
96             }
97
98             @Override
99             public void onFailure(final Throwable throwable) {
100                 timeCounter.addTimeMark();
101                 LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
102                 LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
103                 if (ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
104                     calculateTimerDelay();
105                     scheduleNextPolling(deviceContext, statisticsContext);
106                 }
107             }
108         });
109     }
110
111     private void scheduleNextPolling(final DeviceContext deviceContext, final StatisticsContext statisticsContext) {
112         if (null != hashedWheelTimer) {
113             hashedWheelTimer.newTimeout(new TimerTask() {
114                 @Override
115                 public void run(final Timeout timeout) throws Exception {
116                     pollStatistics(deviceContext, statisticsContext);
117                 }
118             }, currentTimerDelay, TimeUnit.MILLISECONDS);
119         }
120     }
121
122     private void calculateTimerDelay() {
123         long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
124         int numberOfDevices = contexts.size();
125         if ((averageStatisticsGatheringTime * numberOfDevices) > currentTimerDelay) {
126             currentTimerDelay *= 2;
127             if (currentTimerDelay > maximumTimerDelay) {
128                 currentTimerDelay = maximumTimerDelay;
129             }
130         } else {
131             if (currentTimerDelay > basicTimerDelay) {
132                 currentTimerDelay /= 2;
133             }
134         }
135     }
136
137     @Override
138     public void onDeviceContextClosed(final DeviceContext deviceContext) {
139         StatisticsContext statisticsContext = contexts.remove(deviceContext);
140         if (null != statisticsContext) {
141             LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
142             try {
143                 statisticsContext.close();
144             } catch (Exception e) {
145                 LOG.debug("Error closing statistic context for node {}.", deviceContext.getDeviceState().getNodeId());
146             }
147         }
148     }
149
150     private final class TimeCounter {
151         private long beginningOfTime;
152         private long delta;
153         private int marksCount = 0;
154
155         public void markStart() {
156             beginningOfTime = System.nanoTime();
157             delta = 0;
158             marksCount = 0;
159         }
160
161         public void addTimeMark() {
162             delta += System.nanoTime() - beginningOfTime;
163             marksCount++;
164         }
165
166         public long getAverageTimeBetweenMarks() {
167             long average = 0;
168             if (marksCount > 0) {
169                 average = delta / marksCount;
170             }
171             return TimeUnit.NANOSECONDS.toMillis(average);
172         }
173
174     }
175 }