2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.openflowplugin.impl.statistics;
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;
49 class StatisticsContextImpl<T extends OfHeader> implements StatisticsContext {
51 private static final Logger LOG = LoggerFactory.getLogger(StatisticsContextImpl.class);
52 private static final String CONNECTION_CLOSED = "Connection closed.";
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;
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;
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;
94 statisticsGatheringService = new StatisticsGatheringService<>(this, deviceContext);
95 statisticsGatheringOnTheFlyService = new StatisticsGatheringOnTheFlyService<>(this, deviceContext,
97 statisticsWriterProvider);
101 public DeviceInfo getDeviceInfo() {
102 return this.deviceInfo;
107 public ServiceGroupIdentifier getIdentifier() {
108 return deviceInfo.getServiceIdentifier();
112 public void registerMastershipWatcher(@Nonnull final ContextChainMastershipWatcher newWatcher) {
113 this.contextChainMastershipWatcher = newWatcher;
117 public <O> RequestContext<O> createRequestContext() {
118 final AbstractRequestContext<O> ret = new AbstractRequestContext<O>(deviceInfo.reserveXidForDeviceMessage()) {
120 public void close() {
121 requestContexts.remove(this);
125 requestContexts.add(ret);
130 public void enableGathering() {
131 this.schedulingEnabled.set(true);
135 public void disableGathering() {
136 this.schedulingEnabled.set(false);
140 public void continueInitializationAfterReconciliation() {
141 if (deviceContext.initialSubmitTransaction()) {
142 contextChainMastershipWatcher.onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.INITIAL_SUBMIT);
144 startGatheringData();
146 contextChainMastershipWatcher
147 .onNotAbleToStartMastershipMandatory(deviceInfo, "Initial transaction cannot be submitted.");
152 public void instantiateServiceInstance() {
153 final List<MultipartType> statListForCollecting = new ArrayList<>();
155 if (devState.isTableStatisticsAvailable() && config.isIsTableStatisticsPollingOn()) {
156 statListForCollecting.add(MultipartType.OFPMPTABLE);
159 if (devState.isGroupAvailable() && config.isIsGroupStatisticsPollingOn()) {
160 statListForCollecting.add(MultipartType.OFPMPGROUPDESC);
161 statListForCollecting.add(MultipartType.OFPMPGROUP);
164 if (devState.isMetersAvailable() && config.isIsMeterStatisticsPollingOn()) {
165 statListForCollecting.add(MultipartType.OFPMPMETERCONFIG);
166 statListForCollecting.add(MultipartType.OFPMPMETER);
169 if (devState.isFlowStatisticsAvailable() && config.isIsFlowStatisticsPollingOn()) {
170 statListForCollecting.add(MultipartType.OFPMPFLOW);
173 if (devState.isPortStatisticsAvailable() && config.isIsPortStatisticsPollingOn()) {
174 statListForCollecting.add(MultipartType.OFPMPPORTSTATS);
177 if (devState.isQueueStatisticsAvailable() && config.isIsQueueStatisticsPollingOn()) {
178 statListForCollecting.add(MultipartType.OFPMPQUEUE);
181 collectingStatType = ImmutableList.copyOf(statListForCollecting);
182 Futures.addCallback(gatherDynamicData(), new InitialSubmitCallback(), MoreExecutors.directExecutor());
186 public ListenableFuture<Void> closeServiceInstance() {
187 return stopGatheringData();
191 public void close() {
192 Futures.addCallback(stopGatheringData(), new FutureCallback<Void>() {
194 public void onSuccess(final Void result) {
195 requestContexts.forEach(requestContext -> RequestContextUtil
196 .closeRequestContextWithRpcError(requestContext, CONNECTION_CLOSED));
200 public void onFailure(final Throwable throwable) {
201 requestContexts.forEach(requestContext -> RequestContextUtil
202 .closeRequestContextWithRpcError(requestContext, CONNECTION_CLOSED));
204 }, MoreExecutors.directExecutor());
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);
213 return this.lastDataGatheringRef.updateAndGet(future -> {
214 // write start timestamp to state snapshot container
215 StatisticsGatheringUtils.markDeviceStateSnapshotStart(deviceInfo, deviceContext);
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;
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()));
227 // write end timestamp to state snapshot container
228 Futures.addCallback(newDataGathering, new FutureCallback<Boolean>() {
230 public void onSuccess(final Boolean result) {
231 StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceInfo, deviceContext, result);
235 public void onFailure(final Throwable throwable) {
236 if (!(throwable instanceof TransactionChainClosedException)) {
237 StatisticsGatheringUtils.markDeviceStateSnapshotEnd(deviceInfo, deviceContext, false);
240 }, MoreExecutors.directExecutor());
242 return newDataGathering;
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());
255 return Futures.immediateFailedFuture(new ConnectionException(errMsg));
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);
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());
273 private void startGatheringData() {
274 if (!isStatisticsPollingOn) {
278 LOG.info("Starting statistics gathering for node {}", deviceInfo);
279 final StatisticsPollingService statisticsPollingService =
280 new StatisticsPollingService(timeCounter,
281 statisticsPollingInterval,
283 StatisticsContextImpl.this::gatherDynamicData);
285 schedulingEnabled.set(true);
286 statisticsPollingService.startAsync();
287 this.statisticsPollingServiceRef.set(statisticsPollingService);
290 private ListenableFuture<Void> stopGatheringData() {
291 LOG.info("Stopping running statistics gathering for node {}", deviceInfo);
292 cancelLastDataGathering();
294 return Optional.ofNullable(statisticsPollingServiceRef.getAndSet(null)).map(StatisticsPollingService::stop)
295 .orElseGet(() -> Futures.immediateFuture(null));
298 private void cancelLastDataGathering() {
299 final ListenableFuture<Boolean> future = lastDataGatheringRef.getAndSet(null);
301 if (future != null && !future.isDone() && !future.isCancelled()) {
307 void setStatisticsGatheringService(final StatisticsGatheringService<T> statisticsGatheringService) {
308 this.statisticsGatheringService = statisticsGatheringService;
312 void setStatisticsGatheringOnTheFlyService(
313 final StatisticsGatheringOnTheFlyService<T> statisticsGatheringOnTheFlyService) {
314 this.statisticsGatheringOnTheFlyService = statisticsGatheringOnTheFlyService;
317 private final class InitialSubmitCallback implements FutureCallback<Boolean> {
319 public void onSuccess(final Boolean result) {
320 contextChainMastershipWatcher
321 .onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.INITIAL_GATHERING);
323 if (!isUsingReconciliationFramework) {
324 continueInitializationAfterReconciliation();
329 public void onFailure(final Throwable throwable) {
330 contextChainMastershipWatcher.onNotAbleToStartMastershipMandatory(deviceInfo,
331 "Initial gathering statistics "
333 + throwable.getMessage());