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