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