Merge "ONF Bundles sample application"
[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.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;
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     @Nonnull
60     private final OpenflowProviderConfig config;
61     private final ConvertorExecutor converterExecutor;
62
63     private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
64
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;
71
72     public StatisticsManagerImpl(@Nonnull final OpenflowProviderConfig config,
73                                  @Nonnull final RpcProviderRegistry rpcProviderRegistry,
74                                  final HashedWheelTimer hashedWheelTimer,
75                                  final ConvertorExecutor convertorExecutor) {
76         this.config = config;
77         currentTimerDelay = config.getBasicTimerDelay().getValue();
78         this.converterExecutor = convertorExecutor;
79         this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry
80                 .addRpcImplementation(StatisticsManagerControlService.class, this));
81
82         this.hashedWheelTimer = hashedWheelTimer;
83     }
84
85     @VisibleForTesting
86     void pollStatistics(final DeviceState deviceState,
87                         final StatisticsContext statisticsContext,
88                         final TimeCounter timeCounter,
89                         final DeviceInfo deviceInfo) {
90
91         if (!statisticsContext.isSchedulingEnabled()) {
92             if (LOG.isDebugEnabled()) {
93                 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
94             }
95             return;
96         }
97
98         if (LOG.isDebugEnabled()) {
99             LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
100         }
101
102         timeCounter.markStart();
103         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
104         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
105             @Override
106             public void onSuccess(final Boolean o) {
107                 timeCounter.addTimeMark();
108                 calculateTimerDelay(timeCounter);
109                 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
110             }
111
112             @Override
113             public void onFailure(@Nonnull final Throwable throwable) {
114                 timeCounter.addTimeMark();
115                 calculateTimerDelay(timeCounter);
116
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());
127                 } else {
128                     LOG.warn("Unexpected error occurred during statistics collection for device {}, rescheduling " +
129                             "statistics collections", deviceInfo.getLOGValue(), throwable);
130
131                     scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
132                 }
133             }
134         });
135
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);
142             }
143         };
144
145         hashedWheelTimer.newTimeout(timerTask, statsTimeoutSec, TimeUnit.SECONDS);
146     }
147
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());
154         }
155
156         if (isStatisticsEnabled()) {
157             final Timeout pollTimeout = hashedWheelTimer.newTimeout(
158                     timeout -> pollStatistics(
159                             deviceState,
160                             statisticsContext,
161                             timeCounter,
162                             deviceInfo),
163                     currentTimerDelay,
164                     TimeUnit.MILLISECONDS);
165
166             statisticsContext.setPollTimeout(pollTimeout);
167         }
168     }
169
170     private boolean isStatisticsEnabled() {
171         return !istStatisticsFullyDisabled && config.isIsStatisticsPollingOn();
172     }
173
174     @VisibleForTesting
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();
181             }
182         } else {
183             if (currentTimerDelay > config.getBasicTimerDelay().getValue()) {
184                 currentTimerDelay /= 2;
185             } else {
186                 currentTimerDelay = config.getBasicTimerDelay().getValue();
187             }
188         }
189     }
190
191     @VisibleForTesting
192     long getCurrentTimerDelay() {
193         return currentTimerDelay;
194     }
195
196     @Override
197     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
198         final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
199         smModeOutputBld.setMode(workMode);
200         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
201     }
202
203     @Override
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);
211
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) {
218                         case COLLECTALL:
219                             scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
220                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
221                                 lifeCycleSource.setItemLifecycleListener(null);
222                             }
223                             break;
224                         case FULLYDISABLED:
225                             statisticsContext.stopGatheringData();
226                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
227                                 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
228                             }
229                             break;
230                         default:
231                             LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
232                     }
233                 }
234                 workMode = targetWorkMode;
235             }
236             workModeGuard.release();
237             result = RpcResultBuilder.<Void>success().buildFuture();
238         } else {
239             result = RpcResultBuilder.<Void>failed()
240                     .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
241                     .buildFuture();
242         }
243         return result;
244     }
245
246     @Override
247     public void startScheduling(final DeviceInfo deviceInfo) {
248         if (!isStatisticsEnabled()) {
249             LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
250             return;
251         }
252
253         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
254
255         if (statisticsContext == null) {
256             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
257             return;
258         }
259
260         if (statisticsContext.isSchedulingEnabled()) {
261             LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
262             return;
263         }
264
265         LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
266
267         statisticsContext.setSchedulingEnabled(true);
268         scheduleNextPolling(
269                 statisticsContext.gainDeviceState(),
270                 deviceInfo,
271                 statisticsContext,
272                 new TimeCounter()
273         );
274     }
275
276     @Override
277     public void stopScheduling(final DeviceInfo deviceInfo) {
278         if (LOG.isDebugEnabled()) {
279             LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
280         }
281
282         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
283
284         if (statisticsContext == null) {
285             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
286             return;
287         }
288
289         statisticsContext.setSchedulingEnabled(false);
290     }
291
292     @Override
293     public void close() {
294         istStatisticsFullyDisabled = true;
295
296         if (controlServiceRegistration != null) {
297             controlServiceRegistration.close();
298             controlServiceRegistration = null;
299         }
300
301         for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
302                 iterator.hasNext();) {
303             iterator.next().close();
304         }
305     }
306
307     @Override
308     public StatisticsContext createContext(@Nonnull final DeviceContext deviceContext) {
309
310         final MultipartWriterProvider statisticsWriterProvider = MultipartWriterProviderFactory
311             .createDefaultProvider(deviceContext);
312
313         final StatisticsContext statisticsContext =
314             deviceContext.canUseSingleLayerSerialization() ?
315             new StatisticsContextImpl<MultipartReply>(
316                 isStatisticsEnabled(),
317                 deviceContext,
318                 converterExecutor,
319                     this,
320                 statisticsWriterProvider) :
321             new StatisticsContextImpl<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
322                 .MultipartReply>(
323                 isStatisticsEnabled(),
324                 deviceContext,
325                 converterExecutor,
326                     this,
327                 statisticsWriterProvider);
328         contexts.putIfAbsent(deviceContext.getDeviceInfo(), statisticsContext);
329
330         return statisticsContext;
331     }
332
333     @Override
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());
338         }
339     }
340 }