Encapsulate OpenFlowPlugin configuration
[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 boolean isStatisticsPollingOn;
69     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
70
71     private final HashedWheelTimer hashedWheelTimer;
72
73     public StatisticsManagerImpl(@Nonnull final OpenflowProviderConfig config,
74                                  @Nonnull final RpcProviderRegistry rpcProviderRegistry,
75                                  final HashedWheelTimer hashedWheelTimer,
76                                  final ConvertorExecutor convertorExecutor) {
77         this.config = config;
78         currentTimerDelay = config.getBasicTimerDelay().getValue();
79         this.converterExecutor = convertorExecutor;
80         this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry
81                 .addRpcImplementation(StatisticsManagerControlService.class, this));
82
83         this.hashedWheelTimer = hashedWheelTimer;
84     }
85
86     @VisibleForTesting
87     void pollStatistics(final DeviceState deviceState,
88                         final StatisticsContext statisticsContext,
89                         final TimeCounter timeCounter,
90                         final DeviceInfo deviceInfo) {
91
92         if (!statisticsContext.isSchedulingEnabled()) {
93             if (LOG.isDebugEnabled()) {
94                 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
95             }
96             return;
97         }
98
99         if (LOG.isDebugEnabled()) {
100             LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
101         }
102
103         timeCounter.markStart();
104         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
105         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
106             @Override
107             public void onSuccess(final Boolean o) {
108                 timeCounter.addTimeMark();
109                 calculateTimerDelay(timeCounter);
110                 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
111             }
112
113             @Override
114             public void onFailure(@Nonnull final Throwable throwable) {
115                 timeCounter.addTimeMark();
116                 calculateTimerDelay(timeCounter);
117
118                 if (throwable instanceof ConnectionException) {
119                     // ConnectionException is raised by StatisticsContextImpl class when the connections
120                     // move to RIP state. In this particular case, there is no need to reschedule
121                     // because this statistics manager should be closed soon
122                     LOG.warn("Device {} is no more connected, stopping the statistics collection",
123                             deviceInfo.getLOGValue(),throwable);
124                     stopScheduling(deviceInfo);
125                 } else if (throwable instanceof CancellationException) {
126                     LOG.info("Statistics gathering for device {} was cancelled.",
127                             deviceInfo.getLOGValue());
128                 } else {
129                     LOG.warn("Unexpected error occurred during statistics collection for device {}, 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
157         if (isStatisticsPollingOn) {
158             final Timeout pollTimeout = hashedWheelTimer.newTimeout(
159                     timeout -> pollStatistics(
160                             deviceState,
161                             statisticsContext,
162                             timeCounter,
163                             deviceInfo),
164                     currentTimerDelay,
165                     TimeUnit.MILLISECONDS);
166
167             statisticsContext.setPollTimeout(pollTimeout);
168         }
169     }
170
171     @VisibleForTesting
172     void calculateTimerDelay(final TimeCounter timeCounter) {
173         final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
174         if (averageStatisticsGatheringTime > currentTimerDelay) {
175             currentTimerDelay *= 2;
176             if (currentTimerDelay > config.getMaximumTimerDelay().getValue()) {
177                 currentTimerDelay = config.getMaximumTimerDelay().getValue();
178             }
179         } else {
180             if (currentTimerDelay > config.getBasicTimerDelay().getValue()) {
181                 currentTimerDelay /= 2;
182             } else {
183                 currentTimerDelay = config.getBasicTimerDelay().getValue();
184             }
185         }
186     }
187
188     @VisibleForTesting
189     long getCurrentTimerDelay() {
190         return currentTimerDelay;
191     }
192
193     @Override
194     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
195         final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
196         smModeOutputBld.setMode(workMode);
197         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
198     }
199
200     @Override
201     public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
202         final Future<RpcResult<Void>> result;
203         // acquire exclusive access
204         if (workModeGuard.tryAcquire()) {
205             final StatisticsWorkMode targetWorkMode = input.getMode();
206             if (!workMode.equals(targetWorkMode)) {
207                 isStatisticsPollingOn = !(StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode));
208                 // iterate through stats-ctx: propagate mode
209                 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
210                     final DeviceInfo deviceInfo = entry.getKey();
211                     final StatisticsContext statisticsContext = entry.getValue();
212                     final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
213                     switch (targetWorkMode) {
214                         case COLLECTALL:
215                             scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
216                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
217                                 lifeCycleSource.setItemLifecycleListener(null);
218                             }
219                             break;
220                         case FULLYDISABLED:
221                             statisticsContext.stopGatheringData();
222                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
223                                 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
224                             }
225                             break;
226                         default:
227                             LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
228                     }
229                 }
230                 workMode = targetWorkMode;
231             }
232             workModeGuard.release();
233             result = RpcResultBuilder.<Void>success().buildFuture();
234         } else {
235             result = RpcResultBuilder.<Void>failed()
236                     .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
237                     .buildFuture();
238         }
239         return result;
240     }
241
242     @Override
243     public void startScheduling(final DeviceInfo deviceInfo) {
244         if (!isStatisticsPollingOn) {
245             LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
246             return;
247         }
248
249         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
250
251         if (statisticsContext == null) {
252             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
253             return;
254         }
255
256         if (statisticsContext.isSchedulingEnabled()) {
257             LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
258             return;
259         }
260
261         LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
262
263         statisticsContext.setSchedulingEnabled(true);
264         scheduleNextPolling(
265                 statisticsContext.gainDeviceState(),
266                 deviceInfo,
267                 statisticsContext,
268                 new TimeCounter()
269         );
270     }
271
272     @Override
273     public void stopScheduling(final DeviceInfo deviceInfo) {
274         if (LOG.isDebugEnabled()) {
275             LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
276         }
277
278         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
279
280         if (statisticsContext == null) {
281             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
282             return;
283         }
284
285         statisticsContext.setSchedulingEnabled(false);
286     }
287
288     @Override
289     public void close() {
290         if (controlServiceRegistration != null) {
291             controlServiceRegistration.close();
292             controlServiceRegistration = null;
293         }
294
295         for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
296                 iterator.hasNext();) {
297             iterator.next().close();
298         }
299     }
300
301     @Override
302     public StatisticsContext createContext(@Nonnull final DeviceContext deviceContext) {
303
304         final MultipartWriterProvider statisticsWriterProvider = MultipartWriterProviderFactory
305             .createDefaultProvider(deviceContext);
306
307         final StatisticsContext statisticsContext =
308             deviceContext.canUseSingleLayerSerialization() ?
309             new StatisticsContextImpl<MultipartReply>(
310                 isStatisticsPollingOn,
311                 deviceContext,
312                 converterExecutor,
313                     this,
314                 statisticsWriterProvider) :
315             new StatisticsContextImpl<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
316                 .MultipartReply>(
317                 isStatisticsPollingOn,
318                 deviceContext,
319                 converterExecutor,
320                     this,
321                 statisticsWriterProvider);
322         contexts.putIfAbsent(deviceContext.getDeviceInfo(), statisticsContext);
323
324         return statisticsContext;
325     }
326
327     @Override
328     public void onDeviceRemoved(final DeviceInfo deviceInfo) {
329         contexts.remove(deviceInfo);
330         if (LOG.isDebugEnabled()) {
331             LOG.debug("Statistics context removed for node {}", deviceInfo.getLOGValue());
332         }
333     }
334 }