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 BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
69 private final HashedWheelTimer hashedWheelTimer;
70 private boolean istStatisticsFullyDisabled;
72 public StatisticsManagerImpl(@Nonnull final OpenflowProviderConfig config,
73 @Nonnull final RpcProviderRegistry rpcProviderRegistry,
74 final HashedWheelTimer hashedWheelTimer,
75 final ConvertorExecutor convertorExecutor) {
77 currentTimerDelay = config.getBasicTimerDelay().getValue();
78 this.converterExecutor = convertorExecutor;
79 this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry
80 .addRpcImplementation(StatisticsManagerControlService.class, this));
82 this.hashedWheelTimer = hashedWheelTimer;
86 void pollStatistics(final DeviceState deviceState,
87 final StatisticsContext statisticsContext,
88 final TimeCounter timeCounter,
89 final DeviceInfo deviceInfo) {
91 if (!statisticsContext.isSchedulingEnabled()) {
92 if (LOG.isDebugEnabled()) {
93 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
98 if (LOG.isDebugEnabled()) {
99 LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
102 timeCounter.markStart();
103 final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
104 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
106 public void onSuccess(final Boolean o) {
107 timeCounter.addTimeMark();
108 calculateTimerDelay(timeCounter);
109 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
113 public void onFailure(@Nonnull final Throwable throwable) {
114 timeCounter.addTimeMark();
115 calculateTimerDelay(timeCounter);
117 if (throwable instanceof ConnectionException) {
118 // ConnectionException is raised by StatisticsContextImpl class when the connections
119 // move to RIP state. In this particular case, there is no need to reschedule
120 // because this statistics manager should be closed soon
121 LOG.warn("Device {} is no more connected, stopping the statistics collection",
122 deviceInfo.getLOGValue(),throwable);
123 stopScheduling(deviceInfo);
124 } else if (throwable instanceof CancellationException) {
125 LOG.info("Statistics gathering for device {} was cancelled.",
126 deviceInfo.getLOGValue());
128 LOG.warn("Unexpected error occurred during statistics collection for device {}, rescheduling " +
129 "statistics collections", deviceInfo.getLOGValue(), throwable);
131 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
136 final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
137 final long statsTimeoutSec = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
138 final TimerTask timerTask = timeout -> {
139 if (!deviceStatisticsCollectionFuture.isDone()) {
140 LOG.info("Statistics collection for node {} still in progress even after {} secs", deviceInfo.getLOGValue(), statsTimeoutSec);
141 deviceStatisticsCollectionFuture.cancel(true);
145 hashedWheelTimer.newTimeout(timerTask, statsTimeoutSec, TimeUnit.SECONDS);
148 private void scheduleNextPolling(final DeviceState deviceState,
149 final DeviceInfo deviceInfo,
150 final StatisticsContext statisticsContext,
151 final TimeCounter timeCounter) {
152 if (LOG.isDebugEnabled()) {
153 LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceInfo.getNodeId());
156 if (isStatisticsEnabled()) {
157 final Timeout pollTimeout = hashedWheelTimer.newTimeout(
158 timeout -> pollStatistics(
164 TimeUnit.MILLISECONDS);
166 statisticsContext.setPollTimeout(pollTimeout);
170 private boolean isStatisticsEnabled() {
171 return !istStatisticsFullyDisabled && config.isIsStatisticsPollingOn();
175 void calculateTimerDelay(final TimeCounter timeCounter) {
176 final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
177 if (averageStatisticsGatheringTime > currentTimerDelay) {
178 currentTimerDelay *= 2;
179 if (currentTimerDelay > config.getMaximumTimerDelay().getValue()) {
180 currentTimerDelay = config.getMaximumTimerDelay().getValue();
183 if (currentTimerDelay > config.getBasicTimerDelay().getValue()) {
184 currentTimerDelay /= 2;
186 currentTimerDelay = config.getBasicTimerDelay().getValue();
192 long getCurrentTimerDelay() {
193 return currentTimerDelay;
197 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
198 final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
199 smModeOutputBld.setMode(workMode);
200 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
204 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
205 final Future<RpcResult<Void>> result;
206 // acquire exclusive access
207 if (workModeGuard.tryAcquire()) {
208 final StatisticsWorkMode targetWorkMode = input.getMode();
209 if (!workMode.equals(targetWorkMode)) {
210 istStatisticsFullyDisabled = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
212 // iterate through stats-ctx: propagate mode
213 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
214 final DeviceInfo deviceInfo = entry.getKey();
215 final StatisticsContext statisticsContext = entry.getValue();
216 final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
217 switch (targetWorkMode) {
219 scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
220 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
221 lifeCycleSource.setItemLifecycleListener(null);
225 statisticsContext.stopGatheringData();
226 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
227 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
231 LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
234 workMode = targetWorkMode;
236 workModeGuard.release();
237 result = RpcResultBuilder.<Void>success().buildFuture();
239 result = RpcResultBuilder.<Void>failed()
240 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
247 public void startScheduling(final DeviceInfo deviceInfo) {
248 if (!isStatisticsEnabled()) {
249 LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
253 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
255 if (statisticsContext == null) {
256 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
260 if (statisticsContext.isSchedulingEnabled()) {
261 LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
265 LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
267 statisticsContext.setSchedulingEnabled(true);
269 statisticsContext.gainDeviceState(),
277 public void stopScheduling(final DeviceInfo deviceInfo) {
278 if (LOG.isDebugEnabled()) {
279 LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
282 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
284 if (statisticsContext == null) {
285 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
289 statisticsContext.setSchedulingEnabled(false);
293 public void close() {
294 istStatisticsFullyDisabled = true;
296 if (controlServiceRegistration != null) {
297 controlServiceRegistration.close();
298 controlServiceRegistration = null;
301 for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
302 iterator.hasNext();) {
303 iterator.next().close();
308 public StatisticsContext createContext(@Nonnull final DeviceContext deviceContext) {
310 final MultipartWriterProvider statisticsWriterProvider = MultipartWriterProviderFactory
311 .createDefaultProvider(deviceContext);
313 final StatisticsContext statisticsContext =
314 deviceContext.canUseSingleLayerSerialization() ?
315 new StatisticsContextImpl<MultipartReply>(
316 isStatisticsEnabled(),
320 statisticsWriterProvider) :
321 new StatisticsContextImpl<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
323 isStatisticsEnabled(),
327 statisticsWriterProvider);
328 contexts.putIfAbsent(deviceContext.getDeviceInfo(), statisticsContext);
330 return statisticsContext;
334 public void onDeviceRemoved(final DeviceInfo deviceInfo) {
335 contexts.remove(deviceInfo);
336 if (LOG.isDebugEnabled()) {
337 LOG.debug("Statistics context removed for node {}", deviceInfo.getLOGValue());