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.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
47 import org.opendaylight.yangtools.yang.common.RpcError;
48 import org.opendaylight.yangtools.yang.common.RpcResult;
49 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
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;
58 private final ConvertorExecutor converterExecutor;
60 private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
62 private long basicTimerDelay;
63 private long currentTimerDelay;
64 private long maximumTimerDelay; //wait time for next statistics
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 RpcProviderRegistry rpcProviderRegistry,
74 final HashedWheelTimer hashedWheelTimer,
75 final ConvertorExecutor convertorExecutor) {
76 this.converterExecutor = convertorExecutor;
77 this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry
78 .addRpcImplementation(StatisticsManagerControlService.class, this));
80 this.hashedWheelTimer = hashedWheelTimer;
84 void pollStatistics(final DeviceState deviceState,
85 final StatisticsContext statisticsContext,
86 final TimeCounter timeCounter,
87 final DeviceInfo deviceInfo) {
89 if (!statisticsContext.isSchedulingEnabled()) {
90 if (LOG.isDebugEnabled()) {
91 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
96 if (LOG.isDebugEnabled()) {
97 LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
100 timeCounter.markStart();
101 final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
102 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
104 public void onSuccess(final Boolean o) {
105 timeCounter.addTimeMark();
106 calculateTimerDelay(timeCounter);
107 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
111 public void onFailure(@Nonnull final Throwable throwable) {
112 timeCounter.addTimeMark();
113 LOG.warn("Statistics gathering for single node {} was not successful: {}", deviceInfo.getLOGValue(),
114 throwable.getMessage());
115 if (LOG.isTraceEnabled()) {
116 LOG.trace("Gathering for node {} failure: ", deviceInfo.getLOGValue(), throwable);
118 calculateTimerDelay(timeCounter);
119 if (throwable instanceof ConnectionException) {
120 // ConnectionException is raised by StatisticsContextImpl class when the connections
121 // move to RIP state. In this particular case, there is no need to reschedule
122 // because this statistics manager should be closed soon
123 LOG.warn("Node {} is no more connected, stopping the statistics collection",
124 deviceInfo.getLOGValue(),throwable);
125 stopScheduling(deviceInfo);
127 if (!(throwable instanceof CancellationException)) {
128 LOG.warn("Unexpected error occurred during statistics collection for node {}, 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 (isStatisticsPollingOn) {
157 final Timeout pollTimeout = hashedWheelTimer.newTimeout(
158 timeout -> pollStatistics(
164 TimeUnit.MILLISECONDS);
166 statisticsContext.setPollTimeout(pollTimeout);
171 void calculateTimerDelay(final TimeCounter timeCounter) {
172 final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
173 if (averageStatisticsGatheringTime > currentTimerDelay) {
174 currentTimerDelay *= 2;
175 if (currentTimerDelay > maximumTimerDelay) {
176 currentTimerDelay = maximumTimerDelay;
179 if (currentTimerDelay > basicTimerDelay) {
180 currentTimerDelay /= 2;
182 currentTimerDelay = basicTimerDelay;
188 long getCurrentTimerDelay() {
189 return currentTimerDelay;
193 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
194 final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
195 smModeOutputBld.setMode(workMode);
196 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
200 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
201 final Future<RpcResult<Void>> result;
202 // acquire exclusive access
203 if (workModeGuard.tryAcquire()) {
204 final StatisticsWorkMode targetWorkMode = input.getMode();
205 if (!workMode.equals(targetWorkMode)) {
206 isStatisticsPollingOn = !(StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode));
207 // iterate through stats-ctx: propagate mode
208 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
209 final DeviceInfo deviceInfo = entry.getKey();
210 final StatisticsContext statisticsContext = entry.getValue();
211 final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
212 switch (targetWorkMode) {
214 scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
215 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
216 lifeCycleSource.setItemLifecycleListener(null);
220 statisticsContext.stopGatheringData();
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;