2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.impl.statistics;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import io.netty.util.HashedWheelTimer;
17 import io.netty.util.Timeout;
18 import io.netty.util.TimerTask;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.Future;
22 import java.util.concurrent.Semaphore;
23 import java.util.concurrent.TimeUnit;
24 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
25 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
26 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
27 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
28 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
29 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
30 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
31 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
37 import org.opendaylight.yangtools.yang.common.RpcError;
38 import org.opendaylight.yangtools.yang.common.RpcResult;
39 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * Created by Martin Bobak <mbobak@cisco.com> on 1.4.2015.
46 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
48 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
49 private final RpcProviderRegistry rpcProviderRegistry;
51 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
53 private HashedWheelTimer hashedWheelTimer;
55 private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
57 private static final long basicTimerDelay = 3000;
58 private static long currentTimerDelay = basicTimerDelay;
59 private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
61 private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
62 private Semaphore workModeGuard = new Semaphore(1, true);
63 private boolean shuttingDownStatisticsPolling;
64 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
67 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
68 deviceInitPhaseHandler = handler;
71 public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry) {
72 this.rpcProviderRegistry = rpcProviderRegistry;
73 controlServiceRegistration = rpcProviderRegistry.addRpcImplementation(StatisticsManagerControlService.class, this);
76 public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry, final boolean shuttingDownStatisticsPolling) {
77 this(rpcProviderRegistry);
78 this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
82 public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
84 if (null == hashedWheelTimer) {
85 LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
86 hashedWheelTimer = deviceContext.getTimer();
89 final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
90 deviceContext.addDeviceContextClosedHandler(this);
91 final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
92 Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
94 public void onSuccess(final Boolean statisticsGathered) {
95 if (statisticsGathered) {
96 //there are some statistics on device worth gathering
97 contexts.put(deviceContext, statisticsContext);
98 final TimeCounter timeCounter = new TimeCounter();
99 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
100 LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
101 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
102 deviceContext.getDeviceState().setDeviceSynchronized(true);
104 final String deviceAdress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress().toString();
106 deviceContext.close();
107 } catch (Exception e) {
108 LOG.info("Statistics for device {} could not be gathered. Closing its device context.", deviceAdress);
114 public void onFailure(final Throwable throwable) {
115 LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
117 deviceContext.close();
118 } catch (Exception e) {
119 LOG.warn("Error closing device context.", e);
125 private void pollStatistics(final DeviceContext deviceContext,
126 final StatisticsContext statisticsContext,
127 final TimeCounter timeCounter) {
128 timeCounter.markStart();
129 ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
130 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
132 public void onSuccess(final Boolean o) {
133 timeCounter.addTimeMark();
134 calculateTimerDelay(timeCounter);
135 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
139 public void onFailure(final Throwable throwable) {
140 timeCounter.addTimeMark();
141 LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
142 LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
143 if (ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
144 calculateTimerDelay(timeCounter);
145 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
151 private void scheduleNextPolling(final DeviceContext deviceContext,
152 final StatisticsContext statisticsContext,
153 final TimeCounter timeCounter) {
154 if (null != hashedWheelTimer) {
155 if (!shuttingDownStatisticsPolling) {
156 Timeout pollTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
158 public void run(final Timeout timeout) throws Exception {
159 pollStatistics(deviceContext, statisticsContext, timeCounter);
161 }, currentTimerDelay, TimeUnit.MILLISECONDS);
162 statisticsContext.setPollTimeout(pollTimeout);
168 protected void calculateTimerDelay(final TimeCounter timeCounter) {
169 // TODO: move into TimeCounter
170 long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
171 if (averageStatisticsGatheringTime > currentTimerDelay) {
172 currentTimerDelay *= 2;
173 if (currentTimerDelay > maximumTimerDelay) {
174 currentTimerDelay = maximumTimerDelay;
177 if (currentTimerDelay > basicTimerDelay) {
178 currentTimerDelay /= 2;
180 currentTimerDelay = basicTimerDelay;
186 protected static long getCurrentTimerDelay() {
187 return currentTimerDelay;
191 public void onDeviceContextClosed(final DeviceContext deviceContext) {
192 StatisticsContext statisticsContext = contexts.remove(deviceContext);
193 if (null != statisticsContext) {
194 LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
196 statisticsContext.close();
197 } catch (Exception e) {
198 LOG.debug("Error closing statistic context for node {}.", deviceContext.getDeviceState().getNodeId());
204 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
205 GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
206 smModeOutputBld.setMode(workMode);
207 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
211 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
212 final Future<RpcResult<Void>> result;
213 // acquire exclusive access
214 if (workModeGuard.tryAcquire()) {
215 final StatisticsWorkMode targetWorkMode = input.getMode();
216 if (!workMode.equals(targetWorkMode)) {
217 shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
218 // iterate through stats-ctx: propagate mode
219 for (Map.Entry<DeviceContext, StatisticsContext> contextEntry : contexts.entrySet()) {
220 final DeviceContext deviceContext = contextEntry.getKey();
221 final StatisticsContext statisticsContext = contextEntry.getValue();
222 switch (targetWorkMode) {
224 scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
225 for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
226 lifeCycleSource.setItemLifecycleListener(null);
230 final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
231 if (pollTimeout.isPresent()) {
232 pollTimeout.get().cancel();
234 for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
235 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
239 LOG.warn("statistics work mode not supported: {}", targetWorkMode);
242 workMode = targetWorkMode;
244 workModeGuard.release();
245 result = RpcResultBuilder.<Void>success().buildFuture();
247 result = RpcResultBuilder.<Void>failed()
248 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
255 public void close() {
256 if (controlServiceRegistration != null) {
257 controlServiceRegistration.close();
258 controlServiceRegistration = null;