Bump odlparent to 5.0.0
[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 package org.opendaylight.openflowplugin.impl.statistics;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
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 com.google.common.util.concurrent.ListeningExecutorService;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.List;
21 import java.util.Optional;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import java.util.concurrent.atomic.AtomicReference;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.mdsal.binding.api.TransactionChainClosedException;
27 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
28 import org.opendaylight.openflowplugin.api.ConnectionException;
29 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
30 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
31 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
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.ContextChainMastershipState;
35 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipWatcher;
36 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
37 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
38 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
39 import org.opendaylight.openflowplugin.impl.services.util.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.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfig;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 class StatisticsContextImpl<T extends OfHeader> implements StatisticsContext {
50
51     private static final Logger LOG = LoggerFactory.getLogger(StatisticsContextImpl.class);
52     private static final String CONNECTION_CLOSED = "Connection closed.";
53
54     private final Collection<RequestContext<?>> requestContexts = ConcurrentHashMap.newKeySet();
55     private final DeviceContext deviceContext;
56     private final DeviceState devState;
57     private final ListeningExecutorService executorService;
58     private final boolean isStatisticsPollingOn;
59     private final ConvertorExecutor convertorExecutor;
60     private final MultipartWriterProvider statisticsWriterProvider;
61     private final DeviceInfo deviceInfo;
62     private final TimeCounter timeCounter = new TimeCounter();
63     private final OpenflowProviderConfig config;
64     private final long statisticsPollingInterval;
65     private final long maximumPollingDelay;
66     private final boolean isUsingReconciliationFramework;
67     private final AtomicBoolean schedulingEnabled = new AtomicBoolean(true);
68     private final AtomicReference<ListenableFuture<Boolean>> lastDataGatheringRef = new AtomicReference<>();
69     private final AtomicReference<StatisticsPollingService> statisticsPollingServiceRef = new AtomicReference<>();
70     private List<MultipartType> collectingStatType;
71     private StatisticsGatheringService<T> statisticsGatheringService;
72     private StatisticsGatheringOnTheFlyService<T> statisticsGatheringOnTheFlyService;
73     private ContextChainMastershipWatcher contextChainMastershipWatcher;
74
75     StatisticsContextImpl(@Nonnull final DeviceContext deviceContext,
76                           @Nonnull final ConvertorExecutor convertorExecutor,
77                           @Nonnull final MultipartWriterProvider statisticsWriterProvider,
78                           @Nonnull final ListeningExecutorService executorService,
79                           @Nonnull final OpenflowProviderConfig config,
80                           boolean isStatisticsPollingOn,
81                           boolean isUsingReconciliationFramework) {
82         this.deviceContext = deviceContext;
83         this.devState = Preconditions.checkNotNull(deviceContext.getDeviceState());
84         this.executorService = executorService;
85         this.isStatisticsPollingOn = isStatisticsPollingOn;
86         this.config = config;
87         this.convertorExecutor = convertorExecutor;
88         this.deviceInfo = deviceContext.getDeviceInfo();
89         this.statisticsPollingInterval = config.getBasicTimerDelay().getValue();
90         this.maximumPollingDelay = config.getMaximumTimerDelay().getValue();
91         this.statisticsWriterProvider = statisticsWriterProvider;
92         this.isUsingReconciliationFramework = isUsingReconciliationFramework;
93
94         statisticsGatheringService = new StatisticsGatheringService<>(this, deviceContext);
95         statisticsGatheringOnTheFlyService = new StatisticsGatheringOnTheFlyService<>(this, deviceContext,
96                                                                                       convertorExecutor,
97                                                                                       statisticsWriterProvider);
98     }
99
100     @Override
101     public DeviceInfo getDeviceInfo() {
102         return this.deviceInfo;
103     }
104
105     @Nonnull
106     @Override
107     public ServiceGroupIdentifier getIdentifier() {
108         return deviceInfo.getServiceIdentifier();
109     }
110
111     @Override
112     public void registerMastershipWatcher(@Nonnull final ContextChainMastershipWatcher newWatcher) {
113         this.contextChainMastershipWatcher = newWatcher;
114     }
115
116     @Override
117     public <O> RequestContext<O> createRequestContext() {
118         final AbstractRequestContext<O> ret = new AbstractRequestContext<O>(deviceInfo.reserveXidForDeviceMessage()) {
119             @Override
120             public void close() {
121                 requestContexts.remove(this);
122             }
123         };
124
125         requestContexts.add(ret);
126         return ret;
127     }
128
129     @Override
130     public void enableGathering() {
131         this.schedulingEnabled.set(true);
132     }
133
134     @Override
135     public void disableGathering() {
136         this.schedulingEnabled.set(false);
137     }
138
139     @Override
140     public void continueInitializationAfterReconciliation() {
141         if (deviceContext.initialSubmitTransaction()) {
142             contextChainMastershipWatcher.onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.INITIAL_SUBMIT);
143
144             startGatheringData();
145         } else {
146             contextChainMastershipWatcher
147                     .onNotAbleToStartMastershipMandatory(deviceInfo, "Initial transaction cannot be submitted.");
148         }
149     }
150
151     @Override
152     public void instantiateServiceInstance() {
153         final List<MultipartType> statListForCollecting = new ArrayList<>();
154
155         if (devState.isTableStatisticsAvailable() && config.isIsTableStatisticsPollingOn()) {
156             statListForCollecting.add(MultipartType.OFPMPTABLE);
157         }
158
159         if (devState.isGroupAvailable() && config.isIsGroupStatisticsPollingOn()) {
160             statListForCollecting.add(MultipartType.OFPMPGROUPDESC);
161             statListForCollecting.add(MultipartType.OFPMPGROUP);
162         }
163
164         if (devState.isMetersAvailable() && config.isIsMeterStatisticsPollingOn()) {
165             statListForCollecting.add(MultipartType.OFPMPMETERCONFIG);
166             statListForCollecting.add(MultipartType.OFPMPMETER);
167         }
168
169         if (devState.isFlowStatisticsAvailable() && config.isIsFlowStatisticsPollingOn()) {
170             statListForCollecting.add(MultipartType.OFPMPFLOW);
171         }
172
173         if (devState.isPortStatisticsAvailable() && config.isIsPortStatisticsPollingOn()) {
174             statListForCollecting.add(MultipartType.OFPMPPORTSTATS);
175         }
176
177         if (devState.isQueueStatisticsAvailable() && config.isIsQueueStatisticsPollingOn()) {
178             statListForCollecting.add(MultipartType.OFPMPQUEUE);
179         }
180
181         collectingStatType = ImmutableList.copyOf(statListForCollecting);
182         Futures.addCallback(gatherDynamicData(), new InitialSubmitCallback(), MoreExecutors.directExecutor());
183     }
184
185     @Override
186     public ListenableFuture<Void> closeServiceInstance() {
187         return stopGatheringData();
188     }
189
190     @Override
191     public void close() {
192         Futures.addCallback(stopGatheringData(), new FutureCallback<Void>() {
193             @Override
194             public void onSuccess(final Void result) {
195                 requestContexts.forEach(requestContext -> RequestContextUtil
196                         .closeRequestContextWithRpcError(requestContext, CONNECTION_CLOSED));
197             }
198
199             @Override
200             public void onFailure(final Throwable throwable) {
201                 requestContexts.forEach(requestContext -> RequestContextUtil
202                         .closeRequestContextWithRpcError(requestContext, CONNECTION_CLOSED));
203             }
204         }, MoreExecutors.directExecutor());
205     }
206
207     private ListenableFuture<Boolean> gatherDynamicData() {
208         if (!isStatisticsPollingOn || !schedulingEnabled.get()) {
209             LOG.debug("Statistics for device {} are not enabled.", getDeviceInfo().getNodeId().getValue());
210             return Futures.immediateFuture(Boolean.TRUE);
211         }
212
213         return this.lastDataGatheringRef.updateAndGet(future -> {
214             // write start timestamp to state snapshot container
215             StatisticsGatheringUtils.markDeviceStateSnapshotStart(deviceInfo, deviceContext);
216
217             // recreate gathering future if it should be recreated
218             final ListenableFuture<Boolean> lastDataGathering = future == null || future.isCancelled()
219                     || future.isDone() ? Futures.immediateFuture(Boolean.TRUE) : future;
220
221             // build statistics gathering future
222             final ListenableFuture<Boolean> newDataGathering = collectingStatType.stream()
223                     .reduce(lastDataGathering, this::statChainFuture,
224                         (listenableFuture, asyn) -> Futures.transformAsync(listenableFuture, result -> asyn,
225                                 MoreExecutors.directExecutor()));
226
227             // write end timestamp to state snapshot container
228             Futures.addCallback(newDataGathering, new FutureCallback<Boolean>() {
229                 @Override
230                 public void onSuccess(final Boolean result) {
231                     StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceInfo, deviceContext, result);
232                 }
233
234                 @Override
235                 public void onFailure(final Throwable throwable) {
236                     if (!(throwable instanceof TransactionChainClosedException)) {
237                         StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceInfo, deviceContext, false);
238                     }
239                 }
240             }, MoreExecutors.directExecutor());
241
242             return newDataGathering;
243         });
244     }
245
246     private ListenableFuture<Boolean> statChainFuture(final ListenableFuture<Boolean> prevFuture,
247                                                       final MultipartType multipartType) {
248         if (ConnectionContext.CONNECTION_STATE.RIP
249                 .equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
250             final String errMsg = String
251                     .format("Device connection for node %s doesn't exist anymore. Primary connection status : %s",
252                             getDeviceInfo().getNodeId(),
253                             deviceContext.getPrimaryConnectionContext().getConnectionState());
254
255             return Futures.immediateFailedFuture(new ConnectionException(errMsg));
256         }
257
258         return Futures.transformAsync(prevFuture, result -> {
259             LOG.debug("Status of previous stat iteration for node {}: {}", deviceInfo, result);
260             LOG.debug("Stats iterating to next type for node {} of type {}", deviceInfo, multipartType);
261             final boolean onTheFly = MultipartType.OFPMPFLOW.equals(multipartType);
262             final boolean supported = collectingStatType.contains(multipartType);
263
264             // TODO: Refactor twice sending deviceContext into gatheringStatistics
265             return supported ? StatisticsGatheringUtils
266                     .gatherStatistics(onTheFly ? statisticsGatheringOnTheFlyService : statisticsGatheringService,
267                                       getDeviceInfo(), multipartType, deviceContext, deviceContext, convertorExecutor,
268                                       statisticsWriterProvider, executorService) : Futures
269                     .immediateFuture(Boolean.FALSE);
270         }, MoreExecutors.directExecutor());
271     }
272
273     private void startGatheringData() {
274         if (!isStatisticsPollingOn) {
275             return;
276         }
277
278         LOG.info("Starting statistics gathering for node {}", deviceInfo);
279         final StatisticsPollingService statisticsPollingService =
280                 new StatisticsPollingService(timeCounter,
281                                              statisticsPollingInterval,
282                                              maximumPollingDelay,
283                                              StatisticsContextImpl.this::gatherDynamicData);
284
285         schedulingEnabled.set(true);
286         statisticsPollingService.startAsync();
287         this.statisticsPollingServiceRef.set(statisticsPollingService);
288     }
289
290     private ListenableFuture<Void> stopGatheringData() {
291         LOG.info("Stopping running statistics gathering for node {}", deviceInfo);
292         cancelLastDataGathering();
293
294         return Optional.ofNullable(statisticsPollingServiceRef.getAndSet(null)).map(StatisticsPollingService::stop)
295                 .orElseGet(() -> Futures.immediateFuture(null));
296     }
297
298     private void cancelLastDataGathering() {
299         final ListenableFuture<Boolean> future = lastDataGatheringRef.getAndSet(null);
300
301         if (future != null && !future.isDone() && !future.isCancelled()) {
302             future.cancel(true);
303         }
304     }
305
306     @VisibleForTesting
307     void setStatisticsGatheringService(final StatisticsGatheringService<T> statisticsGatheringService) {
308         this.statisticsGatheringService = statisticsGatheringService;
309     }
310
311     @VisibleForTesting
312     void setStatisticsGatheringOnTheFlyService(
313             final StatisticsGatheringOnTheFlyService<T> statisticsGatheringOnTheFlyService) {
314         this.statisticsGatheringOnTheFlyService = statisticsGatheringOnTheFlyService;
315     }
316
317     private final class InitialSubmitCallback implements FutureCallback<Boolean> {
318         @Override
319         public void onSuccess(final Boolean result) {
320             contextChainMastershipWatcher
321                     .onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.INITIAL_GATHERING);
322
323             if (!isUsingReconciliationFramework) {
324                 continueInitializationAfterReconciliation();
325             }
326         }
327
328         @Override
329         public void onFailure(final Throwable throwable) {
330             contextChainMastershipWatcher.onNotAbleToStartMastershipMandatory(deviceInfo,
331                                                                               "Initial gathering statistics "
332                                                                                       + "unsuccessful: "
333                                                                                       + throwable.getMessage());
334         }
335     }
336 }