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