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.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ListeningExecutorService;
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 org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
27 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
28 import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
29 import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
30 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
31 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
32 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
33 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
34 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.StatisticsGatherer;
35 import org.opendaylight.openflowplugin.impl.common.MultipartReplyTranslatorUtil;
36 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
37 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatusBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEndBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusStartBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
53 import org.opendaylight.yangtools.yang.binding.DataContainer;
54 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Utils for gathering statistics.
61 public final class StatisticsGatheringUtils {
63 private static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
64 private static final Logger LOG = LoggerFactory.getLogger(StatisticsGatheringUtils.class);
65 private static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
67 private StatisticsGatheringUtils() {
68 throw new IllegalStateException("This class should not be instantiated.");
71 static <T extends OfHeader> ListenableFuture<Boolean> gatherStatistics(
72 final StatisticsGatherer<T> statisticsGatheringService, final DeviceInfo deviceInfo,
73 final MultipartType type, final TxFacade txFacade, final DeviceRegistry registry,
74 final ConvertorExecutor convertorExecutor, final MultipartWriterProvider statisticsWriterProvider,
75 final ListeningExecutorService executorService) {
76 return Futures.transformAsync(statisticsGatheringService.getStatisticsOfType(
77 new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString()), type),
78 rpcResult -> executorService.submit(() -> {
79 final boolean rpcResultIsNull = rpcResult == null;
81 if (!rpcResultIsNull && rpcResult.isSuccessful()) {
82 LOG.debug("Stats reply successfully received for node {} of type {}", deviceInfo.getNodeId(), type);
83 // TODO: in case the result value is null then multipart data probably got processed
84 // TODO: on the fly. This contract should by clearly stated and enforced.
85 // TODO: Now simple true value is returned
86 if (Objects.nonNull(rpcResult.getResult()) && !rpcResult.getResult().isEmpty()) {
87 final List<DataContainer> allMultipartData = rpcResult.getResult().stream()
88 .map(reply -> MultipartReplyTranslatorUtil
89 .translate(reply, deviceInfo, convertorExecutor, null))
90 .filter(java.util.Optional::isPresent).map(java.util.Optional::get)
91 .collect(Collectors.toList());
93 return processStatistics(type, allMultipartData, txFacade, registry, deviceInfo,
94 statisticsWriterProvider);
96 LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
99 LOG.warn("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type,
100 rpcResultIsNull ? "" : rpcResult.getErrors());
106 private static boolean processStatistics(final MultipartType type, final List<? extends DataContainer> statistics,
107 final TxFacade txFacade, final DeviceRegistry deviceRegistry,
108 final DeviceInfo deviceInfo,
109 final MultipartWriterProvider statisticsWriterProvider) {
110 final InstanceIdentifier<FlowCapableNode> instanceIdentifier = deviceInfo.getNodeInstanceIdentifier()
111 .augmentation(FlowCapableNode.class);
115 deleteAllKnownFlows(txFacade, instanceIdentifier, deviceRegistry.getDeviceFlowRegistry());
117 case OFPMPMETERCONFIG:
118 deleteAllKnownMeters(txFacade, instanceIdentifier, deviceRegistry.getDeviceMeterRegistry());
121 deleteAllKnownGroups(txFacade, instanceIdentifier, deviceRegistry.getDeviceGroupRegistry());
127 if (writeStatistics(type, statistics, deviceInfo, statisticsWriterProvider)) {
128 txFacade.submitTransaction();
132 deviceRegistry.getDeviceFlowRegistry().processMarks();
134 case OFPMPMETERCONFIG:
135 deviceRegistry.getDeviceMeterRegistry().processMarks();
138 deviceRegistry.getDeviceGroupRegistry().processMarks();
144 LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
148 LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo);
152 @SuppressWarnings("checkstyle:IllegalCatch")
153 private static boolean writeStatistics(final MultipartType type, final List<? extends DataContainer> statistics,
154 final DeviceInfo deviceInfo,
155 final MultipartWriterProvider statisticsWriterProvider) {
156 final AtomicBoolean result = new AtomicBoolean(false);
159 statistics.forEach(stat -> statisticsWriterProvider.lookup(type).ifPresent(p -> {
160 final boolean write = p.write(stat, false);
166 } catch (final Exception ex) {
167 LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo,
174 public static void deleteAllKnownFlows(final TxFacade txFacade,
175 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
176 final DeviceFlowRegistry deviceFlowRegistry) {
177 if (!txFacade.isTransactionsEnabled()) {
181 final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
184 Futures.transform(Futures.catchingAsync(readTx.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier),
185 Throwable.class, throwable -> {
186 // we wish to close readTx for fallBack
188 return Futures.immediateFailedFuture(throwable);
189 }), (Function<Optional<FlowCapableNode>, Void>) flowCapNodeOpt -> {
190 // we have to read actual tables with all information before we set empty Flow list,
191 // merge is expensive and not applicable for lists
192 if (flowCapNodeOpt != null && flowCapNodeOpt.isPresent()) {
193 for (final Table tableData : flowCapNodeOpt.get().getTable()) {
194 final Table table = new TableBuilder(tableData).setFlow(Collections.emptyList()).build();
195 final InstanceIdentifier<Table> iiToTable = instanceIdentifier
196 .child(Table.class, tableData.getKey());
197 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
203 } catch (InterruptedException | ExecutionException ex) {
204 LOG.debug("Failed to delete {} flows, exception: {}", deviceFlowRegistry.size(), ex);
208 public static void deleteAllKnownMeters(final TxFacade txFacade,
209 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
210 final DeviceMeterRegistry meterRegistry) {
211 meterRegistry.forEach(meterId -> txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL,
212 instanceIdentifier.child(Meter.class,
213 new MeterKey(meterId))));
216 public static void deleteAllKnownGroups(final TxFacade txFacade,
217 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
218 final DeviceGroupRegistry groupRegistry) {
219 groupRegistry.forEach(groupId -> txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL,
220 instanceIdentifier.child(Group.class,
221 new GroupKey(groupId))));
225 * Writes snapshot gathering start timestamp + cleans end mark.
227 * @param deviceInfo device info
228 * @param txFacade tx manager
230 static void markDeviceStateSnapshotStart(final DeviceInfo deviceInfo, final TxFacade txFacade) {
231 final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceInfo
232 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
234 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
235 final FlowCapableStatisticsGatheringStatus gatheringStatus = new FlowCapableStatisticsGatheringStatusBuilder()
236 .setSnapshotGatheringStatusStart(new SnapshotGatheringStatusStartBuilder()
237 .setBegin(new DateAndTime(simpleDateFormat.format(new Date())))
239 .setSnapshotGatheringStatusEnd(null) // TODO: reconsider if really need to clean end mark here
242 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusPath, gatheringStatus);
243 } catch (final TransactionChainClosedException e) {
244 LOG.warn("Can't write to transaction, transaction chain probably closed.");
245 LOG.trace("Write to transaction exception: ", e);
248 txFacade.submitTransaction();
252 * Writes snapshot gathering end timestamp + outcome.
254 * @param deviceInfo device info
255 * @param txFacade tx manager
256 * @param succeeded outcome of currently finished gathering
258 static void markDeviceStateSnapshotEnd(final DeviceInfo deviceInfo, final TxFacade txFacade,
259 final boolean succeeded) {
260 final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceInfo.getNodeInstanceIdentifier()
261 .augmentation(FlowCapableStatisticsGatheringStatus.class).child(SnapshotGatheringStatusEnd.class);
263 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
264 final SnapshotGatheringStatusEnd gatheringStatus = new SnapshotGatheringStatusEndBuilder()
265 .setEnd(new DateAndTime(simpleDateFormat.format(new Date()))).setSucceeded(succeeded).build();
267 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusEndPath, gatheringStatus);
268 } catch (TransactionChainClosedException e) {
269 LOG.warn("Can't write to transaction, transaction chain probably closed.");
270 LOG.trace("Write to transaction exception: ", e);
273 txFacade.submitTransaction();