Report (TCP) port number for switches
[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.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;
52
53 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
54
55     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
56
57     private static final long DEFAULT_STATS_TIMEOUT_SEC = 50L;
58     private final ConvertorExecutor converterExecutor;
59
60     private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
61
62     private long basicTimerDelay;
63     private long currentTimerDelay;
64     private long maximumTimerDelay; //wait time for next statistics
65
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 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));
79
80         this.hashedWheelTimer = hashedWheelTimer;
81     }
82
83     @VisibleForTesting
84     void pollStatistics(final DeviceState deviceState,
85                         final StatisticsContext statisticsContext,
86                         final TimeCounter timeCounter,
87                         final DeviceInfo deviceInfo) {
88
89         if (!statisticsContext.isSchedulingEnabled()) {
90             if (LOG.isDebugEnabled()) {
91                 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
92             }
93             return;
94         }
95
96         if (LOG.isDebugEnabled()) {
97             LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
98         }
99
100         timeCounter.markStart();
101         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
102         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
103             @Override
104             public void onSuccess(final Boolean o) {
105                 timeCounter.addTimeMark();
106                 calculateTimerDelay(timeCounter);
107                 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
108             }
109
110             @Override
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);
117                 }
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);
126                 } else {
127                     if (!(throwable instanceof CancellationException)) {
128                         LOG.warn("Unexpected error occurred during statistics collection for node {}, 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 (isStatisticsPollingOn) {
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     @VisibleForTesting
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;
177             }
178         } else {
179             if (currentTimerDelay > basicTimerDelay) {
180                 currentTimerDelay /= 2;
181             } else {
182                 currentTimerDelay = basicTimerDelay;
183             }
184         }
185     }
186
187     @VisibleForTesting
188     long getCurrentTimerDelay() {
189         return currentTimerDelay;
190     }
191
192     @Override
193     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
194         final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
195         smModeOutputBld.setMode(workMode);
196         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
197     }
198
199     @Override
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) {
213                         case COLLECTALL:
214                             scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
215                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
216                                 lifeCycleSource.setItemLifecycleListener(null);
217                             }
218                             break;
219                         case FULLYDISABLED:
220                             statisticsContext.stopGatheringData();
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 }