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