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