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.Optional;
23 import java.util.concurrent.CancellationException;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.Future;
27 import java.util.concurrent.Semaphore;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.Nonnull;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
31 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
32 import org.opendaylight.openflowplugin.api.ConnectionException;
33 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
34 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
35 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
36 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
37 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
38 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
39 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
40 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProviderFactory;
41 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.multipart.types.rev170112.MultipartReply;
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;
59 private final ConvertorExecutor converterExecutor;
61 private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
63 private long basicTimerDelay;
64 private long currentTimerDelay;
65 private long maximumTimerDelay; //wait time for next statistics
67 private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
68 private final Semaphore workModeGuard = new Semaphore(1, true);
69 private boolean isStatisticsPollingOn;
70 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
72 private final HashedWheelTimer hashedWheelTimer;
74 public StatisticsManagerImpl(@Nonnull final RpcProviderRegistry rpcProviderRegistry,
75 final HashedWheelTimer hashedWheelTimer,
76 final ConvertorExecutor convertorExecutor) {
77 this.converterExecutor = convertorExecutor;
78 this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry
79 .addRpcImplementation(StatisticsManagerControlService.class, this));
81 this.hashedWheelTimer = hashedWheelTimer;
85 void pollStatistics(final DeviceState deviceState,
86 final StatisticsContext statisticsContext,
87 final TimeCounter timeCounter,
88 final DeviceInfo deviceInfo) {
90 if (!statisticsContext.isSchedulingEnabled()) {
91 if (LOG.isDebugEnabled()) {
92 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
97 if (LOG.isDebugEnabled()) {
98 LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
101 timeCounter.markStart();
102 final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
103 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
105 public void onSuccess(final Boolean o) {
106 timeCounter.addTimeMark();
107 calculateTimerDelay(timeCounter);
108 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
112 public void onFailure(@Nonnull final Throwable throwable) {
113 timeCounter.addTimeMark();
114 LOG.warn("Statistics gathering for single node {} was not successful: {}", deviceInfo.getLOGValue(),
115 throwable.getMessage());
116 if (LOG.isTraceEnabled()) {
117 LOG.trace("Gathering for node {} failure: ", deviceInfo.getLOGValue(), throwable);
119 calculateTimerDelay(timeCounter);
120 if (throwable instanceof ConnectionException) {
121 // ConnectionException is raised by StatisticsContextImpl class when the connections
122 // move to RIP state. In this particular case, there is no need to reschedule
123 // because this statistics manager should be closed soon
124 LOG.warn("Node {} is no more connected, stopping the statistics collection",
125 deviceInfo.getLOGValue(),throwable);
126 stopScheduling(deviceInfo);
128 if (!(throwable instanceof CancellationException)) {
129 LOG.warn("Unexpected error occurred during statistics collection for node {}, 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());
156 if (isStatisticsPollingOn) {
157 final Timeout pollTimeout = hashedWheelTimer.newTimeout(
158 timeout -> pollStatistics(
164 TimeUnit.MILLISECONDS);
165 statisticsContext.setPollTimeout(pollTimeout);
170 void calculateTimerDelay(final TimeCounter timeCounter) {
171 final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
172 if (averageStatisticsGatheringTime > currentTimerDelay) {
173 currentTimerDelay *= 2;
174 if (currentTimerDelay > maximumTimerDelay) {
175 currentTimerDelay = maximumTimerDelay;
178 if (currentTimerDelay > basicTimerDelay) {
179 currentTimerDelay /= 2;
181 currentTimerDelay = basicTimerDelay;
187 long getCurrentTimerDelay() {
188 return currentTimerDelay;
192 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
193 final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
194 smModeOutputBld.setMode(workMode);
195 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
199 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
200 final Future<RpcResult<Void>> result;
201 // acquire exclusive access
202 if (workModeGuard.tryAcquire()) {
203 final StatisticsWorkMode targetWorkMode = input.getMode();
204 if (!workMode.equals(targetWorkMode)) {
205 isStatisticsPollingOn = !(StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode));
206 // iterate through stats-ctx: propagate mode
207 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
208 final DeviceInfo deviceInfo = entry.getKey();
209 final StatisticsContext statisticsContext = entry.getValue();
210 final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
211 switch (targetWorkMode) {
213 scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
214 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
215 lifeCycleSource.setItemLifecycleListener(null);
219 final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
220 pollTimeout.ifPresent(Timeout::cancel);
221 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
222 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
226 LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
229 workMode = targetWorkMode;
231 workModeGuard.release();
232 result = RpcResultBuilder.<Void>success().buildFuture();
234 result = RpcResultBuilder.<Void>failed()
235 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
242 public void startScheduling(final DeviceInfo deviceInfo) {
243 if (!isStatisticsPollingOn) {
244 LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
248 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
250 if (statisticsContext == null) {
251 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
255 if (statisticsContext.isSchedulingEnabled()) {
256 LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
260 LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
262 statisticsContext.setSchedulingEnabled(true);
264 statisticsContext.gainDeviceState(),
272 public void stopScheduling(final DeviceInfo deviceInfo) {
273 if (LOG.isDebugEnabled()) {
274 LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
277 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
279 if (statisticsContext == null) {
280 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
284 statisticsContext.setSchedulingEnabled(false);
288 public void close() {
289 if (controlServiceRegistration != null) {
290 controlServiceRegistration.close();
291 controlServiceRegistration = null;
294 for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
295 iterator.hasNext();) {
296 iterator.next().close();
301 public void setIsStatisticsPollingOn(boolean isStatisticsPollingOn){
302 this.isStatisticsPollingOn = isStatisticsPollingOn;
306 public StatisticsContext createContext(@Nonnull final DeviceContext deviceContext) {
308 final MultipartWriterProvider statisticsWriterProvider = MultipartWriterProviderFactory
309 .createDefaultProvider(deviceContext);
311 final StatisticsContext statisticsContext =
312 deviceContext.canUseSingleLayerSerialization() ?
313 new StatisticsContextImpl<MultipartReply>(
314 isStatisticsPollingOn,
318 statisticsWriterProvider) :
319 new StatisticsContextImpl<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
321 isStatisticsPollingOn,
325 statisticsWriterProvider);
326 contexts.putIfAbsent(deviceContext.getDeviceInfo(), statisticsContext);
328 return statisticsContext;
332 public void onDeviceRemoved(final DeviceInfo deviceInfo) {
333 contexts.remove(deviceInfo);
334 if (LOG.isDebugEnabled()) {
335 LOG.debug("Statistics context removed for node {}", deviceInfo.getLOGValue());
340 public void setBasicTimerDelay(final long basicTimerDelay) {
341 this.basicTimerDelay = basicTimerDelay;
342 this.currentTimerDelay = basicTimerDelay;
346 public void setMaximumTimerDelay(final long maximumTimerDelay) {
347 this.maximumTimerDelay = maximumTimerDelay;