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.base.Function;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.ListeningExecutorService;
14 import com.google.common.util.concurrent.MoreExecutors;
15 import java.text.SimpleDateFormat;
16 import java.util.Collections;
17 import java.util.Date;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.Optional;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.stream.Collectors;
24 import org.opendaylight.mdsal.binding.api.ReadTransaction;
25 import org.opendaylight.mdsal.binding.api.TransactionChainClosedException;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
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());
103 }), MoreExecutors.directExecutor());
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());
116 deviceRegistry.getDeviceFlowRegistry().processMarks();
118 case OFPMPMETERCONFIG:
119 deleteAllKnownMeters(txFacade, instanceIdentifier, deviceRegistry.getDeviceMeterRegistry());
120 deviceRegistry.getDeviceMeterRegistry().processMarks();
123 deleteAllKnownGroups(txFacade, instanceIdentifier, deviceRegistry.getDeviceGroupRegistry());
124 deviceRegistry.getDeviceGroupRegistry().processMarks();
130 if (writeStatistics(type, statistics, deviceInfo, statisticsWriterProvider)) {
131 txFacade.submitTransaction();
133 LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
137 LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo);
141 @SuppressWarnings("checkstyle:IllegalCatch")
142 private static boolean writeStatistics(final MultipartType type, final List<? extends DataContainer> statistics,
143 final DeviceInfo deviceInfo,
144 final MultipartWriterProvider statisticsWriterProvider) {
145 final AtomicBoolean result = new AtomicBoolean(false);
148 statistics.forEach(stat -> statisticsWriterProvider.lookup(type).ifPresent(p -> {
149 final boolean write = p.write(stat, false);
155 } catch (final Exception ex) {
156 LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo,
163 public static void deleteAllKnownFlows(final TxFacade txFacade,
164 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
165 final DeviceFlowRegistry deviceFlowRegistry) {
166 if (!txFacade.isTransactionsEnabled()) {
170 final ListenableFuture<Optional<FlowCapableNode>> future;
171 try (ReadTransaction readTx = txFacade.getReadTransaction()) {
172 future = readTx.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
176 Futures.transform(Futures.catchingAsync(future, Throwable.class, Futures::immediateFailedFuture,
177 MoreExecutors.directExecutor()), (Function<Optional<FlowCapableNode>, Void>) flowCapNodeOpt -> {
178 // we have to read actual tables with all information before we set empty Flow list,
179 // merge is expensive and not applicable for lists
180 if (flowCapNodeOpt != null && flowCapNodeOpt.isPresent()) {
181 for (final Table tableData : flowCapNodeOpt.get().getTable()) {
182 final Table table = new TableBuilder(tableData).setFlow(Collections.emptyList()).build();
183 final InstanceIdentifier<Table> iiToTable = instanceIdentifier
184 .child(Table.class, tableData.key());
185 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
189 }, MoreExecutors.directExecutor()).get();
190 } catch (InterruptedException | ExecutionException ex) {
191 LOG.debug("Failed to delete {} flows", deviceFlowRegistry.size(), ex);
195 public static void deleteAllKnownMeters(final TxFacade txFacade,
196 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
197 final DeviceMeterRegistry meterRegistry) {
198 meterRegistry.forEach(meterId -> {
201 LogicalDatastoreType.OPERATIONAL,
202 instanceIdentifier.child(Meter.class, new MeterKey(meterId)));
203 meterRegistry.addMark(meterId);
207 public static void deleteAllKnownGroups(final TxFacade txFacade,
208 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
209 final DeviceGroupRegistry groupRegistry) {
210 LOG.debug("deleteAllKnownGroups on device targetType {}", instanceIdentifier.getTargetType());
211 groupRegistry.forEach(groupId -> {
214 LogicalDatastoreType.OPERATIONAL,
215 instanceIdentifier.child(Group.class, new GroupKey(groupId)));
216 groupRegistry.addMark(groupId);
221 * Writes snapshot gathering start timestamp + cleans end mark.
223 * @param deviceInfo device info
224 * @param txFacade tx manager
226 static void markDeviceStateSnapshotStart(final DeviceInfo deviceInfo, final TxFacade txFacade) {
227 final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceInfo
228 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
230 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
231 final FlowCapableStatisticsGatheringStatus gatheringStatus = new FlowCapableStatisticsGatheringStatusBuilder()
232 .setSnapshotGatheringStatusStart(new SnapshotGatheringStatusStartBuilder()
233 .setBegin(new DateAndTime(simpleDateFormat.format(new Date())))
235 .setSnapshotGatheringStatusEnd(null) // TODO: reconsider if really need to clean end mark here
238 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusPath, gatheringStatus);
239 } catch (final TransactionChainClosedException e) {
240 LOG.warn("Can't write to transaction, transaction chain probably closed.");
241 LOG.trace("Write to transaction exception: ", e);
244 txFacade.submitTransaction();
248 * Writes snapshot gathering end timestamp + outcome.
250 * @param deviceInfo device info
251 * @param txFacade tx manager
252 * @param succeeded outcome of currently finished gathering
254 static void markDeviceStateSnapshotEnd(final DeviceInfo deviceInfo,
255 final TxFacade txFacade, final boolean succeeded) {
256 final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceInfo
257 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class)
258 .child(SnapshotGatheringStatusEnd.class);
260 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
261 final SnapshotGatheringStatusEnd gatheringStatus = new SnapshotGatheringStatusEndBuilder()
262 .setEnd(new DateAndTime(simpleDateFormat.format(new Date())))
263 .setSucceeded(succeeded)
266 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusEndPath, gatheringStatus);
267 } catch (TransactionChainClosedException e) {
268 LOG.warn("Can't write to transaction, transaction chain probably closed.");
269 LOG.trace("Write to transaction exception: ", e);
272 txFacade.submitTransaction();