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 com.google.common.util.concurrent.MoreExecutors;
17 import java.text.SimpleDateFormat;
18 import java.util.Collections;
19 import java.util.Date;
20 import java.util.List;
21 import java.util.Objects;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import java.util.stream.Collectors;
25 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
28 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
30 import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
31 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
32 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
33 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
34 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
35 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.StatisticsGatherer;
36 import org.opendaylight.openflowplugin.impl.common.MultipartReplyTranslatorUtil;
37 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
38 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatusBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEndBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusStartBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
54 import org.opendaylight.yangtools.yang.binding.DataContainer;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
60 * Utils for gathering statistics.
62 public final class StatisticsGatheringUtils {
64 private static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
65 private static final Logger LOG = LoggerFactory.getLogger(StatisticsGatheringUtils.class);
66 private static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
68 private StatisticsGatheringUtils() {
69 throw new IllegalStateException("This class should not be instantiated.");
72 static <T extends OfHeader> ListenableFuture<Boolean> gatherStatistics(
73 final StatisticsGatherer<T> statisticsGatheringService, final DeviceInfo deviceInfo,
74 final MultipartType type, final TxFacade txFacade, final DeviceRegistry registry,
75 final ConvertorExecutor convertorExecutor, final MultipartWriterProvider statisticsWriterProvider,
76 final ListeningExecutorService executorService) {
77 return Futures.transformAsync(statisticsGatheringService.getStatisticsOfType(
78 new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString()), type),
79 rpcResult -> executorService.submit(() -> {
80 final boolean rpcResultIsNull = rpcResult == null;
82 if (!rpcResultIsNull && rpcResult.isSuccessful()) {
83 LOG.debug("Stats reply successfully received for node {} of type {}", deviceInfo.getNodeId(), type);
84 // TODO: in case the result value is null then multipart data probably got processed
85 // TODO: on the fly. This contract should by clearly stated and enforced.
86 // TODO: Now simple true value is returned
87 if (Objects.nonNull(rpcResult.getResult()) && !rpcResult.getResult().isEmpty()) {
88 final List<DataContainer> allMultipartData = rpcResult.getResult().stream()
89 .map(reply -> MultipartReplyTranslatorUtil
90 .translate(reply, deviceInfo, convertorExecutor, null))
91 .filter(java.util.Optional::isPresent).map(java.util.Optional::get)
92 .collect(Collectors.toList());
94 return processStatistics(type, allMultipartData, txFacade, registry, deviceInfo,
95 statisticsWriterProvider);
97 LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
100 LOG.warn("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type,
101 rpcResultIsNull ? "" : rpcResult.getErrors());
104 }), MoreExecutors.directExecutor());
107 private static boolean processStatistics(final MultipartType type, final List<? extends DataContainer> statistics,
108 final TxFacade txFacade, final DeviceRegistry deviceRegistry,
109 final DeviceInfo deviceInfo,
110 final MultipartWriterProvider statisticsWriterProvider) {
111 final InstanceIdentifier<FlowCapableNode> instanceIdentifier = deviceInfo.getNodeInstanceIdentifier()
112 .augmentation(FlowCapableNode.class);
116 deleteAllKnownFlows(txFacade, instanceIdentifier, deviceRegistry.getDeviceFlowRegistry());
117 deviceRegistry.getDeviceFlowRegistry().processMarks();
119 case OFPMPMETERCONFIG:
120 deleteAllKnownMeters(txFacade, instanceIdentifier, deviceRegistry.getDeviceMeterRegistry());
121 deviceRegistry.getDeviceMeterRegistry().processMarks();
124 deleteAllKnownGroups(txFacade, instanceIdentifier, deviceRegistry.getDeviceGroupRegistry());
125 deviceRegistry.getDeviceGroupRegistry().processMarks();
131 if (writeStatistics(type, statistics, deviceInfo, statisticsWriterProvider)) {
132 txFacade.submitTransaction();
134 LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
138 LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo);
142 @SuppressWarnings("checkstyle:IllegalCatch")
143 private static boolean writeStatistics(final MultipartType type, final List<? extends DataContainer> statistics,
144 final DeviceInfo deviceInfo,
145 final MultipartWriterProvider statisticsWriterProvider) {
146 final AtomicBoolean result = new AtomicBoolean(false);
149 statistics.forEach(stat -> statisticsWriterProvider.lookup(type).ifPresent(p -> {
150 final boolean write = p.write(stat, false);
156 } catch (final Exception ex) {
157 LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo,
164 public static void deleteAllKnownFlows(final TxFacade txFacade,
165 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
166 final DeviceFlowRegistry deviceFlowRegistry) {
167 if (!txFacade.isTransactionsEnabled()) {
171 final ListenableFuture<Optional<FlowCapableNode>> future;
172 try (ReadOnlyTransaction readTx = txFacade.getReadTransaction()) {
173 future = readTx.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
177 Futures.transform(Futures.catchingAsync(future, Throwable.class, Futures::immediateFailedFuture,
178 MoreExecutors.directExecutor()), (Function<Optional<FlowCapableNode>, Void>) flowCapNodeOpt -> {
179 // we have to read actual tables with all information before we set empty Flow list,
180 // merge is expensive and not applicable for lists
181 if (flowCapNodeOpt != null && flowCapNodeOpt.isPresent()) {
182 for (final Table tableData : flowCapNodeOpt.get().getTable()) {
183 final Table table = new TableBuilder(tableData).setFlow(Collections.emptyList()).build();
184 final InstanceIdentifier<Table> iiToTable = instanceIdentifier
185 .child(Table.class, tableData.key());
186 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
190 }, MoreExecutors.directExecutor()).get();
191 } catch (InterruptedException | ExecutionException ex) {
192 LOG.debug("Failed to delete {} flows", deviceFlowRegistry.size(), ex);
196 public static void deleteAllKnownMeters(final TxFacade txFacade,
197 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
198 final DeviceMeterRegistry meterRegistry) {
199 meterRegistry.forEach(meterId -> {
202 LogicalDatastoreType.OPERATIONAL,
203 instanceIdentifier.child(Meter.class, new MeterKey(meterId)));
204 meterRegistry.addMark(meterId);
208 public static void deleteAllKnownGroups(final TxFacade txFacade,
209 final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
210 final DeviceGroupRegistry groupRegistry) {
211 LOG.debug("deleteAllKnownGroups on device targetType {}", instanceIdentifier.getTargetType());
212 groupRegistry.forEach(groupId -> {
215 LogicalDatastoreType.OPERATIONAL,
216 instanceIdentifier.child(Group.class, new GroupKey(groupId)));
217 groupRegistry.addMark(groupId);
222 * Writes snapshot gathering start timestamp + cleans end mark.
224 * @param deviceInfo device info
225 * @param txFacade tx manager
227 static void markDeviceStateSnapshotStart(final DeviceInfo deviceInfo, final TxFacade txFacade) {
228 final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceInfo
229 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
231 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
232 final FlowCapableStatisticsGatheringStatus gatheringStatus = new FlowCapableStatisticsGatheringStatusBuilder()
233 .setSnapshotGatheringStatusStart(new SnapshotGatheringStatusStartBuilder()
234 .setBegin(new DateAndTime(simpleDateFormat.format(new Date())))
236 .setSnapshotGatheringStatusEnd(null) // TODO: reconsider if really need to clean end mark here
239 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusPath, gatheringStatus);
240 } catch (final TransactionChainClosedException e) {
241 LOG.warn("Can't write to transaction, transaction chain probably closed.");
242 LOG.trace("Write to transaction exception: ", e);
245 txFacade.submitTransaction();
249 * Writes snapshot gathering end timestamp + outcome.
251 * @param deviceInfo device info
252 * @param txFacade tx manager
253 * @param succeeded outcome of currently finished gathering
255 static void markDeviceStateSnapshotEnd(final DeviceInfo deviceInfo,
256 final TxFacade txFacade, final boolean succeeded) {
257 final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceInfo
258 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class)
259 .child(SnapshotGatheringStatusEnd.class);
261 final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
262 final SnapshotGatheringStatusEnd gatheringStatus = new SnapshotGatheringStatusEndBuilder()
263 .setEnd(new DateAndTime(simpleDateFormat.format(new Date())))
264 .setSucceeded(succeeded)
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();