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.base.Preconditions;
14 import com.google.common.base.Verify;
15 import com.google.common.collect.Iterators;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import io.netty.util.Timeout;
20 import io.netty.util.TimerTask;
21 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
22 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
23 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
24 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
25 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
26 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
27 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
28 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
29 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
30 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
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;
43 import javax.annotation.CheckForNull;
44 import javax.annotation.Nonnull;
45 import java.util.Iterator;
46 import java.util.concurrent.CancellationException;
47 import java.util.concurrent.ConcurrentHashMap;
48 import java.util.concurrent.ConcurrentMap;
49 import java.util.concurrent.Future;
50 import java.util.concurrent.Semaphore;
51 import java.util.concurrent.TimeUnit;
53 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
55 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
57 private static final long DEFAULT_STATS_TIMEOUT_SEC = 50L;
59 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
60 private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
62 private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
64 private static final long basicTimerDelay = 3000;
65 private static long currentTimerDelay = basicTimerDelay;
66 private static final long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
68 private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
69 private final Semaphore workModeGuard = new Semaphore(1, true);
70 private boolean shuttingDownStatisticsPolling;
71 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
73 private final LifecycleConductor conductor;
76 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
77 deviceInitPhaseHandler = handler;
80 public StatisticsManagerImpl(@CheckForNull final RpcProviderRegistry rpcProviderRegistry,
81 final boolean shuttingDownStatisticsPolling,
82 final LifecycleConductor lifecycleConductor) {
83 Preconditions.checkArgument(rpcProviderRegistry != null);
84 this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry.addRpcImplementation(
85 StatisticsManagerControlService.class, this));
86 this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
87 this.conductor = lifecycleConductor;
91 public void onDeviceContextLevelUp(final DeviceInfo deviceInfo) throws Exception {
93 final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(deviceInfo));
95 final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceInfo, shuttingDownStatisticsPolling, conductor);
96 Verify.verify(contexts.putIfAbsent(deviceInfo, statisticsContext) == null, "StatisticsCtx still not closed for Node {}", deviceInfo.getNodeId());
98 deviceContext.getDeviceState().setDeviceSynchronized(true);
99 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceInfo);
103 void pollStatistics(final DeviceContext deviceContext,
104 final StatisticsContext statisticsContext,
105 final TimeCounter timeCounter) {
107 final NodeId nodeId = deviceContext.getDeviceInfo().getNodeId();
109 if (!statisticsContext.isSchedulingEnabled()) {
110 LOG.debug("Disabling statistics scheduling for device: {}", nodeId);
114 if (!deviceContext.getDeviceState().isValid()) {
115 LOG.debug("Session is not valid for device: {}", nodeId);
119 if (!deviceContext.getDeviceState().isStatisticsPollingEnabled()) {
120 LOG.debug("Statistics polling is currently disabled for device: {}", nodeId);
121 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
125 LOG.debug("POLLING ALL STATISTICS for device: {}", nodeId);
126 timeCounter.markStart();
127 final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
128 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
130 public void onSuccess(final Boolean o) {
131 timeCounter.addTimeMark();
132 calculateTimerDelay(timeCounter);
133 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
137 public void onFailure(@Nonnull final Throwable throwable) {
138 timeCounter.addTimeMark();
139 LOG.warn("Statistics gathering for single node was not successful: {}", throwable.getMessage());
140 LOG.trace("Statistics gathering for single node was not successful.. ", throwable);
141 calculateTimerDelay(timeCounter);
142 if (throwable instanceof CancellationException) {
143 /** This often happens when something wrong with akka or DS, so closing connection will help to restart device **/
144 conductor.closeConnection(deviceContext.getDeviceInfo());
146 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
151 final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
152 final long STATS_TIMEOUT_SEC = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
153 final TimerTask timerTask = timeout -> {
154 if (!deviceStatisticsCollectionFuture.isDone()) {
155 LOG.info("Statistics collection for node {} still in progress even after {} secs", nodeId, STATS_TIMEOUT_SEC);
156 deviceStatisticsCollectionFuture.cancel(true);
160 conductor.newTimeout(timerTask, STATS_TIMEOUT_SEC, TimeUnit.SECONDS);
163 private void scheduleNextPolling(final DeviceContext deviceContext,
164 final StatisticsContext statisticsContext,
165 final TimeCounter timeCounter) {
166 LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceContext.getDeviceInfo().getNodeId());
167 if (!shuttingDownStatisticsPolling) {
168 final Timeout pollTimeout = conductor.newTimeout(timeout -> pollStatistics(deviceContext, statisticsContext, timeCounter), currentTimerDelay, TimeUnit.MILLISECONDS);
169 statisticsContext.setPollTimeout(pollTimeout);
174 void calculateTimerDelay(final TimeCounter timeCounter) {
175 final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
176 if (averageStatisticsGatheringTime > currentTimerDelay) {
177 currentTimerDelay *= 2;
178 if (currentTimerDelay > maximumTimerDelay) {
179 currentTimerDelay = maximumTimerDelay;
182 if (currentTimerDelay > basicTimerDelay) {
183 currentTimerDelay /= 2;
185 currentTimerDelay = basicTimerDelay;
191 static long getCurrentTimerDelay() {
192 return currentTimerDelay;
196 public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
197 final StatisticsContext statisticsContext = contexts.remove(deviceInfo);
198 if (null != statisticsContext) {
199 LOG.trace("Removing device context from stack. No more statistics gathering for device: {}", deviceInfo.getNodeId());
200 statisticsContext.close();
202 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
206 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
207 final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
208 smModeOutputBld.setMode(workMode);
209 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
213 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
214 final Future<RpcResult<Void>> result;
215 // acquire exclusive access
216 if (workModeGuard.tryAcquire()) {
217 final StatisticsWorkMode targetWorkMode = input.getMode();
218 if (!workMode.equals(targetWorkMode)) {
219 shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
220 // iterate through stats-ctx: propagate mode
221 for (final StatisticsContext statisticsContext : contexts.values()) {
222 final DeviceContext deviceContext = statisticsContext.getDeviceContext();
223 switch (targetWorkMode) {
225 scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
226 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
227 lifeCycleSource.setItemLifecycleListener(null);
231 final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
232 if (pollTimeout.isPresent()) {
233 pollTimeout.get().cancel();
235 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
236 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
240 LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
243 workMode = targetWorkMode;
245 workModeGuard.release();
246 result = RpcResultBuilder.<Void>success().buildFuture();
248 result = RpcResultBuilder.<Void>failed()
249 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
256 public void startScheduling(final DeviceInfo deviceInfo) {
257 if (shuttingDownStatisticsPolling) {
258 LOG.info("Statistics are shut down for device: {}", deviceInfo.getNodeId());
262 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
264 if (statisticsContext == null) {
265 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
269 if (statisticsContext.isSchedulingEnabled()) {
270 LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
274 LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
275 final DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
277 if (deviceContext == null) {
278 LOG.warn("Device context not found for device: {}", deviceInfo.getNodeId());
282 statisticsContext.setSchedulingEnabled(true);
283 scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
287 public void stopScheduling(final DeviceInfo deviceInfo) {
288 LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
289 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
291 if (statisticsContext == null) {
292 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
296 statisticsContext.setSchedulingEnabled(false);
300 public void close() {
301 if (controlServiceRegistration != null) {
302 controlServiceRegistration.close();
303 controlServiceRegistration = null;
305 for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
306 iterator.hasNext();) {
307 iterator.next().close();
312 public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
313 this.deviceTerminPhaseHandler = handler;