BUG-4084: Li:Save flows in operational based on barrier success
[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.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import io.netty.util.HashedWheelTimer;
17 import io.netty.util.Timeout;
18 import io.netty.util.TimerTask;
19 import java.util.Map;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.Future;
22 import java.util.concurrent.Semaphore;
23 import java.util.concurrent.TimeUnit;
24 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
25 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
26 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
27 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
28 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
29 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
30 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
31 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
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 /**
44  * Created by Martin Bobak <mbobak@cisco.com> on 1.4.2015.
45  */
46 public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
47
48     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
49     private final RpcProviderRegistry rpcProviderRegistry;
50
51     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
52
53     private HashedWheelTimer hashedWheelTimer;
54
55     private final ConcurrentHashMap<DeviceContext, StatisticsContext> contexts = new ConcurrentHashMap<>();
56
57     private static final long basicTimerDelay = 3000;
58     private static long currentTimerDelay = basicTimerDelay;
59     private static long maximumTimerDelay = 900000; //wait max 15 minutes for next statistics
60
61     private StatisticsWorkMode workMode = StatisticsWorkMode.COLLECTALL;
62     private Semaphore workModeGuard = new Semaphore(1, true);
63     private boolean shuttingDownStatisticsPolling;
64     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> controlServiceRegistration;
65
66     @Override
67     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
68         deviceInitPhaseHandler = handler;
69     }
70
71     public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry) {
72         this.rpcProviderRegistry = rpcProviderRegistry;
73         controlServiceRegistration = rpcProviderRegistry.addRpcImplementation(StatisticsManagerControlService.class, this);
74     }
75
76     public StatisticsManagerImpl(RpcProviderRegistry rpcProviderRegistry, final boolean shuttingDownStatisticsPolling) {
77         this(rpcProviderRegistry);
78         this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
79     }
80
81     @Override
82     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
83
84         if (null == hashedWheelTimer) {
85             LOG.trace("This is first device that delivered timer. Starting statistics polling immediately.");
86             hashedWheelTimer = deviceContext.getTimer();
87         }
88
89         final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceContext);
90         deviceContext.addDeviceContextClosedHandler(this);
91         final ListenableFuture<Boolean> weHaveDynamicData = statisticsContext.gatherDynamicData();
92         Futures.addCallback(weHaveDynamicData, new FutureCallback<Boolean>() {
93             @Override
94             public void onSuccess(final Boolean statisticsGathered) {
95                 if (statisticsGathered) {
96                     //there are some statistics on device worth gathering
97                     contexts.put(deviceContext, statisticsContext);
98                     final TimeCounter timeCounter = new TimeCounter();
99                     scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
100                     LOG.trace("Device dynamic info collecting done. Going to announce raise to next level.");
101                     deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
102                     deviceContext.getDeviceState().setDeviceSynchronized(true);
103                 } else {
104                     final String deviceAdress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress().toString();
105                     try {
106                         deviceContext.close();
107                     } catch (Exception e) {
108                         LOG.info("Statistics for device {} could not be gathered. Closing its device context.", deviceAdress);
109                     }
110                 }
111             }
112
113             @Override
114             public void onFailure(final Throwable throwable) {
115                 LOG.warn("Statistics manager was not able to collect dynamic info for device.", deviceContext.getDeviceState().getNodeId(), throwable);
116                 try {
117                     deviceContext.close();
118                 } catch (Exception e) {
119                     LOG.warn("Error closing device context.", e);
120                 }
121             }
122         });
123     }
124
125     private void pollStatistics(final DeviceContext deviceContext,
126                                 final StatisticsContext statisticsContext,
127                                 final TimeCounter timeCounter) {
128         timeCounter.markStart();
129         ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
130         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
131             @Override
132             public void onSuccess(final Boolean o) {
133                 timeCounter.addTimeMark();
134                 calculateTimerDelay(timeCounter);
135                 scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
136             }
137
138             @Override
139             public void onFailure(final Throwable throwable) {
140                 timeCounter.addTimeMark();
141                 LOG.info("Statistics gathering for single node was not successful: {}", throwable.getMessage());
142                 LOG.debug("Statistics gathering for single node was not successful.. ", throwable);
143                 if (ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
144                     calculateTimerDelay(timeCounter);
145                     scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
146                 }
147             }
148         });
149     }
150
151     private void scheduleNextPolling(final DeviceContext deviceContext,
152                                      final StatisticsContext statisticsContext,
153                                      final TimeCounter timeCounter) {
154         if (null != hashedWheelTimer) {
155             if (!shuttingDownStatisticsPolling) {
156                 Timeout pollTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
157                     @Override
158                     public void run(final Timeout timeout) throws Exception {
159                         pollStatistics(deviceContext, statisticsContext, timeCounter);
160                     }
161                 }, currentTimerDelay, TimeUnit.MILLISECONDS);
162                 statisticsContext.setPollTimeout(pollTimeout);
163             }
164         }
165     }
166
167     @VisibleForTesting
168     protected void calculateTimerDelay(final TimeCounter timeCounter) {
169         // TODO: move into TimeCounter
170         long averageStatisticsGatheringTime = timeCounter.getAverageTimeBetweenMarks();
171         if (averageStatisticsGatheringTime > currentTimerDelay) {
172             currentTimerDelay *= 2;
173             if (currentTimerDelay > maximumTimerDelay) {
174                 currentTimerDelay = maximumTimerDelay;
175             }
176         } else {
177             if (currentTimerDelay > basicTimerDelay) {
178                 currentTimerDelay /= 2;
179             } else {
180                 currentTimerDelay = basicTimerDelay;
181             }
182         }
183     }
184
185     @VisibleForTesting
186     protected static long getCurrentTimerDelay() {
187         return currentTimerDelay;
188     }
189
190     @Override
191     public void onDeviceContextClosed(final DeviceContext deviceContext) {
192         StatisticsContext statisticsContext = contexts.remove(deviceContext);
193         if (null != statisticsContext) {
194             LOG.trace("Removing device context from stack. No more statistics gathering for node {}", deviceContext.getDeviceState().getNodeId());
195             try {
196                 statisticsContext.close();
197             } catch (Exception e) {
198                 LOG.debug("Error closing statistic context for node {}.", deviceContext.getDeviceState().getNodeId());
199             }
200         }
201     }
202
203     @Override
204     public Future<RpcResult<GetStatisticsWorkModeOutput>> getStatisticsWorkMode() {
205         GetStatisticsWorkModeOutputBuilder smModeOutputBld = new GetStatisticsWorkModeOutputBuilder();
206         smModeOutputBld.setMode(workMode);
207         return RpcResultBuilder.success(smModeOutputBld.build()).buildFuture();
208     }
209
210     @Override
211     public Future<RpcResult<Void>> changeStatisticsWorkMode(ChangeStatisticsWorkModeInput input) {
212         final Future<RpcResult<Void>> result;
213         // acquire exclusive access
214         if (workModeGuard.tryAcquire()) {
215             final StatisticsWorkMode targetWorkMode = input.getMode();
216             if (!workMode.equals(targetWorkMode)) {
217                 shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
218                 // iterate through stats-ctx: propagate mode
219                 for (Map.Entry<DeviceContext, StatisticsContext> contextEntry : contexts.entrySet()) {
220                     final DeviceContext deviceContext = contextEntry.getKey();
221                     final StatisticsContext statisticsContext = contextEntry.getValue();
222                     switch (targetWorkMode) {
223                         case COLLECTALL:
224                             scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
225                             for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
226                                 lifeCycleSource.setItemLifecycleListener(null);
227                             }
228                             break;
229                         case FULLYDISABLED:
230                             final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
231                             if (pollTimeout.isPresent()) {
232                                 pollTimeout.get().cancel();
233                             }
234                             for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
235                                 lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
236                             }
237                             break;
238                         default:
239                             LOG.warn("statistics work mode not supported: {}", targetWorkMode);
240                     }
241                 }
242                 workMode = targetWorkMode;
243             }
244             workModeGuard.release();
245             result = RpcResultBuilder.<Void>success().buildFuture();
246         } else {
247             result = RpcResultBuilder.<Void>failed()
248                     .withError(RpcError.ErrorType.APPLICATION, "mode change already in progress")
249                     .buildFuture();
250         }
251         return result;
252     }
253
254     @Override
255     public void close() {
256         if (controlServiceRegistration != null) {
257             controlServiceRegistration.close();
258             controlServiceRegistration = null;
259         }
260     }
261 }