Switch to MD-SAL APIs
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsGatheringUtils.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.openflowplugin.impl.statistics;
9
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;
57
58 /**
59  * Utils for gathering statistics.
60  */
61 public final class StatisticsGatheringUtils {
62
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-";
66
67     private StatisticsGatheringUtils() {
68         throw new IllegalStateException("This class should not be instantiated.");
69     }
70
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;
80
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());
92
93                         return processStatistics(type, allMultipartData, txFacade, registry, deviceInfo,
94                                         statisticsWriterProvider);
95                     } else {
96                         LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
97                     }
98                 } else {
99                     LOG.warn("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type,
100                                 rpcResultIsNull ? "" : rpcResult.getErrors());
101                 }
102                 return false;
103             }), MoreExecutors.directExecutor());
104     }
105
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);
112
113         switch (type) {
114             case OFPMPFLOW:
115                 deleteAllKnownFlows(txFacade, instanceIdentifier, deviceRegistry.getDeviceFlowRegistry());
116                 deviceRegistry.getDeviceFlowRegistry().processMarks();
117                 break;
118             case OFPMPMETERCONFIG:
119                 deleteAllKnownMeters(txFacade, instanceIdentifier, deviceRegistry.getDeviceMeterRegistry());
120                 deviceRegistry.getDeviceMeterRegistry().processMarks();
121                 break;
122             case OFPMPGROUPDESC:
123                 deleteAllKnownGroups(txFacade, instanceIdentifier, deviceRegistry.getDeviceGroupRegistry());
124                 deviceRegistry.getDeviceGroupRegistry().processMarks();
125                 break;
126             default:
127                 // no operation
128         }
129
130         if (writeStatistics(type, statistics, deviceInfo, statisticsWriterProvider)) {
131             txFacade.submitTransaction();
132
133             LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
134             return true;
135         }
136
137         LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo);
138         return false;
139     }
140
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);
146
147         try {
148             statistics.forEach(stat -> statisticsWriterProvider.lookup(type).ifPresent(p -> {
149                 final boolean write = p.write(stat, false);
150
151                 if (!result.get()) {
152                     result.set(write);
153                 }
154             }));
155         } catch (final Exception ex) {
156             LOG.warn("Stats processing of type {} for node {} " + "failed during write-to-tx step", type, deviceInfo,
157                      ex);
158         }
159
160         return result.get();
161     }
162
163     public static void deleteAllKnownFlows(final TxFacade txFacade,
164                                            final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
165                                            final DeviceFlowRegistry deviceFlowRegistry) {
166         if (!txFacade.isTransactionsEnabled()) {
167             return;
168         }
169
170         final ListenableFuture<Optional<FlowCapableNode>> future;
171         try (ReadTransaction readTx = txFacade.getReadTransaction()) {
172             future = readTx.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
173         }
174
175         try {
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);
186                         }
187                     }
188                     return null;
189                 }, MoreExecutors.directExecutor()).get();
190         } catch (InterruptedException | ExecutionException ex) {
191             LOG.debug("Failed to delete {} flows", deviceFlowRegistry.size(), ex);
192         }
193     }
194
195     public static void deleteAllKnownMeters(final TxFacade txFacade,
196                                             final InstanceIdentifier<FlowCapableNode> instanceIdentifier,
197                                             final DeviceMeterRegistry meterRegistry) {
198         meterRegistry.forEach(meterId -> {
199             txFacade
200                     .addDeleteToTxChain(
201                             LogicalDatastoreType.OPERATIONAL,
202                             instanceIdentifier.child(Meter.class, new MeterKey(meterId)));
203             meterRegistry.addMark(meterId);
204         });
205     }
206
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 -> {
212             txFacade
213                     .addDeleteToTxChain(
214                             LogicalDatastoreType.OPERATIONAL,
215                             instanceIdentifier.child(Group.class, new GroupKey(groupId)));
216             groupRegistry.addMark(groupId);
217         });
218     }
219
220     /**
221      * Writes snapshot gathering start timestamp + cleans end mark.
222      *
223      * @param deviceInfo device info
224      * @param txFacade tx manager
225      */
226     static void markDeviceStateSnapshotStart(final DeviceInfo deviceInfo, final TxFacade txFacade) {
227         final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceInfo
228                 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
229
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())))
234                         .build())
235                 .setSnapshotGatheringStatusEnd(null) // TODO: reconsider if really need to clean end mark here
236                 .build();
237         try {
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);
242         }
243
244         txFacade.submitTransaction();
245     }
246
247     /**
248      * Writes snapshot gathering end timestamp + outcome.
249      *
250      * @param deviceInfo device info
251      * @param txFacade tx manager
252      * @param succeeded     outcome of currently finished gathering
253      */
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);
259
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)
264                 .build();
265         try {
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);
270         }
271
272         txFacade.submitTransaction();
273     }
274 }