Merge "BUG-5573: Altering the HandshakePool to have a LinkedBlockingQueue instead...
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsContextImpl.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.collect.ImmutableList;
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 com.google.common.util.concurrent.SettableFuture;
20 import io.netty.util.Timeout;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
26 import javax.annotation.CheckForNull;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import javax.annotation.concurrent.GuardedBy;
30 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
31 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
32 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
33 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
34 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
35 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
36 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
37 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
38 import org.opendaylight.openflowplugin.impl.rpc.listener.ItemLifecycleListenerImpl;
39 import org.opendaylight.openflowplugin.impl.services.RequestContextUtil;
40 import org.opendaylight.openflowplugin.impl.statistics.services.dedicated.StatisticsGatheringOnTheFlyService;
41 import org.opendaylight.openflowplugin.impl.statistics.services.dedicated.StatisticsGatheringService;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class StatisticsContextImpl implements StatisticsContext {
48
49     private static final Logger LOG = LoggerFactory.getLogger(StatisticsContextImpl.class);
50     private static final String CONNECTION_CLOSED = "Connection closed.";
51
52     private final ItemLifecycleListener itemLifeCycleListener;
53     private final Collection<RequestContext<?>> requestContexts = new HashSet<>();
54     private final DeviceContext deviceContext;
55     private final DeviceState devState;
56     private final ListenableFuture<Boolean> emptyFuture;
57     private final boolean shuttingDownStatisticsPolling;
58     private final Object COLLECTION_STAT_TYPE_LOCK = new Object();
59     @GuardedBy("COLLECTION_STAT_TYPE_LOCK")
60     private List<MultipartType> collectingStatType;
61
62     private StatisticsGatheringService statisticsGatheringService;
63     private StatisticsGatheringOnTheFlyService statisticsGatheringOnTheFlyService;
64     private Timeout pollTimeout;
65
66     private final LifecycleConductor conductor;
67
68     public StatisticsContextImpl(@CheckForNull final NodeId nodeId, final boolean shuttingDownStatisticsPolling, final LifecycleConductor lifecycleConductor) {
69         this.conductor = lifecycleConductor;
70         this.deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
71         this.devState = Preconditions.checkNotNull(deviceContext.getDeviceState());
72         this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
73         emptyFuture = Futures.immediateFuture(false);
74         statisticsGatheringService = new StatisticsGatheringService(this, deviceContext);
75         statisticsGatheringOnTheFlyService = new StatisticsGatheringOnTheFlyService(this, deviceContext);
76         itemLifeCycleListener = new ItemLifecycleListenerImpl(deviceContext);
77         statListForCollectingInitialization();
78         this.deviceContext.setStatisticsContext(StatisticsContextImpl.this);
79     }
80
81     @Override
82     public void statListForCollectingInitialization() {
83         synchronized (COLLECTION_STAT_TYPE_LOCK) {
84             final List<MultipartType> statListForCollecting = new ArrayList<>();
85             if (devState.isTableStatisticsAvailable()) {
86                 statListForCollecting.add(MultipartType.OFPMPTABLE);
87             }
88             if (devState.isFlowStatisticsAvailable()) {
89                 statListForCollecting.add(MultipartType.OFPMPFLOW);
90             }
91             if (devState.isGroupAvailable()) {
92                 statListForCollecting.add(MultipartType.OFPMPGROUPDESC);
93                 statListForCollecting.add(MultipartType.OFPMPGROUP);
94             }
95             if (devState.isMetersAvailable()) {
96                 statListForCollecting.add(MultipartType.OFPMPMETERCONFIG);
97                 statListForCollecting.add(MultipartType.OFPMPMETER);
98             }
99             if (devState.isPortStatisticsAvailable()) {
100                 statListForCollecting.add(MultipartType.OFPMPPORTSTATS);
101             }
102             if (devState.isQueueStatisticsAvailable()) {
103                 statListForCollecting.add(MultipartType.OFPMPQUEUE);
104             }
105             collectingStatType = ImmutableList.<MultipartType>copyOf(statListForCollecting);
106         }
107     }
108
109     @Override
110     public ListenableFuture<Boolean> gatherDynamicData() {
111         if (shuttingDownStatisticsPolling) {
112             LOG.debug("Statistics for device {} is not enabled.", deviceContext.getDeviceState().getNodeId());
113             return Futures.immediateFuture(Boolean.TRUE);
114         }
115         final ListenableFuture<Boolean> errorResultFuture = deviceConnectionCheck();
116         if (errorResultFuture != null) {
117             return errorResultFuture;
118         }
119         synchronized (COLLECTION_STAT_TYPE_LOCK) {
120             final Iterator<MultipartType> statIterator = collectingStatType.iterator();
121             final SettableFuture<Boolean> settableStatResultFuture = SettableFuture.create();
122
123             // write start timestamp to state snapshot container
124             StatisticsGatheringUtils.markDeviceStateSnapshotStart(deviceContext);
125
126             statChainFuture(statIterator, settableStatResultFuture);
127
128             // write end timestamp to state snapshot container
129             Futures.addCallback(settableStatResultFuture, new FutureCallback<Boolean>() {
130                 @Override
131                 public void onSuccess(@Nullable final Boolean result) {
132                     StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceContext, true);
133                 }
134                 @Override
135                 public void onFailure(final Throwable t) {
136                     StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceContext, false);
137                 }
138             });
139             return settableStatResultFuture;
140         }
141     }
142
143     private ListenableFuture<Boolean> chooseStat(final MultipartType multipartType){
144         switch (multipartType) {
145             case OFPMPFLOW:
146                 return collectFlowStatistics(multipartType);
147             case OFPMPTABLE:
148                 return collectTableStatistics(multipartType);
149             case OFPMPPORTSTATS:
150                 return collectPortStatistics(multipartType);
151             case OFPMPQUEUE:
152                 return collectQueueStatistics(multipartType);
153             case OFPMPGROUPDESC:
154                 return collectGroupDescStatistics(multipartType);
155             case OFPMPGROUP:
156                 return collectGroupStatistics(multipartType);
157             case OFPMPMETERCONFIG:
158                 return collectMeterConfigStatistics(multipartType);
159             case OFPMPMETER:
160                 return collectMeterStatistics(multipartType);
161             default:
162                 LOG.warn("Unsuported Statistics type {}", multipartType);
163                 return Futures.immediateCheckedFuture(Boolean.TRUE);
164         }
165     }
166
167
168     @Override
169     public <T> RequestContext<T> createRequestContext() {
170         final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceContext.reserveXidForDeviceMessage()) {
171             @Override
172             public void close() {
173                 requestContexts.remove(this);
174             }
175         };
176         requestContexts.add(ret);
177         return ret;
178     }
179
180     @Override
181     public void close() {
182         for (final Iterator<RequestContext<?>> iterator = Iterators.consumingIterator(requestContexts.iterator());
183                 iterator.hasNext();) {
184             RequestContextUtil.closeRequestContextWithRpcError(iterator.next(), CONNECTION_CLOSED);
185         }
186         if (null != pollTimeout && !pollTimeout.isExpired()) {
187             pollTimeout.cancel();
188             }
189         }
190
191     @Override
192     public void setPollTimeout(final Timeout pollTimeout) {
193         this.pollTimeout = pollTimeout;
194     }
195
196     @Override
197     public Optional<Timeout> getPollTimeout() {
198         return Optional.fromNullable(pollTimeout);
199     }
200
201     private void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture) {
202         if (ConnectionContext.CONNECTION_STATE.RIP.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
203             final String errMsg = String.format("Device connection is closed for Node : %s.",
204                     deviceContext.getDeviceState().getNodeId());
205             LOG.debug(errMsg);
206             resultFuture.setException(new IllegalStateException(errMsg));
207             return;
208         }
209         if ( ! iterator.hasNext()) {
210             resultFuture.set(Boolean.TRUE);
211             LOG.debug("Stats collection successfully finished for node {}", deviceContext.getDeviceState().getNodeId());
212             return;
213         }
214
215         final MultipartType nextType = iterator.next();
216         LOG.debug("Stats iterating to next type for node {} of type {}", deviceContext.getDeviceState().getNodeId(), nextType);
217
218         final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType);
219         Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
220             @Override
221             public void onSuccess(final Boolean result) {
222                 statChainFuture(iterator, resultFuture);
223             }
224             @Override
225             public void onFailure(@Nonnull final Throwable t) {
226                 resultFuture.setException(t);
227             }
228         });
229     }
230
231     /**
232      * Method checks a device state. It returns null for be able continue. Otherwise it returns immediateFuture
233      * which has to be returned from caller too
234      *
235      * @return
236      */
237     @VisibleForTesting
238     ListenableFuture<Boolean> deviceConnectionCheck() {
239         if (!ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
240             ListenableFuture<Boolean> resultingFuture = SettableFuture.create();
241             switch (deviceContext.getPrimaryConnectionContext().getConnectionState()) {
242                 case RIP:
243                     final String errMsg = String.format("Device connection doesn't exist anymore. Primary connection status : %s",
244                             deviceContext.getPrimaryConnectionContext().getConnectionState());
245                     resultingFuture = Futures.immediateFailedFuture(new Throwable(errMsg));
246                     break;
247                 default:
248                     resultingFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
249                     break;
250             }
251             return resultingFuture;
252         }
253         return null;
254     }
255
256     private ListenableFuture<Boolean> collectFlowStatistics(final MultipartType multipartType) {
257         return devState.isFlowStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
258                 statisticsGatheringOnTheFlyService, deviceContext, /*MultipartType.OFPMPFLOW*/ multipartType) : emptyFuture;
259     }
260
261     private ListenableFuture<Boolean> collectTableStatistics(final MultipartType multipartType) {
262         return devState.isTableStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
263                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPTABLE*/ multipartType) : emptyFuture;
264     }
265
266     private ListenableFuture<Boolean> collectPortStatistics(final MultipartType multipartType) {
267         return devState.isPortStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
268                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPPORTSTATS*/ multipartType) : emptyFuture;
269     }
270
271     private ListenableFuture<Boolean> collectQueueStatistics(final MultipartType multipartType) {
272         return devState.isQueueStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
273                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPQUEUE*/ multipartType) : emptyFuture;
274     }
275
276     private ListenableFuture<Boolean> collectGroupDescStatistics(final MultipartType multipartType) {
277         return devState.isGroupAvailable() ? StatisticsGatheringUtils.gatherStatistics(
278                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPGROUPDESC*/ multipartType) : emptyFuture;
279     }
280
281     private ListenableFuture<Boolean> collectGroupStatistics(final MultipartType multipartType) {
282         return devState.isGroupAvailable() ? StatisticsGatheringUtils.gatherStatistics(
283                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPGROUP*/ multipartType) : emptyFuture;
284     }
285
286     private ListenableFuture<Boolean> collectMeterConfigStatistics(final MultipartType multipartType) {
287         return devState.isMetersAvailable() ? StatisticsGatheringUtils.gatherStatistics(
288                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPMETERCONFIG*/ multipartType) : emptyFuture;
289     }
290
291     private ListenableFuture<Boolean> collectMeterStatistics(final MultipartType multipartType) {
292         return devState.isMetersAvailable() ? StatisticsGatheringUtils.gatherStatistics(
293                 statisticsGatheringService, deviceContext, /*MultipartType.OFPMPMETER*/ multipartType) : emptyFuture;
294     }
295
296     @VisibleForTesting
297     void setStatisticsGatheringService(final StatisticsGatheringService statisticsGatheringService) {
298         this.statisticsGatheringService = statisticsGatheringService;
299     }
300
301     @VisibleForTesting
302     void setStatisticsGatheringOnTheFlyService(final StatisticsGatheringOnTheFlyService
303                                                              statisticsGatheringOnTheFlyService) {
304         this.statisticsGatheringOnTheFlyService = statisticsGatheringOnTheFlyService;
305     }
306
307     @Override
308     public ItemLifecycleListener getItemLifeCycleListener () {
309         return itemLifeCycleListener;
310     }
311
312
313     @Override
314     public DeviceContext getDeviceContext() {
315         return deviceContext;
316     }
317 }