DeviceState changes
[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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Verify;
15 import com.google.common.collect.Iterators;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import io.netty.util.Timeout;
20 import io.netty.util.TimerTask;
21 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
22 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
23 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
24 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
25 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
26 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
27 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
28 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
29 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
30 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
37 import org.opendaylight.yangtools.yang.common.RpcError;
38 import org.opendaylight.yangtools.yang.common.RpcResult;
39 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import javax.annotation.CheckForNull;
44 import javax.annotation.Nonnull;
45 import java.util.Iterator;
46 import java.util.concurrent.CancellationException;
47 import java.util.concurrent.ConcurrentHashMap;
48 import java.util.concurrent.ConcurrentMap;
49 import java.util.concurrent.Future;
50 import java.util.concurrent.Semaphore;
51 import java.util.concurrent.TimeUnit;
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
59     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
60     private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
61
62     private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
63
64     private static final long basicTimerDelay = 3000;
65     private static long currentTimerDelay = basicTimerDelay;
66     private static final long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
67
68     private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
69     private final Semaphore workModeGuard = new Semaphore(1, true);
70     private boolean shuttingDownStatisticsPolling;
71     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
72
73     private final LifecycleConductor conductor;
74
75     @Override
76     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
77         deviceInitPhaseHandler = handler;
78     }
79
80     public StatisticsManagerImpl(@CheckForNull final RpcProviderRegistry rpcProviderRegistry,
81                                  final boolean shuttingDownStatisticsPolling,
82                                  final LifecycleConductor lifecycleConductor) {
83         Preconditions.checkArgument(rpcProviderRegistry != null);
84         this.controlServiceRegistration = Preconditions.checkNotNull(rpcProviderRegistry.addRpcImplementation(
85                 StatisticsManagerControlService.class, this));
86         this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
87         this.conductor = lifecycleConductor;
88     }
89
90     @Override
91     public void onDeviceContextLevelUp(final DeviceInfo deviceInfo) throws Exception {
92
93         final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(deviceInfo));
94
95         final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceInfo, shuttingDownStatisticsPolling, conductor);
96         Verify.verify(contexts.putIfAbsent(deviceInfo, statisticsContext) == null, "StatisticsCtx still not closed for Node {}", deviceInfo.getNodeId());
97
98         deviceContext.getDeviceState().setDeviceSynchronized(true);
99         deviceInitPhaseHandler.onDeviceContextLevelUp(deviceInfo);
100     }
101
102     @VisibleForTesting
103     void pollStatistics(final DeviceContext deviceContext,
104                                 final StatisticsContext statisticsContext,
105                                 final TimeCounter timeCounter) {
106
107         final NodeId nodeId = deviceContext.getDeviceInfo().getNodeId();
108
109         if (!statisticsContext.isSchedulingEnabled()) {
110             LOG.debug("Disabling statistics scheduling for device: {}", nodeId);
111             return;
112         }
113         
114         if (!deviceContext.getDeviceState().isValid()) {
115             LOG.debug("Session is not valid for device: {}", nodeId);
116             return;
117         }
118
119         if (!deviceContext.getDeviceState().isStatisticsPollingEnabled()) {
120             LOG.debug("Statistics polling is currently disabled for device: {}", nodeId);
121             scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
122             return;
123         }
124
125         LOG.debug("POLLING ALL STATISTICS for device: {}", nodeId);
126         timeCounter.markStart();
127         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
128         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
129             @Override
130             public void onSuccess(final Boolean o) {
131                 timeCounter.addTimeMark();
132                 calculateTimerDelay(timeCounter);
133                 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
134             }
135
136             @Override
137             public void onFailure(@Nonnull final Throwable throwable) {
138                 timeCounter.addTimeMark();
139                 LOG.warn("Statistics gathering for single node was not successful: {}", throwable.getMessage());
140                 LOG.trace("Statistics gathering for single node was not successful.. ", throwable);
141                 calculateTimerDelay(timeCounter);
142                 if (throwable instanceof CancellationException) {
143                     /** This often happens when something wrong with akka or DS, so closing connection will help to restart device **/
144                     conductor.closeConnection(deviceContext.getDeviceInfo());
145                 } else {
146                     scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
147                 }
148             }
149         });
150
151         final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
152         final long STATS_TIMEOUT_SEC = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
153         final TimerTask timerTask = timeout -> {
154             if (!deviceStatisticsCollectionFuture.isDone()) {
155                 LOG.info("Statistics collection for node {} still in progress even after {} secs", nodeId, STATS_TIMEOUT_SEC);
156                 deviceStatisticsCollectionFuture.cancel(true);
157             }
158         };
159
160         conductor.newTimeout(timerTask, STATS_TIMEOUT_SEC, TimeUnit.SECONDS);
161     }
162
163     private void scheduleNextPolling(final DeviceContext deviceContext,
164                                      final StatisticsContext statisticsContext,
165                                      final TimeCounter timeCounter) {
166         LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceContext.getDeviceInfo().getNodeId());
167         if (!shuttingDownStatisticsPolling) {
168             final Timeout pollTimeout = conductor.newTimeout(timeout -> pollStatistics(deviceContext, statisticsContext, timeCounter), currentTimerDelay, TimeUnit.MILLISECONDS);
169             statisticsContext.setPollTimeout(pollTimeout);
170         }
171     }
172
173     @VisibleForTesting
174     void calculateTimerDelay(final TimeCounter timeCounter) {
175         final long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
176         if (averageStatisticsGatheringTime > currentTimerDelay) {
177             currentTimerDelay *= 2;
178             if (currentTimerDelay > maximumTimerDelay) {
179                 currentTimerDelay = maximumTimerDelay;
180             }
181         } else {
182             if (currentTimerDelay > basicTimerDelay) {
183                 currentTimerDelay /= 2;
184             } else {
185                 currentTimerDelay = basicTimerDelay;
186             }
187         }
188     }
189
190     @VisibleForTesting
191     static long getCurrentTimerDelay() {
192         return currentTimerDelay;
193     }
194
195     @Override
196     public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
197         final StatisticsContext statisticsContext = contexts.remove(deviceInfo);
198         if (null != statisticsContext) {
199             LOG.trace("Removing device context from stack. No more statistics gathering for device: {}", deviceInfo.getNodeId());
200             statisticsContext.close();
201         }
202         deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
203     }
204
205     @Override
206     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
207         final GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
208         smModeOutputBld.setMode(workMode);
209         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
210     }
211
212     @Override
213     public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
214         final Future<RpcResult<Void>> result;
215         // acquire exclusive access
216         if (workModeGuard.tryAcquire()) {
217             final StatisticsWorkMode targetWorkMode = input.getMode();
218             if (!workMode.equals(targetWorkMode)) {
219                 shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
220                 // iterate through stats-ctx: propagate mode
221                 for (final StatisticsContext statisticsContext : contexts.values()) {
222                     final DeviceContext deviceContext = statisticsContext.getDeviceContext();
223                     switch (targetWorkMode) {
224                         case COLLECTALL:
225                             scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
226                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
227                                 lifeCycleSource.setItemLifecycleListener(null);
228                             }
229                             break;
230                         case FULLYDISABLED:
231                             final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
232                             if (pollTimeout.isPresent()) {
233                                 pollTimeout.get().cancel();
234                             }
235                             for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
236                                 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
237                             }
238                             break;
239                         default:
240                             LOG.warn("Statistics work mode not supported: {}", targetWorkMode);
241                     }
242                 }
243                 workMode = targetWorkMode;
244             }
245             workModeGuard.release();
246             result = RpcResultBuilder.<Void>success().buildFuture();
247         } else {
248             result = RpcResultBuilder.<Void>failed()
249                     .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
250                     .buildFuture();
251         }
252         return result;
253     }
254
255     @Override
256     public void startScheduling(final DeviceInfo deviceInfo) {
257         if (shuttingDownStatisticsPolling) {
258             LOG.info("Statistics are shut down for device: {}", deviceInfo.getNodeId());
259             return;
260         }
261
262         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
263
264         if (statisticsContext == null) {
265             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
266             return;
267         }
268
269         if (statisticsContext.isSchedulingEnabled()) {
270             LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
271             return;
272         }
273
274         LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
275         final DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
276
277         if (deviceContext == null) {
278             LOG.warn("Device context not found for device: {}", deviceInfo.getNodeId());
279             return;
280         }
281
282         statisticsContext.setSchedulingEnabled(true);
283         scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
284     }
285
286     @Override
287     public void stopScheduling(final DeviceInfo deviceInfo) {
288         LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
289         final StatisticsContext statisticsContext = contexts.get(deviceInfo);
290
291         if (statisticsContext == null) {
292             LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
293             return;
294         }
295
296         statisticsContext.setSchedulingEnabled(false);
297     }
298
299     @Override
300     public void close() {
301         if (controlServiceRegistration != null) {
302             controlServiceRegistration.close();
303             controlServiceRegistration = null;
304         }
305         for (final Iterator<StatisticsContext> iterator = Iterators.consumingIterator(contexts.values().iterator());
306                 iterator.hasNext();) {
307             iterator.next().close();
308         }
309     }
310
311     @Override
312     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
313         this.deviceTerminPhaseHandler = handler;
314     }
315 }