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.base.Verify;
14 import com.google.common.collect.Iterators;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import java.util.Iterator;
20 import java.util.Optional;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23 import java.util.concurrent.Future;
24 import java.util.concurrent.Semaphore;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
28 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
29 import org.opendaylight.openflowplugin.api.ConnectionException;
30 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
31 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
32 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
33 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
34 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
35 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
36 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
37 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
38 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
39 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
40 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
46 import org.opendaylight.yangtools.yang.common.RpcError;
47 import org.opendaylight.yangtools.yang.common.RpcResult;
48 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import io.netty.util.HashedWheelTimer;
52 import io.netty.util.Timeout;
53 import io.netty.util.TimerTask;
55 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
57 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
59 private static final long DEFAULT_STATS_TIMEOUT_SEC = 50L;
60 private final ConvertorExecutor converterExecutor;
62 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
63 private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
65 private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
67 private static long basicTimerDelay;
68 private static long currentTimerDelay;
69 private static long maximumTimerDelay; //wait time for next statistics
71 private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
72 private final Semaphore workModeGuard = new Semaphore(1, true);
73 private boolean isStatisticsPollingOn;
74 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
76 private final HashedWheelTimer hashedWheelTimer;
79 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
80 deviceInitPhaseHandler = handler;
83 public StatisticsManagerImpl(final RpcProviderRegistry rpcProviderRegistry,
84 final boolean isStatisticsPollingOn,
85 final HashedWheelTimer hashedWheelTimer,
86 final ConvertorExecutor convertorExecutor,
87 final long basicTimerDelay,
88 final long maximumTimerDelay) {
89 Preconditions.checkArgument(rpcProviderRegistry != null);
90 this.converterExecutor = convertorExecutor;
91 this.controlServiceRegistration = Preconditions.checkNotNull(
92 rpcProviderRegistry.addRpcImplementation(StatisticsManagerControlService.class, this)
94 this.isStatisticsPollingOn = isStatisticsPollingOn;
95 this.basicTimerDelay = basicTimerDelay;
96 this.currentTimerDelay = basicTimerDelay;
97 this.maximumTimerDelay = maximumTimerDelay;
98 this.hashedWheelTimer = hashedWheelTimer;
102 public void onDeviceContextLevelUp(final DeviceInfo deviceInfo,
103 final LifecycleService lifecycleService) throws Exception {
105 final StatisticsContext statisticsContext =
106 new StatisticsContextImpl(
108 isStatisticsPollingOn,
114 contexts.putIfAbsent(deviceInfo, statisticsContext) == null,
115 "StatisticsCtx still not closed for Node {}", deviceInfo.getLOGValue()
118 lifecycleService.setStatContext(statisticsContext);
119 lifecycleService.registerDeviceRemovedHandler(this);
120 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceInfo, lifecycleService);
124 void pollStatistics(final DeviceState deviceState,
125 final StatisticsContext statisticsContext,
126 final TimeCounter timeCounter,
127 final DeviceInfo deviceInfo) {
129 if (!statisticsContext.isSchedulingEnabled()) {
130 if (LOG.isDebugEnabled()) {
131 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
136 if (LOG.isDebugEnabled()) {
137 LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
140 timeCounter.markStart();
141 final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
142 Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
144 public void onSuccess(final Boolean o) {
145 timeCounter.addTimeMark();
146 calculateTimerDelay(timeCounter);
147 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
151 public void onFailure(@Nonnull final Throwable throwable) {
152 timeCounter.addTimeMark();
153 LOG.warn("Statistics gathering for single node {} was not successful: {}", deviceInfo.getLOGValue(),
154 throwable.getMessage());
155 if (LOG.isTraceEnabled()) {
156 LOG.trace("Gathering for node {} failure: ", deviceInfo.getLOGValue(), throwable);
158 calculateTimerDelay(timeCounter);
159 if (throwable instanceof ConnectionException) {
160 // ConnectionException is raised by StatisticsContextImpl class when the connections
161 // move to RIP state. In this particular case, there is no need to reschedule
162 // because this statistics manager should be closed soon
163 LOG.warn("Node {} is no more connected, stopping the statistics collection",
164 deviceInfo.getLOGValue(),throwable);
165 stopScheduling(deviceInfo);
167 LOG.warn("Unexpected error occurred during statistics collection for node {}, rescheduling " +
168 "statistics collections", deviceInfo.getLOGValue(),throwable);
169 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
174 final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
175 final long statsTimeoutSec = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
176 final TimerTask timerTask = timeout -> {
177 if (!deviceStatisticsCollectionFuture.isDone()) {
178 LOG.info("Statistics collection for node {} still in progress even after {} secs", deviceInfo.getLOGValue(), statsTimeoutSec);
179 deviceStatisticsCollectionFuture.cancel(true);
183 hashedWheelTimer.newTimeout(timerTask, statsTimeoutSec, TimeUnit.SECONDS);
186 private void scheduleNextPolling(final DeviceState deviceState,
187 final DeviceInfo deviceInfo,
188 final StatisticsContext statisticsContext,
189 final TimeCounter timeCounter) {
190 if (LOG.isDebugEnabled()) {
191 LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceInfo.getNodeId());
193 if (isStatisticsPollingOn) {
194 final Timeout pollTimeout = hashedWheelTimer.newTimeout(
195 timeout -> pollStatistics(
201 TimeUnit.MILLISECONDS);
202 statisticsContext.setPollTimeout(pollTimeout);
207 void calculateTimerDelay(final TimeCounter timeCounter) {
208 final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
209 if (averageStatisticsGatheringTime > currentTimerDelay) {
210 currentTimerDelay *= 2;
211 if (currentTimerDelay > maximumTimerDelay) {
212 currentTimerDelay = maximumTimerDelay;
215 if (currentTimerDelay > basicTimerDelay) {
216 currentTimerDelay /= 2;
218 currentTimerDelay = basicTimerDelay;
224 static long getCurrentTimerDelay() {
225 return currentTimerDelay;
229 public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
230 Optional.ofNullable(contexts.get(deviceInfo)).ifPresent(OFPContext::close);
231 deviceTerminationPhaseHandler.onDeviceContextLevelDown(deviceInfo);
235 public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
236 final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
237 smModeOutputBld.setMode(workMode);
238 return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
242 public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
243 final Future<RpcResult<Void>> result;
244 // acquire exclusive access
245 if (workModeGuard.tryAcquire()) {
246 final StatisticsWorkMode targetWorkMode = input.getMode();
247 if (!workMode.equals(targetWorkMode)) {
248 isStatisticsPollingOn = !(StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode));
249 // iterate through stats-ctx: propagate mode
250 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
251 final DeviceInfo deviceInfo = entry.getKey();
252 final StatisticsContext statisticsContext = entry.getValue();
253 final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
254 switch (targetWorkMode) {
256 scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
257 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
258 lifeCycleSource.setItemLifecycleListener(null);
262 final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
263 if (pollTimeout.isPresent()) {
264 pollTimeout.get().cancel();
266 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
267 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
271 LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
274 workMode = targetWorkMode;
276 workModeGuard.release();
277 result = RpcResultBuilder.<Void>success().buildFuture();
279 result = RpcResultBuilder.<Void>failed()
280 .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
287 public void startScheduling(final DeviceInfo deviceInfo) {
288 if (!isStatisticsPollingOn) {
289 LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
293 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
295 if (statisticsContext == null) {
296 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
300 if (statisticsContext.isSchedulingEnabled()) {
301 LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
305 LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
307 statisticsContext.setSchedulingEnabled(true);
309 statisticsContext.gainDeviceState(),
317 public void stopScheduling(final DeviceInfo deviceInfo) {
318 if (LOG.isDebugEnabled()) {
319 LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
322 final StatisticsContext statisticsContext = contexts.get(deviceInfo);
324 if (statisticsContext == null) {
325 LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
329 statisticsContext.setSchedulingEnabled(false);
333 public void close() {
334 if (controlServiceRegistration != null) {
335 controlServiceRegistration.close();
336 controlServiceRegistration = null;
339 for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
340 iterator.hasNext();) {
341 iterator.next().close();
346 public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
347 this.deviceTerminationPhaseHandler = handler;
351 public void setIsStatisticsPollingOn(boolean isStatisticsPollingOn){
352 this.isStatisticsPollingOn = isStatisticsPollingOn;
355 public void onDeviceRemoved(DeviceInfo deviceInfo) {
356 contexts.remove(deviceInfo);
357 LOG.debug("Statistics context removed for node {}", deviceInfo.getLOGValue());
361 public void setBasicTimerDelay(final long basicTimerDelay) {
362 this.basicTimerDelay = basicTimerDelay;
366 public void setMaximumTimerDelay(final long maximumTimerDelay) {
367 this.maximumTimerDelay = maximumTimerDelay;