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.ExecutionException;
22 import java.util.concurrent.Future;
23 import java.util.concurrent.Semaphore;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
26 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
27 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
28 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
30 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
31 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
32 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
33 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
40 import org.opendaylight.yangtools.yang.common.RpcError;
41 import org.opendaylight.yangtools.yang.common.RpcResult;
42 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * Created by Martin Bobak <mbobak@cisco.com> on 1.4.2015.
49 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
51 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
52 private final RpcProviderRegistry rpcProviderRegistry;
54 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
56 private HashedWheelTimer hashedWheelTimer;
58 private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
60 private static final long basicTimerDelay = 3000;
61 private static long currentTimerDelay = basicTimerDelay;
62 private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
64 private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
65 private Semaphore workModeGuard = new Semaphore(1, true);
66 private boolean shuttingDownStatisticsPolling;
67 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
70 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
71 deviceInitPhaseHandler = handler;
74 public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry) {
75 this.rpcProviderRegistry = rpcProviderRegistry;
76 controlServiceRegistration = rpcProviderRegistry.addRpcImplementation(StatisticsManagerControlService.class, this);
79 public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry, final boolean shuttingDownStatisticsPolling) {
80 this(rpcProviderRegistry);
81 this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
85 public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
86 LOG.debug("Node:{}, deviceContext.getDeviceState().getRole():{}", deviceContext.getDeviceState().getNodeId(),
87 deviceContext.getDeviceState().getRole());
88 if (deviceContext.getDeviceState().getRole() == OfpRole.BECOMESLAVE) {
89 // if slave, we dont poll for statistics and jump to rpc initialization
90 LOG.info("Skipping Statistics for slave role for node:{}", deviceContext.getDeviceState().getNodeId());
91 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
95 if (null == hashedWheelTimer) {
96 LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
97 hashedWheelTimer = deviceContext.getTimer();
100 LOG.info("Starting Statistics for master role for node:{}", deviceContext.getDeviceState().getNodeId());
102 final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
103 deviceContext.addDeviceContextClosedHandler(this);
104 final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
105 Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
107 public void onSuccess(final Boolean statisticsGathered) {
108 if (statisticsGathered) {
109 //there are some statistics on device worth gathering
110 contexts.put(deviceContext, statisticsContext);
111 final TimeCounter timeCounter = new TimeCounter();
112 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
113 LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
114 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
115 deviceContext.getDeviceState().setDeviceSynchronized(true);
117 final String deviceAdress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress().toString();
119 deviceContext.close();
120 } catch (Exception e) {
121 LOG.info("Statistics for device {} could not be gathered. Closing its device context.", deviceAdress);
127 public void onFailure(final Throwable throwable) {
128 LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
130 deviceContext.close();
131 } catch (Exception e) {
132 LOG.warn("Error closing device context.", e);
138 private void pollStatistics(final DeviceContext deviceContext,
139 final StatisticsContext statisticsContext,
140 final TimeCounter timeCounter) {
141 LOG.debug("POLLING ALL STATS for device: {}", deviceContext.getDeviceState().getNodeId().getValue());
142 timeCounter.markStart();
143 ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
144 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
146 public void onSuccess(final Boolean o) {
147 timeCounter.addTimeMark();
148 calculateTimerDelay(timeCounter);
149 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
153 public void onFailure(final Throwable throwable) {
154 timeCounter.addTimeMark();
155 LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
156 LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
157 calculateTimerDelay(timeCounter);
158 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
162 final long STATS_TIMEOUT_SEC = 20L;
164 deviceStatisticsCollectionFuture.get(STATS_TIMEOUT_SEC, TimeUnit.SECONDS);
165 } catch (InterruptedException | ExecutionException e) {
166 LOG.warn("Statistics collection for node {} failed", deviceContext.getDeviceState().getNodeId(), e);
167 } catch (TimeoutException e) {
168 LOG.info("Statistics collection for node {} still in progress even after {} secs", deviceContext.getDeviceState().getNodeId(), STATS_TIMEOUT_SEC);
172 private void scheduleNextPolling(final DeviceContext deviceContext,
173 final StatisticsContext statisticsContext,
174 final TimeCounter timeCounter) {
175 if (null != hashedWheelTimer) {
176 LOG.debug("SCHEDULING NEXT STATS POLLING for device: {}", deviceContext.getDeviceState().getNodeId().getValue());
177 if (!shuttingDownStatisticsPolling) {
178 Timeout pollTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
180 public void run(final Timeout timeout) throws Exception {
181 pollStatistics(deviceContext, statisticsContext, timeCounter);
183 }, currentTimerDelay, TimeUnit.MILLISECONDS);
184 statisticsContext.setPollTimeout(pollTimeout);
187 LOG.debug("#!NOT SCHEDULING NEXT STATS POLLING for device: {}", deviceContext.getDeviceState().getNodeId().getValue());
192 protected void calculateTimerDelay(final TimeCounter timeCounter) {
193 long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
194 if (averageStatisticsGatheringTime > currentTimerDelay) {
195 currentTimerDelay *= 2;
196 if (currentTimerDelay > maximumTimerDelay) {
197 currentTimerDelay = maximumTimerDelay;
200 if (currentTimerDelay > basicTimerDelay) {
201 currentTimerDelay /= 2;
203 currentTimerDelay = basicTimerDelay;
209 protected static long getCurrentTimerDelay() {
210 return currentTimerDelay;
214 public void onDeviceContextClosed(final DeviceContext deviceContext) {
215 StatisticsContext statisticsContext = contexts.remove(deviceContext);
216 if (null != statisticsContext) {
217 LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
219 statisticsContext.close();
220 } catch (Exception e) {
221 LOG.debug("Error closing statistic context for node {}.", deviceContext.getDeviceState().getNodeId());
227 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
228 GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
229 smModeOutputBld.setMode(workMode);
230 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
234 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
235 final Future<RpcResult<Void>> result;
236 // acquire exclusive access
237 if (workModeGuard.tryAcquire()) {
238 final StatisticsWorkMode targetWorkMode = input.getMode();
239 if (!workMode.equals(targetWorkMode)) {
240 shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
241 // iterate through stats-ctx: propagate mode
242 for (Map.Entry<DeviceContext, StatisticsContext> contextEntry : contexts.entrySet()) {
243 final DeviceContext deviceContext = contextEntry.getKey();
244 final StatisticsContext statisticsContext = contextEntry.getValue();
245 switch (targetWorkMode) {
247 scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
248 for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
249 lifeCycleSource.setItemLifecycleListener(null);
253 final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
254 if (pollTimeout.isPresent()) {
255 pollTimeout.get().cancel();
257 for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
258 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
262 LOG.warn("statistics work mode not supported: {}", targetWorkMode);
265 workMode = targetWorkMode;
267 workModeGuard.release();
268 result = RpcResultBuilder.<Void>success().buildFuture();
270 result = RpcResultBuilder.<Void>failed()
271 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
278 public void close() {
279 if (controlServiceRegistration != null) {
280 controlServiceRegistration.close();
281 controlServiceRegistration = null;