Merge "Bug 8223: Fixed incorrect enable-flow-removed-notification check."
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImpl.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.openflowplugin.impl.statistics;
10
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;
21 import java.util.Map;
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;
53
54 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
55
56     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
57
58     private static final long DEFAULT_STATS_TIMEOUT_SEC = 50L;
59     private final ConvertorExecutor converterExecutor;
60
61     private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
62
63     private long basicTimerDelay;
64     private long currentTimerDelay;
65     private long maximumTimerDelay; //wait time for next statistics
66
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;
71
72     private final HashedWheelTimer hashedWheelTimer;
73
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));
80
81         this.hashedWheelTimer = hashedWheelTimer;
82     }
83
84     @VisibleForTesting
85     void pollStatistics(final DeviceState deviceState,
86                         final StatisticsContext statisticsContext,
87                         final TimeCounter timeCounter,
88                         final DeviceInfo deviceInfo) {
89
90         if (!statisticsContext.isSchedulingEnabled()) {
91             if (LOG.isDebugEnabled()) {
92                 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
93             }
94             return;
95         }
96
97         if (LOG.isDebugEnabled()) {
98             LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
99         }
100
101         timeCounter.markStart();
102         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
103         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
104             @Override
105             public void onSuccess(final Boolean o) {
106                 timeCounter.addTimeMark();
107                 calculateTimerDelay(timeCounter);
108                 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
109             }
110
111             @Override
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);
118                 }
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);
127                 } else {
128                     if (!(throwable instanceof CancellationException)) {
129                         LOG.warn("Unexpected error occurred during statistics collection for node {}, rescheduling " +
130                                 "statistics collections", deviceInfo.getLOGValue(),throwable);
131                     }
132                     scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
133                 }
134             }
135         });
136
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);
143             }
144         };
145
146         hashedWheelTimer.newTimeout(timerTask, statsTimeoutSec, TimeUnit.SECONDS);
147     }
148
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());
155         }
156         if (isStatisticsPollingOn) {
157             final Timeout pollTimeout = hashedWheelTimer.newTimeout(
158                     timeout -> pollStatistics(
159                             deviceState,
160                             statisticsContext,
161                             timeCounter,
162                             deviceInfo),
163                     currentTimerDelay,
164                     TimeUnit.MILLISECONDS);
165             statisticsContext.setPollTimeout(pollTimeout);
166         }
167     }
168
169     @VisibleForTesting
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;
176             }
177         } else {
178             if (currentTimerDelay > basicTimerDelay) {
179                 currentTimerDelay /= 2;
180             } else {
181                 currentTimerDelay = basicTimerDelay;
182             }
183         }
184     }
185
186     @VisibleForTesting
187     long getCurrentTimerDelay() {
188         return currentTimerDelay;
189     }
190
191     @Override
192     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
193         final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
194         smModeOutputBld.setMode(workMode);
195         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
196     }
197
198     @Override
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) {
212                         case COLLECTALL:
213                             scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
214                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
215                                 lifeCycleSource.setItemLifecycleListener(null);
216                             }
217                             break;
218                         case FULLYDISABLED:
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());
223                             }
224                             break;
225                         default:
226                             LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
227                     }
228                 }
229                 workMode = targetWorkMode;
230             }
231             workModeGuard.release();
232             result = RpcResultBuilder.<Void>success().buildFuture();
233         } else {
234             result = RpcResultBuilder.<Void>failed()
235                     .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
236                     .buildFuture();
237         }
238         return result;
239     }
240
241     @Override
242     public void startScheduling(final DeviceInfo deviceInfo) {
243         if (!isStatisticsPollingOn) {
244             LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
245             return;
246         }
247
248         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
249
250         if (statisticsContext == null) {
251             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
252             return;
253         }
254
255         if (statisticsContext.isSchedulingEnabled()) {
256             LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
257             return;
258         }
259
260         LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
261
262         statisticsContext.setSchedulingEnabled(true);
263         scheduleNextPolling(
264                 statisticsContext.gainDeviceState(),
265                 deviceInfo,
266                 statisticsContext,
267                 new TimeCounter()
268         );
269     }
270
271     @Override
272     public void stopScheduling(final DeviceInfo deviceInfo) {
273         if (LOG.isDebugEnabled()) {
274             LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
275         }
276
277         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
278
279         if (statisticsContext == null) {
280             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
281             return;
282         }
283
284         statisticsContext.setSchedulingEnabled(false);
285     }
286
287     @Override
288     public void close() {
289         if (controlServiceRegistration != null) {
290             controlServiceRegistration.close();
291             controlServiceRegistration = null;
292         }
293
294         for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
295                 iterator.hasNext();) {
296             iterator.next().close();
297         }
298     }
299
300     @Override
301     public void setIsStatisticsPollingOn(boolean isStatisticsPollingOn){
302         this.isStatisticsPollingOn = isStatisticsPollingOn;
303     }
304
305     @Override
306     public StatisticsContext createContext(@Nonnull final DeviceContext deviceContext) {
307
308         final MultipartWriterProvider statisticsWriterProvider = MultipartWriterProviderFactory
309             .createDefaultProvider(deviceContext);
310
311         final StatisticsContext statisticsContext =
312             deviceContext.canUseSingleLayerSerialization() ?
313             new StatisticsContextImpl<MultipartReply>(
314                 isStatisticsPollingOn,
315                 deviceContext,
316                 converterExecutor,
317                     this,
318                 statisticsWriterProvider) :
319             new StatisticsContextImpl<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
320                 .MultipartReply>(
321                 isStatisticsPollingOn,
322                 deviceContext,
323                 converterExecutor,
324                     this,
325                 statisticsWriterProvider);
326         contexts.putIfAbsent(deviceContext.getDeviceInfo(), statisticsContext);
327
328         return statisticsContext;
329     }
330
331     @Override
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());
336         }
337     }
338
339     @Override
340     public void setBasicTimerDelay(final long basicTimerDelay) {
341         this.basicTimerDelay = basicTimerDelay;
342         this.currentTimerDelay = basicTimerDelay;
343     }
344
345     @Override
346     public void setMaximumTimerDelay(final long maximumTimerDelay) {
347         this.maximumTimerDelay = maximumTimerDelay;
348     }
349 }