Fix direct statistics
[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.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 io.netty.util.HashedWheelTimer;
19 import io.netty.util.Timeout;
20 import io.netty.util.TimerTask;
21 import java.util.Iterator;
22 import java.util.Map;
23 import java.util.Optional;
24 import java.util.concurrent.CancellationException;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.Semaphore;
29 import java.util.concurrent.TimeUnit;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
32 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
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.device.handlers.DeviceInitializationPhaseHandler;
37 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
38 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
39 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
40 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
41 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
42 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
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 DeviceInitializationPhaseHandler deviceInitPhaseHandler;
62     private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
63
64     private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
65
66     private static final long basicTimerDelay = 3000;
67     private static long currentTimerDelay = basicTimerDelay;
68     private static final long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
69
70     private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
71     private final Semaphore workModeGuard = new Semaphore(1, true);
72     private boolean isStatisticsPollingOff;
73     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
74
75     private final HashedWheelTimer hashedWheelTimer;
76
77     @Override
78     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
79         deviceInitPhaseHandler = handler;
80     }
81
82     public StatisticsManagerImpl(final RpcProviderRegistry rpcProviderRegistry,
83                                  final boolean isStatisticsPollingOff,
84                                  final HashedWheelTimer hashedWheelTimer,
85                                  final ConvertorExecutor convertorExecutor) {
86         Preconditions.checkArgument(rpcProviderRegistry != null);
87             this.converterExecutor = convertorExecutor;
88         this.controlServiceRegistration = Preconditions.checkNotNull(
89                 rpcProviderRegistry.addRpcImplementation(StatisticsManagerControlService.class, this)
90         );
91         this.isStatisticsPollingOff = isStatisticsPollingOff;
92         this.hashedWheelTimer = hashedWheelTimer;
93     }
94
95     @Override
96     public void onDeviceContextLevelUp(final DeviceInfo deviceInfo,
97                                        final LifecycleService lifecycleService) throws Exception {
98
99         final StatisticsContext statisticsContext =
100                 new StatisticsContextImpl(
101                         deviceInfo,
102                         isStatisticsPollingOff,
103                         lifecycleService,
104                         converterExecutor,
105                         this);
106         Verify.verify(
107                 contexts.putIfAbsent(deviceInfo, statisticsContext) == null,
108                 "StatisticsCtx still not closed for Node {}", deviceInfo.getLOGValue()
109         );
110         lifecycleService.setStatContext(statisticsContext);
111         deviceInitPhaseHandler.onDeviceContextLevelUp(deviceInfo, lifecycleService);
112     }
113
114     @VisibleForTesting
115     void pollStatistics(final DeviceState deviceState,
116                         final StatisticsContext statisticsContext,
117                         final TimeCounter timeCounter,
118                         final DeviceInfo deviceInfo) {
119
120         if (!statisticsContext.isSchedulingEnabled()) {
121             if (LOG.isDebugEnabled()) {
122                 LOG.debug("Disabled statistics scheduling for device: {}", deviceInfo.getNodeId().getValue());
123             }
124             return;
125         }
126
127         if (LOG.isDebugEnabled()) {
128             LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
129         }
130         timeCounter.markStart();
131         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
132         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
133             @Override
134             public void onSuccess(final Boolean o) {
135                 timeCounter.addTimeMark();
136                 calculateTimerDelay(timeCounter);
137                 scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
138             }
139
140             @Override
141             public void onFailure(@Nonnull final Throwable throwable) {
142                 timeCounter.addTimeMark();
143                 LOG.warn("Statistics gathering for single node {} was not successful: ", deviceInfo.getLOGValue(), throwable.getMessage());
144                 if (LOG.isTraceEnabled()) {
145                     LOG.trace("Gathering for node {} failure: ", deviceInfo.getLOGValue(), throwable);
146                 }
147                 calculateTimerDelay(timeCounter);
148                 if (throwable instanceof IllegalStateException) {
149                     stopScheduling(deviceInfo);
150                 } else {
151                     scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
152                 }
153             }
154         });
155
156         final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
157         final long statsTimeoutSec = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
158         final TimerTask timerTask = timeout -> {
159             if (!deviceStatisticsCollectionFuture.isDone()) {
160                 LOG.info("Statistics collection for node {} still in progress even after {} secs", deviceInfo.getLOGValue(), statsTimeoutSec);
161                 deviceStatisticsCollectionFuture.cancel(true);
162             }
163         };
164
165         hashedWheelTimer.newTimeout(timerTask, statsTimeoutSec, TimeUnit.SECONDS);
166     }
167
168     private void scheduleNextPolling(final DeviceState deviceState,
169                                      final DeviceInfo deviceInfo,
170                                      final StatisticsContext statisticsContext,
171                                      final TimeCounter timeCounter) {
172         if (LOG.isDebugEnabled()) {
173             LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceInfo.getNodeId());
174         }
175         if (!isStatisticsPollingOff) {
176             final Timeout pollTimeout = hashedWheelTimer.newTimeout(
177                     timeout -> pollStatistics(
178                             deviceState,
179                             statisticsContext,
180                             timeCounter,
181                             deviceInfo),
182                     currentTimerDelay,
183                     TimeUnit.MILLISECONDS);
184             statisticsContext.setPollTimeout(pollTimeout);
185         }
186     }
187
188     @VisibleForTesting
189     void calculateTimerDelay(final TimeCounter timeCounter) {
190         final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
191         if (averageStatisticsGatheringTime > currentTimerDelay) {
192             currentTimerDelay *= 2;
193             if (currentTimerDelay > maximumTimerDelay) {
194                 currentTimerDelay = maximumTimerDelay;
195             }
196         } else {
197             if (currentTimerDelay > basicTimerDelay) {
198                 currentTimerDelay /= 2;
199             } else {
200                 currentTimerDelay = basicTimerDelay;
201             }
202         }
203     }
204
205     @VisibleForTesting
206     static long getCurrentTimerDelay() {
207         return currentTimerDelay;
208     }
209
210     @Override
211     public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
212         final StatisticsContext statisticsContext = contexts.remove(deviceInfo);
213         if (null != statisticsContext) {
214             LOG.debug("Removing device context from stack. No more statistics gathering for device: {}", deviceInfo.getLOGValue());
215             statisticsContext.close();
216         }
217         deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
218     }
219
220     @Override
221     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
222         final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
223         smModeOutputBld.setMode(workMode);
224         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
225     }
226
227     @Override
228     public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
229         final Future<RpcResult<Void>> result;
230         // acquire exclusive access
231         if (workModeGuard.tryAcquire()) {
232             final StatisticsWorkMode targetWorkMode = input.getMode();
233             if (!workMode.equals(targetWorkMode)) {
234                 isStatisticsPollingOff = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
235                 // iterate through stats-ctx: propagate mode
236                 for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
237                     final DeviceInfo deviceInfo = entry.getKey();
238                     final StatisticsContext statisticsContext = entry.getValue();
239                     final DeviceContext deviceContext = statisticsContext.gainDeviceContext();
240                     switch (targetWorkMode) {
241                         case COLLECTALL:
242                             scheduleNextPolling(statisticsContext.gainDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
243                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
244                                 lifeCycleSource.setItemLifecycleListener(null);
245                             }
246                             break;
247                         case FULLYDISABLED:
248                             final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
249                             if (pollTimeout.isPresent()) {
250                                 pollTimeout.get().cancel();
251                             }
252                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
253                                 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
254                             }
255                             break;
256                         default:
257                             LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
258                     }
259                 }
260                 workMode = targetWorkMode;
261             }
262             workModeGuard.release();
263             result = RpcResultBuilder.<Void>success().buildFuture();
264         } else {
265             result = RpcResultBuilder.<Void>failed()
266                     .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
267                     .buildFuture();
268         }
269         return result;
270     }
271
272     @Override
273     public void startScheduling(final DeviceInfo deviceInfo) {
274         if (isStatisticsPollingOff) {
275             LOG.info("Statistics are shutdown for device: {}", deviceInfo.getNodeId());
276             return;
277         }
278
279         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
280
281         if (statisticsContext == null) {
282             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
283             return;
284         }
285
286         if (statisticsContext.isSchedulingEnabled()) {
287             LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
288             return;
289         }
290
291         LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
292
293         statisticsContext.setSchedulingEnabled(true);
294         scheduleNextPolling(
295                 statisticsContext.gainDeviceState(),
296                 deviceInfo,
297                 statisticsContext,
298                 new TimeCounter()
299         );
300     }
301
302     @Override
303     public void stopScheduling(final DeviceInfo deviceInfo) {
304         if (LOG.isDebugEnabled()) {
305             LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
306         }
307         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
308
309         if (statisticsContext == null) {
310             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
311             return;
312         }
313         statisticsContext.setSchedulingEnabled(false);
314     }
315
316     @Override
317     public void close() {
318         if (controlServiceRegistration != null) {
319             controlServiceRegistration.close();
320             controlServiceRegistration = null;
321         }
322         for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
323                 iterator.hasNext();) {
324             iterator.next().close();
325         }
326     }
327
328     @Override
329     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
330         this.deviceTerminPhaseHandler = handler;
331     }
332
333     @Override
334     public void setIsStatisticsPollingOff(boolean isStatisticsPollingOff){
335         this.isStatisticsPollingOff = isStatisticsPollingOff;
336     }
337
338 }