Merge "Removed duplicate sal-binding-config dependency."
[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.collect.Iterables;
14 import com.google.common.util.concurrent.AsyncFunction;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureFallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.JdkFutureAdapters;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.text.SimpleDateFormat;
21 import java.util.Collections;
22 import java.util.Date;
23 import java.util.List;
24 import javax.annotation.Nullable;
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.ReadFailedException;
28 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
30 import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
31 import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
32 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
33 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
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.registry.flow.FlowRegistryKeyFactory;
39 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.EventsTimeCounter;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.DateAndTime;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
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.FlowId;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEndBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusStartBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsData;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsDataBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapList;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.statistics.FlowStatisticsBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdate;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMap;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.statistics.FlowTableStatistics;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.statistics.FlowTableStatisticsBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdated;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdated;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatistics;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatisticsBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.statistics.GroupStatistics;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.statistics.GroupStatisticsBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply.GroupStats;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterConfigStatsUpdated;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdated;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatistics;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatisticsBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.meter.MeterStatistics;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.meter.MeterStatisticsBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStats;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.flow.capable.node.connector.statistics.FlowCapableNodeConnectorStatistics;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.flow.capable.node.connector.statistics.FlowCapableNodeConnectorStatisticsBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.FlowCapableNodeConnectorQueueStatisticsData;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.FlowCapableNodeConnectorQueueStatisticsDataBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdate;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.flow.capable.node.connector.queue.statistics.FlowCapableNodeConnectorQueueStatistics;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.flow.capable.node.connector.queue.statistics.FlowCapableNodeConnectorQueueStatisticsBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap;
108 import org.opendaylight.yangtools.yang.binding.DataObject;
109 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
110 import org.opendaylight.yangtools.yang.common.RpcResult;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
113
114 /**
115  * Utils for gatherig statistics
116  */
117 public final class StatisticsGatheringUtils {
118
119     private static String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
120
121     private static final Logger LOG = LoggerFactory.getLogger(StatisticsGatheringUtils.class);
122     private static final SinglePurposeMultipartReplyTranslator MULTIPART_REPLY_TRANSLATOR = new SinglePurposeMultipartReplyTranslator();
123     private static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
124
125     private StatisticsGatheringUtils() {
126         throw new IllegalStateException("This class should not be instantiated.");
127     }
128
129     //TODO: Flow-,Group- and Meter- registry should be not in device context, consider move it in separate class
130     static ListenableFuture<Boolean> gatherStatistics(final StatisticsGatherer statisticsGatheringService,
131                                                       final DeviceInfo deviceInfo,
132                                                       final MultipartType type,
133                                                       final TxFacade txFacade,
134                                                       final DeviceRegistry registry,
135                                                       final Boolean initial) {
136         EventIdentifier wholeProcessEventIdentifier = null;
137         if (MultipartType.OFPMPFLOW.equals(type)) {
138             wholeProcessEventIdentifier = new EventIdentifier(type.toString(), deviceInfo.getNodeId().getValue());
139             EventsTimeCounter.markStart(wholeProcessEventIdentifier);
140         }
141         final EventIdentifier ofpQueuToRequestContextEventIdentifier = new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString());
142         final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture =
143                 JdkFutureAdapters.listenInPoolThread(statisticsGatheringService.getStatisticsOfType(
144                         ofpQueuToRequestContextEventIdentifier, type));
145         return transformAndStoreStatisticsData(statisticsDataInFuture, deviceInfo, wholeProcessEventIdentifier, type, txFacade, registry, initial);
146     }
147
148     private static ListenableFuture<Boolean> transformAndStoreStatisticsData(final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture,
149                                                                              final DeviceInfo deviceInfo,
150                                                                              final EventIdentifier eventIdentifier,
151                                                                              final MultipartType type,
152                                                                              final TxFacade txFacade,
153                                                                              final DeviceRegistry registry,
154                                                                              final boolean initial) {
155         return Futures.transform(statisticsDataInFuture, new AsyncFunction<RpcResult<List<MultipartReply>>, Boolean>() {
156             @Nullable
157             @Override
158             public ListenableFuture<Boolean> apply(final RpcResult<List<MultipartReply>> rpcResult) {
159                 boolean isMultipartProcessed = Boolean.TRUE;
160                 if (rpcResult.isSuccessful()) {
161                     LOG.debug("Stats reply successfully received for node {} of type {}", deviceInfo.getNodeId(), type);
162
163                     // TODO: in case the result value is null then multipart data probably got processed on the fly -
164                     // TODO: this contract should by clearly stated and enforced - now simple true value is returned
165                     if (null != rpcResult.getResult()) {
166                         Iterable<? extends DataObject> allMultipartData = Collections.emptyList();
167                         DataObject multipartData = null;
168
169
170                         try {
171                             for (final MultipartReply singleReply : rpcResult.getResult()) {
172                                 final List<? extends DataObject> multipartDataList = MULTIPART_REPLY_TRANSLATOR.translate(
173                                         deviceInfo.getDatapathId(),
174                                         deviceInfo.getVersion(), singleReply);
175                                 multipartData = multipartDataList.get(0);
176                                 allMultipartData = Iterables.concat(allMultipartData, multipartDataList);
177                             }
178                         } catch (final Exception e) {
179                             LOG.warn("stats processing of type {} for node {} failed during transfomation step",
180                                     type, deviceInfo.getNodeId(), e);
181                             return Futures.immediateFailedFuture(e);
182                         }
183
184
185                         try {
186                             if (multipartData instanceof GroupStatisticsUpdated) {
187                                 processGroupStatistics((Iterable<GroupStatisticsUpdated>) allMultipartData, deviceInfo, txFacade);
188                             } else if (multipartData instanceof MeterStatisticsUpdated) {
189                                 processMetersStatistics((Iterable<MeterStatisticsUpdated>) allMultipartData, deviceInfo, txFacade);
190                             } else if (multipartData instanceof NodeConnectorStatisticsUpdate) {
191                                 processNodeConnectorStatistics((Iterable<NodeConnectorStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
192                             } else if (multipartData instanceof FlowTableStatisticsUpdate) {
193                                 processFlowTableStatistics((Iterable<FlowTableStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
194                             } else if (multipartData instanceof QueueStatisticsUpdate) {
195                                 processQueueStatistics((Iterable<QueueStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
196                             } else if (multipartData instanceof FlowsStatisticsUpdate) {
197                                 /* FlowStat Processing is realized by NettyThread only by initPhase, otherwise it is realized
198                                  * by MD-SAL thread */
199                                 return processFlowStatistics((Iterable<FlowsStatisticsUpdate>) allMultipartData, deviceInfo, txFacade, registry.getDeviceFlowRegistry(), initial, eventIdentifier);
200
201                             } else if (multipartData instanceof GroupDescStatsUpdated) {
202                                 processGroupDescStats((Iterable<GroupDescStatsUpdated>) allMultipartData, deviceInfo, txFacade, registry.getDeviceGroupRegistry());
203                             } else if (multipartData instanceof MeterConfigStatsUpdated) {
204                                 processMeterConfigStatsUpdated((Iterable<MeterConfigStatsUpdated>) allMultipartData, deviceInfo, txFacade, registry.getDeviceMeterRegistry());
205                             } else {
206                                 isMultipartProcessed = Boolean.FALSE;
207                             }
208                         } catch (final Exception e) {
209                             LOG.warn("stats processing of type {} for node {} failed during write-to-tx step",
210                                     type, deviceInfo.getNodeId(), e);
211                             return Futures.immediateFailedFuture(e);
212                         }
213
214                         LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
215
216                         //TODO : implement experimenter
217                     } else {
218                         LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
219                     }
220
221                 } else {
222                     LOG.debug("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type, rpcResult.getErrors());
223                     isMultipartProcessed = Boolean.FALSE;
224                 }
225                 return Futures.immediateFuture(isMultipartProcessed);
226             }
227         });
228     }
229
230     private static void processMeterConfigStatsUpdated(final Iterable<MeterConfigStatsUpdated> data,
231                                                        final DeviceInfo deviceInfo,
232                                                        final TxFacade txFacade,
233                                                        final DeviceMeterRegistry meterRegistry) throws Exception {
234         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
235         deleteAllKnownMeters(meterRegistry, fNodeIdent, txFacade);
236         for (final MeterConfigStatsUpdated meterConfigStatsUpdated : data) {
237             for (final MeterConfigStats meterConfigStats : meterConfigStatsUpdated.getMeterConfigStats()) {
238                 final MeterId meterId = meterConfigStats.getMeterId();
239                 final InstanceIdentifier<Meter> meterInstanceIdentifier = fNodeIdent.child(Meter.class, new MeterKey(meterId));
240
241                 final MeterBuilder meterBuilder = new MeterBuilder(meterConfigStats);
242                 meterBuilder.setKey(new MeterKey(meterId));
243                 meterBuilder.addAugmentation(NodeMeterStatistics.class, new NodeMeterStatisticsBuilder().build());
244                 meterRegistry.store(meterId);
245                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, meterInstanceIdentifier, meterBuilder.build());
246             }
247         }
248         txFacade.submitTransaction();
249     }
250
251     private static ListenableFuture<Boolean> processFlowStatistics(final Iterable<FlowsStatisticsUpdate> data,
252                                                                    final DeviceInfo deviceInfo,
253                                                                    final TxFacade txFacade,
254                                                                    final DeviceFlowRegistry flowRegistry,
255                                                                    final boolean initial,
256                                                                    final EventIdentifier eventIdentifier) {
257         final ListenableFuture<Void> deleteFuture = initial ? Futures.immediateFuture(null) : deleteAllKnownFlows(deviceInfo,
258                 flowRegistry, txFacade);
259         return Futures.transform(deleteFuture, new Function<Void, Boolean>() {
260
261             @Override
262             public Boolean apply(final Void input) {
263                 writeFlowStatistics(data, deviceInfo, flowRegistry, txFacade);
264                 txFacade.submitTransaction();
265                 EventsTimeCounter.markEnd(eventIdentifier);
266                 return Boolean.TRUE;
267             }
268         });
269     }
270
271     public static void writeFlowStatistics(final Iterable<FlowsStatisticsUpdate> data,
272                                            final DeviceInfo deviceInfo,
273                                            final DeviceFlowRegistry registry,
274                                            final TxFacade txFacade) {
275         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
276         try {
277             for (final FlowsStatisticsUpdate flowsStatistics : data) {
278                 for (final FlowAndStatisticsMapList flowStat : flowsStatistics.getFlowAndStatisticsMapList()) {
279                     final FlowBuilder flowBuilder = new FlowBuilder(flowStat);
280                     flowBuilder.addAugmentation(FlowStatisticsData.class, refineFlowStatisticsAugmentation(flowStat).build());
281
282                     final short tableId = flowStat.getTableId();
283                     final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(flowBuilder.build());
284                     final FlowId flowId = registry.storeIfNecessary(flowRegistryKey, tableId);
285
286                     final FlowKey flowKey = new FlowKey(flowId);
287                     flowBuilder.setKey(flowKey);
288                     final TableKey tableKey = new TableKey(tableId);
289                     final InstanceIdentifier<Flow> flowIdent = fNodeIdent.child(Table.class, tableKey).child(Flow.class, flowKey);
290                     txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, flowIdent, flowBuilder.build());
291                 }
292             }
293         } catch (Exception e) {
294             LOG.warn("Not able to write to transaction: {}", e.getMessage());
295         }
296     }
297
298     /**
299      * Method extracts flow statistics out of flowAndStatistics model
300      *
301      * @param flowAndStats
302      */
303     private static FlowStatisticsDataBuilder refineFlowStatisticsAugmentation(final FlowAndStatisticsMapList flowAndStats) {
304         final FlowStatisticsBuilder flowStatisticsBuilder = new FlowStatisticsBuilder(flowAndStats);
305         final FlowStatisticsDataBuilder flowStatisticsDataBld = new FlowStatisticsDataBuilder();
306         flowStatisticsDataBld.setFlowStatistics(flowStatisticsBuilder.build());
307         return flowStatisticsDataBld;
308     }
309
310     public static ListenableFuture<Void> deleteAllKnownFlows(final DeviceInfo deviceInfo,
311                                                              final DeviceFlowRegistry registry,
312                                                              final TxFacade txFacade) {
313         final InstanceIdentifier<FlowCapableNode> flowCapableNodePath = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
314         final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
315         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowCapableNodeFuture = readTx.read(
316                 LogicalDatastoreType.OPERATIONAL, flowCapableNodePath);
317
318         /* we wish to close readTx for fallBack */
319         Futures.withFallback(flowCapableNodeFuture, new FutureFallback<Optional<FlowCapableNode>>() {
320
321             @Override
322             public ListenableFuture<Optional<FlowCapableNode>> create(final Throwable t) throws Exception {
323                 readTx.close();
324                 return Futures.immediateFailedFuture(t);
325             }
326         });
327         /*
328          * we have to read actual tables with all information before we set empty Flow list, merge is expensive and
329          * not applicable for lists
330          */
331         return Futures.transform(flowCapableNodeFuture, new AsyncFunction<Optional<FlowCapableNode>, Void>() {
332
333             @Override
334             public ListenableFuture<Void> apply(final Optional<FlowCapableNode> flowCapNodeOpt) throws Exception {
335                 if (flowCapNodeOpt.isPresent()) {
336                     for (final Table tableData : flowCapNodeOpt.get().getTable()) {
337                         final Table table = new TableBuilder(tableData).setFlow(Collections.<Flow>emptyList()).build();
338                         final InstanceIdentifier<Table> iiToTable = flowCapableNodePath.child(Table.class, tableData.getKey());
339                         txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
340                     }
341                 }
342                 registry.removeMarked();
343                 readTx.close();
344                 return Futures.immediateFuture(null);
345             }
346
347         });
348     }
349
350     private static void processQueueStatistics(final Iterable<QueueStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
351         // TODO: clean all queues of all node-connectors before writing up-to-date stats
352         final InstanceIdentifier<Node> nodeIdent = deviceInfo.getNodeInstanceIdentifier();
353         for (final QueueStatisticsUpdate queueStatisticsUpdate : data) {
354             for (final QueueIdAndStatisticsMap queueStat : queueStatisticsUpdate.getQueueIdAndStatisticsMap()) {
355                 if (queueStat.getQueueId() != null) {
356                     final FlowCapableNodeConnectorQueueStatistics statChild =
357                             new FlowCapableNodeConnectorQueueStatisticsBuilder(queueStat).build();
358                     final FlowCapableNodeConnectorQueueStatisticsDataBuilder statBuild =
359                             new FlowCapableNodeConnectorQueueStatisticsDataBuilder();
360                     statBuild.setFlowCapableNodeConnectorQueueStatistics(statChild);
361                     final QueueKey qKey = new QueueKey(queueStat.getQueueId());
362                     final InstanceIdentifier<Queue> queueIdent = nodeIdent
363                             .child(NodeConnector.class, new NodeConnectorKey(queueStat.getNodeConnectorId()))
364                             .augmentation(FlowCapableNodeConnector.class)
365                             .child(Queue.class, qKey);
366                     final QueueBuilder queueBuilder = new QueueBuilder()
367                             .setKey(qKey)
368                             .setQueueId(queueStat.getQueueId())
369                             // node-connector-id is already contained in parent node and the port-id here is of incompatible format
370                             .addAugmentation(FlowCapableNodeConnectorQueueStatisticsData.class, statBuild.build());
371                     txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, queueIdent, queueBuilder.build());
372                 }
373             }
374         }
375         txFacade.submitTransaction();
376     }
377
378     private static void processFlowTableStatistics(final Iterable<FlowTableStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
379         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
380         for (final FlowTableStatisticsUpdate flowTableStatisticsUpdate : data) {
381
382             for (final FlowTableAndStatisticsMap tableStat : flowTableStatisticsUpdate.getFlowTableAndStatisticsMap()) {
383                 final InstanceIdentifier<FlowTableStatistics> tStatIdent = fNodeIdent.child(Table.class, new TableKey(tableStat.getTableId().getValue()))
384                         .augmentation(FlowTableStatisticsData.class).child(FlowTableStatistics.class);
385                 final FlowTableStatistics stats = new FlowTableStatisticsBuilder(tableStat).build();
386                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tStatIdent, stats);
387             }
388         }
389         txFacade.submitTransaction();
390     }
391
392     private static void processNodeConnectorStatistics(final Iterable<NodeConnectorStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
393         final InstanceIdentifier<Node> nodeIdent = deviceInfo.getNodeInstanceIdentifier();
394         for (final NodeConnectorStatisticsUpdate nodeConnectorStatisticsUpdate : data) {
395             for (final NodeConnectorStatisticsAndPortNumberMap nConnectPort : nodeConnectorStatisticsUpdate.getNodeConnectorStatisticsAndPortNumberMap()) {
396                 final FlowCapableNodeConnectorStatistics stats = new FlowCapableNodeConnectorStatisticsBuilder(nConnectPort).build();
397                 final NodeConnectorKey key = new NodeConnectorKey(nConnectPort.getNodeConnectorId());
398                 final InstanceIdentifier<NodeConnector> nodeConnectorIdent = nodeIdent.child(NodeConnector.class, key);
399                 final InstanceIdentifier<FlowCapableNodeConnectorStatisticsData> nodeConnStatIdent = nodeConnectorIdent
400                         .augmentation(FlowCapableNodeConnectorStatisticsData.class);
401                 final InstanceIdentifier<FlowCapableNodeConnectorStatistics> flowCapNodeConnStatIdent =
402                         nodeConnStatIdent.child(FlowCapableNodeConnectorStatistics.class);
403                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, flowCapNodeConnStatIdent, stats);
404             }
405         }
406         txFacade.submitTransaction();
407     }
408
409     private static void processMetersStatistics(final Iterable<MeterStatisticsUpdated> data,
410                                                 final DeviceInfo deviceInfo,
411                                                 final TxFacade txFacade) throws Exception {
412         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
413         for (final MeterStatisticsUpdated meterStatisticsUpdated : data) {
414             for (final MeterStats mStat : meterStatisticsUpdated.getMeterStats()) {
415                 final MeterStatistics stats = new MeterStatisticsBuilder(mStat).build();
416                 final MeterId meterId = mStat.getMeterId();
417                 final InstanceIdentifier<Meter> meterIdent = fNodeIdent.child(Meter.class, new MeterKey(meterId));
418                 final InstanceIdentifier<NodeMeterStatistics> nodeMeterStatIdent = meterIdent
419                         .augmentation(NodeMeterStatistics.class);
420                 final InstanceIdentifier<MeterStatistics> msIdent = nodeMeterStatIdent.child(MeterStatistics.class);
421                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, msIdent, stats);
422             }
423         }
424         txFacade.submitTransaction();
425     }
426
427     private static void deleteAllKnownMeters(final DeviceMeterRegistry meterRegistry, final InstanceIdentifier<FlowCapableNode> fNodeIdent, final TxFacade txFacade) throws Exception {
428         for (final MeterId meterId : meterRegistry.getAllMeterIds()) {
429             final InstanceIdentifier<Meter> meterIdent = fNodeIdent.child(Meter.class, new MeterKey(meterId));
430             txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, meterIdent);
431         }
432         meterRegistry.removeMarked();
433     }
434
435     private static void processGroupDescStats(final Iterable<GroupDescStatsUpdated> data, final DeviceInfo deviceInfo, final TxFacade txFacade, final DeviceGroupRegistry groupRegistry) throws Exception {
436         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
437         deleteAllKnownGroups(txFacade, fNodeIdent, groupRegistry);
438
439         for (final GroupDescStatsUpdated groupDescStatsUpdated : data) {
440             for (final GroupDescStats groupDescStats : groupDescStatsUpdated.getGroupDescStats()) {
441                 final GroupId groupId = groupDescStats.getGroupId();
442
443                 final GroupBuilder groupBuilder = new GroupBuilder(groupDescStats);
444                 groupBuilder.setKey(new GroupKey(groupId));
445                 groupBuilder.addAugmentation(NodeGroupStatistics.class, new NodeGroupStatisticsBuilder().build());
446
447                 final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupId));
448
449                 groupRegistry.store(groupId);
450                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, groupIdent, groupBuilder.build());
451             }
452         }
453         txFacade.submitTransaction();
454     }
455
456     private static void deleteAllKnownGroups(final TxFacade txFacade, final InstanceIdentifier<FlowCapableNode> fNodeIdent, final DeviceGroupRegistry groupRegistry) throws Exception {
457         for (final GroupId groupId : groupRegistry.getAllGroupIds()) {
458             final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupId));
459             txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, groupIdent);
460         }
461         groupRegistry.removeMarked();
462     }
463
464     private static void processGroupStatistics(final Iterable<GroupStatisticsUpdated> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
465         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
466         for (final GroupStatisticsUpdated groupStatistics : data) {
467             for (final GroupStats groupStats : groupStatistics.getGroupStats()) {
468
469                 final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupStats.getGroupId()));
470                 final InstanceIdentifier<NodeGroupStatistics> nGroupStatIdent = groupIdent
471                         .augmentation(NodeGroupStatistics.class);
472
473                 final InstanceIdentifier<GroupStatistics> gsIdent = nGroupStatIdent.child(GroupStatistics.class);
474                 final GroupStatistics stats = new GroupStatisticsBuilder(groupStats).build();
475                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gsIdent, stats);
476             }
477         }
478         txFacade.submitTransaction();
479     }
480
481     private static InstanceIdentifier<FlowCapableNode> assembleFlowCapableNodeInstanceIdentifier(final DeviceInfo deviceInfo) {
482         return deviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
483     }
484
485     /**
486      * Writes snapshot gathering start timestamp + cleans end mark
487      *
488      * @param deviceContext txManager + node path keeper
489      */
490     static void markDeviceStateSnapshotStart(final DeviceContext deviceContext) {
491         final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceContext.getDeviceInfo()
492                 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
493
494         final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
495         final FlowCapableStatisticsGatheringStatus gatheringStatus = new FlowCapableStatisticsGatheringStatusBuilder()
496                 .setSnapshotGatheringStatusStart(new SnapshotGatheringStatusStartBuilder()
497                         .setBegin(new DateAndTime(simpleDateFormat.format(new Date())))
498                         .build())
499                 .setSnapshotGatheringStatusEnd(null) // TODO: reconsider if really need to clean end mark here
500                 .build();
501         try {
502             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusPath, gatheringStatus);
503         } catch (final Exception e) {
504             LOG.warn("Can't write to transaction: {}", e);
505         }
506
507         deviceContext.submitTransaction();
508     }
509
510     /**
511      * Writes snapshot gathering end timestamp + outcome
512      *
513      * @param deviceContext txManager + node path keeper
514      * @param succeeded     outcome of currently finished gathering
515      */
516     static void markDeviceStateSnapshotEnd(final DeviceContext deviceContext, final boolean succeeded) {
517         final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceContext.getDeviceInfo()
518                 .getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class)
519                 .child(SnapshotGatheringStatusEnd.class);
520
521         final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
522         final SnapshotGatheringStatusEnd gatheringStatus = new SnapshotGatheringStatusEndBuilder()
523                 .setEnd(new DateAndTime(simpleDateFormat.format(new Date())))
524                 .setSucceeded(succeeded)
525                 .build();
526         try {
527             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusEndPath, gatheringStatus);
528         } catch (Exception e) {
529             LOG.warn("Can't write to transaction: {}", e);
530         }
531
532         deviceContext.submitTransaction();
533     }
534 }