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
9 package org.opendaylight.openflowplugin.impl.statistics;
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.AsyncFunction;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.text.SimpleDateFormat;
17 import java.util.Collections;
18 import java.util.Date;
19 import java.util.List;
20 import java.util.Objects;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.stream.Collectors;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
30 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
31 import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
32 import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
33 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
34 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
35 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
36 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
37 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.StatisticsGatherer;
38 import org.opendaylight.openflowplugin.impl.common.MultipartReplyTranslatorUtil;
39 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
40 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatusBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEndBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusStartBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
56 import org.opendaylight.yangtools.yang.binding.DataContainer;
57 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * Utils for gathering statistics.
65 public final class StatisticsGatheringUtils {
67 private static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
68 private static final Logger LOG = LoggerFactory.getLogger(StatisticsGatheringUtils.class);
69 private static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
71 private StatisticsGatheringUtils() {
72 throw new IllegalStateException("This class should not be instantiated.");
75 static <T extends OfHeader> ListenableFuture<Boolean> gatherStatistics(
76 final StatisticsGatherer<T> statisticsGatheringService,
77 final DeviceInfo deviceInfo,
78 final MultipartType type,
79 final TxFacade txFacade,
80 final DeviceRegistry registry,
81 final ConvertorExecutor convertorExecutor,
82 final MultipartWriterProvider statisticsWriterProvider) {
83 return Futures.transformAsync(
84 statisticsGatheringService.getStatisticsOfType(
85 new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString()),
87 new AsyncFunction<RpcResult<List<T>>, Boolean>() {
90 @SuppressWarnings("checkstyle:IllegalCatch")
91 public ListenableFuture<Boolean> apply(@Nonnull final RpcResult<List<T>> rpcResult) {
92 boolean isMultipartProcessed = Boolean.TRUE;
94 if (rpcResult.isSuccessful()) {
95 LOG.debug("Stats reply successfully received for node {} of type {}",
96 deviceInfo.getNodeId(), type);
98 // TODO: in case the result value is null then multipart data probably got processed
99 // TODO: on the fly. This contract should by clearly stated and enforced.
100 // TODO: Now simple true value is returned
101 if (Objects.nonNull(rpcResult.getResult()) && !rpcResult.getResult().isEmpty()) {
102 final List<DataContainer> allMultipartData;
105 allMultipartData = rpcResult
108 .map(reply -> MultipartReplyTranslatorUtil
109 .translate(reply, deviceInfo, convertorExecutor, null))
110 .filter(java.util.Optional::isPresent)
111 .map(java.util.Optional::get)
112 .collect(Collectors.toList());
113 } catch (final Exception e) {
114 LOG.warn("Stats processing of type {} for node {} "
115 + "failed during transformation step",
116 type, deviceInfo.getLOGValue(), e);
117 return Futures.immediateFailedFuture(e);
121 return Futures.immediateFuture(processStatistics(
127 statisticsWriterProvider));
128 } catch (final Exception e) {
129 LOG.warn("Stats processing of type {} for node {} failed during processing step",
130 type, deviceInfo.getNodeId(), e);
131 return Futures.immediateFailedFuture(e);
134 LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
137 LOG.warn("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type,
138 rpcResult.getErrors());
139 isMultipartProcessed = Boolean.FALSE;
142 return Futures.immediateFuture(isMultipartProcessed);
147 private static boolean processStatistics(final MultipartType type,
148 final List<? extends DataContainer> statistics,
149 final TxFacade txFacade,
150 final DeviceRegistry deviceRegistry,
151 final DeviceInfo deviceInfo,
152 final MultipartWriterProvider statisticsWriterProvider) {
153 final InstanceIdentifier<FlowCapableNode> instanceIdentifier = deviceInfo
154 .getNodeInstanceIdentifier()
155 .augmentation(FlowCapableNode.class);
159 deleteAllKnownFlows(txFacade, instanceIdentifier, deviceRegistry.getDeviceFlowRegistry());
161 case OFPMPMETERCONFIG:
162 deleteAllKnownMeters(txFacade, instanceIdentifier, deviceRegistry.getDeviceMeterRegistry());
165 deleteAllKnownGroups(txFacade, instanceIdentifier, deviceRegistry.getDeviceGroupRegistry());
171 if (writeStatistics(type, statistics, deviceInfo, statisticsWriterProvider)) {
172 txFacade.submitTransaction();
176 deviceRegistry.getDeviceFlowRegistry().processMarks();
178 case OFPMPMETERCONFIG:
179 deviceRegistry.getDeviceMeterRegistry().processMarks();
182 deviceRegistry.getDeviceGroupRegistry().processMarks();
188 LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
192 LOG.warn("Stats processing of type {} for node {} "
193 + "failed during write-to-tx step", type, deviceInfo.getLOGValue());
197 @SuppressWarnings("checkstyle:IllegalCatch")
198 private static boolean writeStatistics(final MultipartType type,
199 final List<? extends DataContainer> statistics,
200 final DeviceInfo deviceInfo,
201 final MultipartWriterProvider statisticsWriterProvider) {
202 final AtomicBoolean result = new AtomicBoolean(false);
205 statistics.forEach(stat -> statisticsWriterProvider.lookup(type).ifPresent(p -> {
206 final boolean write = p.write(stat, false);
212 } catch (final Exception ex) {
213 LOG.warn("Stats processing of type {} for node {} "
214 + "failed during write-to-tx step", type, deviceInfo.getLOGValue(), ex);
220 public static void deleteAllKnownFlows(final TxFacade txFacade,
221 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
222 final DeviceFlowRegistry deviceFlowRegistry) {
223 if (!txFacade.isTransactionsEnabled()) {
227 final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
230 Futures.transform(Futures
231 .catchingAsync(readTx.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier), Throwable.class,
233 // we wish to close readTx for fallBack
235 return Futures.immediateFailedFuture(t);
236 }), (Function<Optional<FlowCapableNode>, Void>)
238 // we have to read actual tables with all information before we set empty Flow list,
239 // merge is expensive and not applicable for lists
240 if (flowCapNodeOpt != null && flowCapNodeOpt.isPresent()) {
241 for (final Table tableData : flowCapNodeOpt.get().getTable()) {
243 new TableBuilder(tableData).setFlow(Collections.emptyList()).build();
244 final InstanceIdentifier<Table> iiToTable =
245 instanceIdentifier.child(Table.class, tableData.getKey());
246 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
253 } catch (InterruptedException | ExecutionException ex) {
254 LOG.debug("Failed to delete {} flows, exception: {}", deviceFlowRegistry.size(), ex);
258 public static void deleteAllKnownMeters(final TxFacade txFacade,
259 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
260 final DeviceMeterRegistry meterRegistry) {
261 meterRegistry.forEach(meterId -> txFacade
263 LogicalDatastoreType.OPERATIONAL,
264 instanceIdentifier.child(Meter.class, new MeterKey(meterId))));
267 public static void deleteAllKnownGroups(final TxFacade txFacade,
268 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
269 final DeviceGroupRegistry groupRegistry) {
270 groupRegistry.forEach(groupId -> txFacade
272 LogicalDatastoreType.OPERATIONAL,
273 instanceIdentifier.child(Group.class, new GroupKey(groupId))));
277 * Writes snapshot gathering start timestamp + cleans end mark.
279 * @param deviceContext txManager + node path keeper
281 static void markDeviceStateSnapshotStart(final DeviceContext deviceContext) {
282 final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceContext.getDeviceInfo()
283 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
285 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
286 final FlowCapableStatisticsGatheringStatus gatheringStatus = new FlowCapableStatisticsGatheringStatusBuilder()
287 .setSnapshotGatheringStatusStart(new SnapshotGatheringStatusStartBuilder()
288 .setBegin(new DateAndTime(simpleDateFormat.format(new Date())))
290 .setSnapshotGatheringStatusEnd(null) // TODO: reconsider if really need to clean end mark here
293 deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusPath, gatheringStatus);
294 } catch (final TransactionChainClosedException e) {
295 LOG.warn("Can't write to transaction, transaction chain probably closed.");
296 LOG.trace("Write to transaction exception: ", e);
299 deviceContext.submitTransaction();
303 * Writes snapshot gathering end timestamp + outcome.
305 * @param deviceContext txManager + node path keeper
306 * @param succeeded outcome of currently finished gathering
308 static void markDeviceStateSnapshotEnd(final DeviceContext deviceContext, final boolean succeeded) {
309 final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceContext.getDeviceInfo()
310 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class)
311 .child(SnapshotGatheringStatusEnd.class);
313 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
314 final SnapshotGatheringStatusEnd gatheringStatus = new SnapshotGatheringStatusEndBuilder()
315 .setEnd(new DateAndTime(simpleDateFormat.format(new Date())))
316 .setSucceeded(succeeded)
319 deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusEndPath, gatheringStatus);
320 } catch (TransactionChainClosedException e) {
321 LOG.warn("Can't write to transaction, transaction chain probably closed.");
322 LOG.trace("Write to transaction exception: ", e);
325 deviceContext.submitTransaction();