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