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