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