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