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.Preconditions;
13 import com.google.common.collect.Iterators;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import io.netty.util.HashedWheelTimer;
18 import io.netty.util.Timeout;
19 import io.netty.util.TimerTask;
20 import java.util.Iterator;
22 import java.util.concurrent.CancellationException;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.ConcurrentMap;
25 import java.util.concurrent.Future;
26 import java.util.concurrent.Semaphore;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
30 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
31 import org.opendaylight.openflowplugin.api.ConnectionException;
32 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
33 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
34 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
35 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
36 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
37 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
38 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
39 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProviderFactory;
40 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.multipart.types.rev170112.MultipartReply;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfig;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
48 import org.opendaylight.yangtools.yang.common.RpcError;
49 import org.opendaylight.yangtools.yang.common.RpcResult;
50 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
56 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
58 private static final long DEFAULT_STATS_TIMEOUT_SEC = 50L;
60 private final OpenflowProviderConfig config;
61 private final ConvertorExecutor converterExecutor;
63 private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
65 private long currentTimerDelay;
66 private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
67 private final Semaphore workModeGuard = new Semaphore(1, true);
68 private boolean isStatisticsPollingOn;
69 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
71 private final HashedWheelTimer hashedWheelTimer;
73 public StatisticsManagerImpl(@Nonnull final OpenflowProviderConfig config,
74 @Nonnull final RpcProviderRegistry rpcProviderRegistry,
75 final HashedWheelTimer hashedWheelTimer,
76 final ConvertorExecutor convertorExecutor) {
78 currentTimerDelay = config.getBasicTimerDelay().getValue();
79 this.converterExecutor = convertorExecutor;
80 this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry
81 .addRpcImplementation(StatisticsManagerControlService.class, this));
83 this.hashedWheelTimer = hashedWheelTimer;
87 void pollStatistics(final DeviceState deviceState,
88 final StatisticsContext statisticsContext,
89 final TimeCounter timeCounter,
90 final DeviceInfo deviceInfo) {
92 if (!statisticsContext.isSchedulingEnabled()) {
93 if (LOG.isDebugEnabled()) {
94 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
99 if (LOG.isDebugEnabled()) {
100 LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
103 timeCounter.markStart();
104 final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
105 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
107 public void onSuccess(final Boolean o) {
108 timeCounter.addTimeMark();
109 calculateTimerDelay(timeCounter);
110 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
114 public void onFailure(@Nonnull final Throwable throwable) {
115 timeCounter.addTimeMark();
116 calculateTimerDelay(timeCounter);
118 if (throwable instanceof ConnectionException) {
119 // ConnectionException is raised by StatisticsContextImpl class when the connections
120 // move to RIP state. In this particular case, there is no need to reschedule
121 // because this statistics manager should be closed soon
122 LOG.warn("Device {} is no more connected, stopping the statistics collection",
123 deviceInfo.getLOGValue(),throwable);
124 stopScheduling(deviceInfo);
125 } else if (throwable instanceof CancellationException) {
126 LOG.info("Statistics gathering for device {} was cancelled.",
127 deviceInfo.getLOGValue());
129 LOG.warn("Unexpected error occurred during statistics collection for device {}, rescheduling " +
130 "statistics collections", deviceInfo.getLOGValue(), throwable);
132 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
137 final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
138 final long statsTimeoutSec = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
139 final TimerTask timerTask = timeout -> {
140 if (!deviceStatisticsCollectionFuture.isDone()) {
141 LOG.info("Statistics collection for node {} still in progress even after {} secs", deviceInfo.getLOGValue(), statsTimeoutSec);
142 deviceStatisticsCollectionFuture.cancel(true);
146 hashedWheelTimer.newTimeout(timerTask, statsTimeoutSec, TimeUnit.SECONDS);
149 private void scheduleNextPolling(final DeviceState deviceState,
150 final DeviceInfo deviceInfo,
151 final StatisticsContext statisticsContext,
152 final TimeCounter timeCounter) {
153 if (LOG.isDebugEnabled()) {
154 LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceInfo.getNodeId());
157 if (isStatisticsPollingOn) {
158 final Timeout pollTimeout = hashedWheelTimer.newTimeout(
159 timeout -> pollStatistics(
165 TimeUnit.MILLISECONDS);
167 statisticsContext.setPollTimeout(pollTimeout);
172 void calculateTimerDelay(final TimeCounter timeCounter) {
173 final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
174 if (averageStatisticsGatheringTime > currentTimerDelay) {
175 currentTimerDelay *= 2;
176 if (currentTimerDelay > config.getMaximumTimerDelay().getValue()) {
177 currentTimerDelay = config.getMaximumTimerDelay().getValue();
180 if (currentTimerDelay > config.getBasicTimerDelay().getValue()) {
181 currentTimerDelay /= 2;
183 currentTimerDelay = config.getBasicTimerDelay().getValue();
189 long getCurrentTimerDelay() {
190 return currentTimerDelay;
194 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
195 final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
196 smModeOutputBld.setMode(workMode);
197 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
201 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
202 final Future<RpcResult<Void>> result;
203 // acquire exclusive access
204 if (workModeGuard.tryAcquire()) {
205 final StatisticsWorkMode targetWorkMode = input.getMode();
206 if (!workMode.equals(targetWorkMode)) {
207 isStatisticsPollingOn = !(StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode));
208 // iterate through stats-ctx: propagate mode
209 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
210 final DeviceInfo deviceInfo = entry.getKey();
211 final StatisticsContext statisticsContext = entry.getValue();
212 final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
213 switch (targetWorkMode) {
215 scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
216 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
217 lifeCycleSource.setItemLifecycleListener(null);
221 statisticsContext.stopGatheringData();
222 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
223 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
227 LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
230 workMode = targetWorkMode;
232 workModeGuard.release();
233 result = RpcResultBuilder.<Void>success().buildFuture();
235 result = RpcResultBuilder.<Void>failed()
236 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
243 public void startScheduling(final DeviceInfo deviceInfo) {
244 if (!isStatisticsPollingOn) {
245 LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
249 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
251 if (statisticsContext == null) {
252 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
256 if (statisticsContext.isSchedulingEnabled()) {
257 LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
261 LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
263 statisticsContext.setSchedulingEnabled(true);
265 statisticsContext.gainDeviceState(),
273 public void stopScheduling(final DeviceInfo deviceInfo) {
274 if (LOG.isDebugEnabled()) {
275 LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
278 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
280 if (statisticsContext == null) {
281 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
285 statisticsContext.setSchedulingEnabled(false);
289 public void close() {
290 if (controlServiceRegistration != null) {
291 controlServiceRegistration.close();
292 controlServiceRegistration = null;
295 for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
296 iterator.hasNext();) {
297 iterator.next().close();
302 public StatisticsContext createContext(@Nonnull final DeviceContext deviceContext) {
304 final MultipartWriterProvider statisticsWriterProvider = MultipartWriterProviderFactory
305 .createDefaultProvider(deviceContext);
307 final StatisticsContext statisticsContext =
308 deviceContext.canUseSingleLayerSerialization() ?
309 new StatisticsContextImpl<MultipartReply>(
310 isStatisticsPollingOn,
314 statisticsWriterProvider) :
315 new StatisticsContextImpl<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
317 isStatisticsPollingOn,
321 statisticsWriterProvider);
322 contexts.putIfAbsent(deviceContext.getDeviceInfo(), statisticsContext);
324 return statisticsContext;
328 public void onDeviceRemoved(final DeviceInfo deviceInfo) {
329 contexts.remove(deviceInfo);
330 if (LOG.isDebugEnabled()) {
331 LOG.debug("Statistics context removed for node {}", deviceInfo.getLOGValue());