Fix statistics race condition on big flows
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsGatheringUtils.java
index e482a7f792b3428133d55150dad39d3536eda852..966608079424ad29c84e875d2eda890e1a989e8c 100644 (file)
@@ -13,18 +13,13 @@ import com.google.common.base.Optional;
 import com.google.common.collect.Iterables;
 import com.google.common.util.concurrent.AsyncFunction;
 import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureFallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
-import java.text.SimpleDateFormat;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import javax.annotation.Nullable;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
@@ -37,7 +32,7 @@ import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.Event
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.StatisticsGatherer;
 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.EventsTimeCounter;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.DateAndTime;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
@@ -111,15 +106,21 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.annotation.Nullable;
+import java.text.SimpleDateFormat;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
 /**
- * Utils for gatherig statistics
+ * Utils for gathering statistics.
  */
 public final class StatisticsGatheringUtils {
 
     private static String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
 
     private static final Logger LOG = LoggerFactory.getLogger(StatisticsGatheringUtils.class);
-    private static final SinglePurposeMultipartReplyTranslator MULTIPART_REPLY_TRANSLATOR = new SinglePurposeMultipartReplyTranslator();
     private static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
 
     private StatisticsGatheringUtils() {
@@ -127,38 +128,54 @@ public final class StatisticsGatheringUtils {
     }
 
     //TODO: Flow-,Group- and Meter- registry should be not in device context, consider move it in separate class
-    static ListenableFuture<Boolean> gatherStatistics(final StatisticsGatherer statisticsGatheringService,
-                                                      final DeviceInfo deviceInfo,
-                                                      final MultipartType type,
-                                                      final TxFacade txFacade,
-                                                      final DeviceRegistry registry,
-                                                      final Boolean initial) {
+    static ListenableFuture<Boolean> gatherStatistics(
+                        final StatisticsGatherer statisticsGatheringService,
+                        final DeviceInfo deviceInfo,
+                        final MultipartType type,
+                        final TxFacade txFacade,
+                        final DeviceRegistry registry,
+                        final Boolean initial,
+                        final SinglePurposeMultipartReplyTranslator multipartReplyTranslator) {
         EventIdentifier wholeProcessEventIdentifier = null;
         if (MultipartType.OFPMPFLOW.equals(type)) {
             wholeProcessEventIdentifier = new EventIdentifier(type.toString(), deviceInfo.getNodeId().getValue());
             EventsTimeCounter.markStart(wholeProcessEventIdentifier);
         }
-        final EventIdentifier ofpQueuToRequestContextEventIdentifier = new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString());
+        final EventIdentifier ofpQueueToRequestContextEventIdentifier
+                = new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString());
         final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture =
                 JdkFutureAdapters.listenInPoolThread(statisticsGatheringService.getStatisticsOfType(
-                        ofpQueuToRequestContextEventIdentifier, type));
-        return transformAndStoreStatisticsData(statisticsDataInFuture, deviceInfo, wholeProcessEventIdentifier, type, txFacade, registry, initial);
+                        ofpQueueToRequestContextEventIdentifier, type));
+        return transformAndStoreStatisticsData(
+                statisticsDataInFuture,
+                deviceInfo,
+                wholeProcessEventIdentifier,
+                type,
+                txFacade,
+                registry,
+                initial,
+                multipartReplyTranslator);
     }
 
-    private static ListenableFuture<Boolean> transformAndStoreStatisticsData(final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture,
-                                                                             final DeviceInfo deviceInfo,
-                                                                             final EventIdentifier eventIdentifier,
-                                                                             final MultipartType type,
-                                                                             final TxFacade txFacade,
-                                                                             final DeviceRegistry registry,
-                                                                             final boolean initial) {
+    private static ListenableFuture<Boolean> transformAndStoreStatisticsData(
+                        final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture,
+                        final DeviceInfo deviceInfo,
+                        final EventIdentifier eventIdentifier,
+                        final MultipartType type,
+                        final TxFacade txFacade,
+                        final DeviceRegistry registry,
+                        final boolean initial,
+                        final SinglePurposeMultipartReplyTranslator multipartReplyTranslator) {
         return Futures.transform(statisticsDataInFuture, new AsyncFunction<RpcResult<List<MultipartReply>>, Boolean>() {
             @Nullable
             @Override
             public ListenableFuture<Boolean> apply(final RpcResult<List<MultipartReply>> rpcResult) {
                 boolean isMultipartProcessed = Boolean.TRUE;
                 if (rpcResult.isSuccessful()) {
-                    LOG.debug("Stats reply successfully received for node {} of type {}", deviceInfo.getNodeId(), type);
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("Stats reply successfully received for node {} of type {}",
+                                deviceInfo.getNodeId(), type);
+                    }
 
                     // TODO: in case the result value is null then multipart data probably got processed on the fly -
                     // TODO: this contract should by clearly stated and enforced - now simple true value is returned
@@ -169,14 +186,14 @@ public final class StatisticsGatheringUtils {
 
                         try {
                             for (final MultipartReply singleReply : rpcResult.getResult()) {
-                                final List<? extends DataObject> multipartDataList = MULTIPART_REPLY_TRANSLATOR.translate(
+                                final List<? extends DataObject> multipartDataList = multipartReplyTranslator.translate(
                                         deviceInfo.getDatapathId(),
                                         deviceInfo.getVersion(), singleReply);
                                 multipartData = multipartDataList.get(0);
                                 allMultipartData = Iterables.concat(allMultipartData, multipartDataList);
                             }
-                        } catch (final Exception e) {
-                            LOG.warn("stats processing of type {} for node {} failed during transfomation step",
+                        } catch (final TransactionChainClosedException e) {
+                            LOG.warn("stats processing of type {} for node {} failed during transformation step",
                                     type, deviceInfo.getNodeId(), e);
                             return Futures.immediateFailedFuture(e);
                         }
@@ -184,42 +201,81 @@ public final class StatisticsGatheringUtils {
 
                         try {
                             if (multipartData instanceof GroupStatisticsUpdated) {
-                                processGroupStatistics((Iterable<GroupStatisticsUpdated>) allMultipartData, deviceInfo, txFacade);
+                                processGroupStatistics(
+                                        (Iterable<GroupStatisticsUpdated>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade);
                             } else if (multipartData instanceof MeterStatisticsUpdated) {
-                                processMetersStatistics((Iterable<MeterStatisticsUpdated>) allMultipartData, deviceInfo, txFacade);
+                                processMetersStatistics(
+                                        (Iterable<MeterStatisticsUpdated>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade);
                             } else if (multipartData instanceof NodeConnectorStatisticsUpdate) {
-                                processNodeConnectorStatistics((Iterable<NodeConnectorStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
+                                processNodeConnectorStatistics(
+                                        (Iterable<NodeConnectorStatisticsUpdate>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade);
                             } else if (multipartData instanceof FlowTableStatisticsUpdate) {
-                                processFlowTableStatistics((Iterable<FlowTableStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
+                                processFlowTableStatistics(
+                                        (Iterable<FlowTableStatisticsUpdate>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade);
                             } else if (multipartData instanceof QueueStatisticsUpdate) {
-                                processQueueStatistics((Iterable<QueueStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
+                                processQueueStatistics(
+                                        (Iterable<QueueStatisticsUpdate>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade);
                             } else if (multipartData instanceof FlowsStatisticsUpdate) {
-                                /* FlowStat Processing is realized by NettyThread only by initPhase, otherwise it is realized
+                                /* FlowStat Processing is realized by NettyThread only by initPhase,
+                                 * otherwise it is realized
                                  * by MD-SAL thread */
-                                return processFlowStatistics((Iterable<FlowsStatisticsUpdate>) allMultipartData, deviceInfo, txFacade, registry.getDeviceFlowRegistry(), initial, eventIdentifier);
+                                return processFlowStatistics(
+                                        (Iterable<FlowsStatisticsUpdate>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade,
+                                        registry.getDeviceFlowRegistry(),
+                                        initial,
+                                        eventIdentifier);
 
                             } else if (multipartData instanceof GroupDescStatsUpdated) {
-                                processGroupDescStats((Iterable<GroupDescStatsUpdated>) allMultipartData, deviceInfo, txFacade, registry.getDeviceGroupRegistry());
+                                processGroupDescStats(
+                                        (Iterable<GroupDescStatsUpdated>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade,
+                                        registry.getDeviceGroupRegistry());
                             } else if (multipartData instanceof MeterConfigStatsUpdated) {
-                                processMeterConfigStatsUpdated((Iterable<MeterConfigStatsUpdated>) allMultipartData, deviceInfo, txFacade, registry.getDeviceMeterRegistry());
+                                processMeterConfigStatsUpdated(
+                                        (Iterable<MeterConfigStatsUpdated>) allMultipartData,
+                                        deviceInfo,
+                                        txFacade,
+                                        registry.getDeviceMeterRegistry());
                             } else {
                                 isMultipartProcessed = Boolean.FALSE;
                             }
-                        } catch (final Exception e) {
+                        } catch (final TransactionChainClosedException e) {
                             LOG.warn("stats processing of type {} for node {} failed during write-to-tx step",
                                     type, deviceInfo.getNodeId(), e);
                             return Futures.immediateFailedFuture(e);
                         }
 
-                        LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
+                        if (LOG.isDebugEnabled()) {
+                            LOG.debug("Stats reply added to transaction for node {} of type {}",
+                                    deviceInfo.getNodeId(), type);
+                        }
 
                         //TODO : implement experimenter
                     } else {
-                        LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
+                        if (LOG.isDebugEnabled()) {
+                            LOG.debug("Stats reply was empty for node {} of type {}",
+                                    deviceInfo.getNodeId(), type);
+                        }
                     }
 
                 } else {
-                    LOG.debug("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type, rpcResult.getErrors());
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("Stats reply FAILED for node {} of type {}: {}",
+                                deviceInfo.getNodeId(), type, rpcResult.getErrors());
+                    }
                     isMultipartProcessed = Boolean.FALSE;
                 }
                 return Futures.immediateFuture(isMultipartProcessed);
@@ -230,19 +286,24 @@ public final class StatisticsGatheringUtils {
     private static void processMeterConfigStatsUpdated(final Iterable<MeterConfigStatsUpdated> data,
                                                        final DeviceInfo deviceInfo,
                                                        final TxFacade txFacade,
-                                                       final DeviceMeterRegistry meterRegistry) throws Exception {
+                                                       final DeviceMeterRegistry meterRegistry)
+            throws TransactionChainClosedException {
         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
         deleteAllKnownMeters(meterRegistry, fNodeIdent, txFacade);
         for (final MeterConfigStatsUpdated meterConfigStatsUpdated : data) {
             for (final MeterConfigStats meterConfigStats : meterConfigStatsUpdated.getMeterConfigStats()) {
                 final MeterId meterId = meterConfigStats.getMeterId();
-                final InstanceIdentifier<Meter> meterInstanceIdentifier = fNodeIdent.child(Meter.class, new MeterKey(meterId));
+                final InstanceIdentifier<Meter> meterInstanceIdentifier
+                        = fNodeIdent.child(Meter.class, new MeterKey(meterId));
 
                 final MeterBuilder meterBuilder = new MeterBuilder(meterConfigStats);
                 meterBuilder.setKey(new MeterKey(meterId));
                 meterBuilder.addAugmentation(NodeMeterStatistics.class, new NodeMeterStatisticsBuilder().build());
                 meterRegistry.store(meterId);
-                txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, meterInstanceIdentifier, meterBuilder.build());
+                txFacade.writeToTransaction(
+                        LogicalDatastoreType.OPERATIONAL,
+                        meterInstanceIdentifier,
+                        meterBuilder.build());
             }
         }
         txFacade.submitTransaction();
@@ -254,17 +315,14 @@ public final class StatisticsGatheringUtils {
                                                                    final DeviceFlowRegistry flowRegistry,
                                                                    final boolean initial,
                                                                    final EventIdentifier eventIdentifier) {
-        final ListenableFuture<Void> deleteFuture = initial ? Futures.immediateFuture(null) : deleteAllKnownFlows(deviceInfo,
-                flowRegistry, txFacade);
-        return Futures.transform(deleteFuture, new Function<Void, Boolean>() {
-
-            @Override
-            public Boolean apply(final Void input) {
-                writeFlowStatistics(data, deviceInfo, flowRegistry, txFacade);
-                txFacade.submitTransaction();
-                EventsTimeCounter.markEnd(eventIdentifier);
-                return Boolean.TRUE;
-            }
+        final ListenableFuture<Void> deleteFuture
+                = initial ? Futures.immediateFuture(null) : deleteAllKnownFlows(deviceInfo, flowRegistry, txFacade);
+        return Futures.transform(deleteFuture, (Function<Void, Boolean>) input -> {
+            writeFlowStatistics(data, deviceInfo, flowRegistry, txFacade);
+            txFacade.submitTransaction();
+            EventsTimeCounter.markEnd(eventIdentifier);
+            flowRegistry.processMarks();
+            return Boolean.TRUE;
         });
     }
 
@@ -277,30 +335,34 @@ public final class StatisticsGatheringUtils {
             for (final FlowsStatisticsUpdate flowsStatistics : data) {
                 for (final FlowAndStatisticsMapList flowStat : flowsStatistics.getFlowAndStatisticsMapList()) {
                     final FlowBuilder flowBuilder = new FlowBuilder(flowStat);
-                    flowBuilder.addAugmentation(FlowStatisticsData.class, refineFlowStatisticsAugmentation(flowStat).build());
+                    flowBuilder.addAugmentation(FlowStatisticsData.class,
+                            refineFlowStatisticsAugmentation(flowStat).build());
 
                     final short tableId = flowStat.getTableId();
-                    final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(flowBuilder.build());
-                    final FlowId flowId = registry.storeIfNecessary(flowRegistryKey);
+                    final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(deviceInfo.getVersion(), flowBuilder.build());
+                    registry.store(flowRegistryKey);
+                    final FlowId flowId = registry.retrieveDescriptor(flowRegistryKey).getFlowId();
 
                     final FlowKey flowKey = new FlowKey(flowId);
                     flowBuilder.setKey(flowKey);
                     final TableKey tableKey = new TableKey(tableId);
-                    final InstanceIdentifier<Flow> flowIdent = fNodeIdent.child(Table.class, tableKey).child(Flow.class, flowKey);
+                    final InstanceIdentifier<Flow> flowIdent
+                            = fNodeIdent.child(Table.class, tableKey).child(Flow.class, flowKey);
                     txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, flowIdent, flowBuilder.build());
                 }
             }
-        } catch (Exception e) {
-            LOG.warn("Not able to write to transaction: {}", e.getMessage());
+        } catch (TransactionChainClosedException e) {
+            LOG.warn("Not able to write to transaction chain: {}", e.getMessage());
         }
     }
 
     /**
-     * Method extracts flow statistics out of flowAndStatistics model
+     * Method extracts flow statistics out of flowAndStatistics model.
      *
-     * @param flowAndStats
+     * @param flowAndStats flow statistics map list
      */
-    private static FlowStatisticsDataBuilder refineFlowStatisticsAugmentation(final FlowAndStatisticsMapList flowAndStats) {
+    private static FlowStatisticsDataBuilder refineFlowStatisticsAugmentation(
+            final FlowAndStatisticsMapList flowAndStats) {
         final FlowStatisticsBuilder flowStatisticsBuilder = new FlowStatisticsBuilder(flowAndStats);
         final FlowStatisticsDataBuilder flowStatisticsDataBld = new FlowStatisticsDataBuilder();
         flowStatisticsDataBld.setFlowStatistics(flowStatisticsBuilder.build());
@@ -310,44 +372,68 @@ public final class StatisticsGatheringUtils {
     public static ListenableFuture<Void> deleteAllKnownFlows(final DeviceInfo deviceInfo,
                                                              final DeviceFlowRegistry registry,
                                                              final TxFacade txFacade) {
-        final InstanceIdentifier<FlowCapableNode> flowCapableNodePath = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
+        final InstanceIdentifier<FlowCapableNode> flowCapableNodePath
+                = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
         final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowCapableNodeFuture = readTx.read(
                 LogicalDatastoreType.OPERATIONAL, flowCapableNodePath);
 
         /* we wish to close readTx for fallBack */
-        Futures.withFallback(flowCapableNodeFuture, new FutureFallback<Optional<FlowCapableNode>>() {
-
-            @Override
-            public ListenableFuture<Optional<FlowCapableNode>> create(final Throwable t) throws Exception {
-                readTx.close();
-                return Futures.immediateFailedFuture(t);
-            }
+        Futures.withFallback(flowCapableNodeFuture, t -> {
+            readTx.close();
+            return Futures.immediateFailedFuture(t);
         });
         /*
          * we have to read actual tables with all information before we set empty Flow list, merge is expensive and
          * not applicable for lists
          */
-        return Futures.transform(flowCapableNodeFuture, new AsyncFunction<Optional<FlowCapableNode>, Void>() {
-
-            @Override
-            public ListenableFuture<Void> apply(final Optional<FlowCapableNode> flowCapNodeOpt) throws Exception {
-                if (flowCapNodeOpt.isPresent()) {
-                    for (final Table tableData : flowCapNodeOpt.get().getTable()) {
-                        final Table table = new TableBuilder(tableData).setFlow(Collections.<Flow>emptyList()).build();
-                        final InstanceIdentifier<Table> iiToTable = flowCapableNodePath.child(Table.class, tableData.getKey());
-                        txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
+        return Futures.transform(
+                flowCapableNodeFuture, (AsyncFunction<Optional<FlowCapableNode>, Void>) flowCapNodeOpt -> {
+                    if (flowCapNodeOpt.isPresent()) {
+                        for (final Table tableData : flowCapNodeOpt.get().getTable()) {
+                            final Table table = new TableBuilder(tableData).setFlow(Collections.<Flow>emptyList()).build();
+                            final InstanceIdentifier<Table> iiToTable
+                                    = flowCapableNodePath.child(Table.class, tableData.getKey());
+                            txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
+                        }
                     }
+                    readTx.close();
+                    return Futures.immediateFuture(null);
+                });
+    }
+
+    public static Optional<FlowCapableNode> deleteAllKnownFlows(final DeviceInfo deviceInfo,
+                                                             final TxFacade txFacade) {
+        final InstanceIdentifier<FlowCapableNode> flowCapableNodePath
+                = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
+        final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
+        final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowCapableNodeFuture = readTx.read(
+                LogicalDatastoreType.OPERATIONAL, flowCapableNodePath);
+
+        try {
+            Optional<FlowCapableNode> fcNodeOpt = flowCapableNodeFuture.get();
+            if ( fcNodeOpt != null && fcNodeOpt.isPresent()){
+                for (final Table tableData : flowCapableNodeFuture.get().get().getTable()) {
+                    final Table table = new TableBuilder(tableData).setFlow(Collections.<Flow>emptyList()).build();
+                    final InstanceIdentifier<Table> iiToTable = flowCapableNodePath.child(Table.class, tableData.getKey());
+                    txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
                 }
-                registry.removeMarked();
+                return fcNodeOpt;
+            }
+        } catch (InterruptedException|ExecutionException e) {
+            LOG.error("Failed to read current OpenFlow node {] operational data", deviceInfo.getNodeId());
+        } finally {
+            if (readTx != null){
                 readTx.close();
-                return Futures.immediateFuture(null);
             }
-
-        });
+        }
+        return Optional.absent();
     }
 
-    private static void processQueueStatistics(final Iterable<QueueStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+    private static void processQueueStatistics(
+            final Iterable<QueueStatisticsUpdate> data,
+            final DeviceInfo deviceInfo,
+            final TxFacade txFacade) throws TransactionChainClosedException {
         // TODO: clean all queues of all node-connectors before writing up-to-date stats
         final InstanceIdentifier<Node> nodeIdent = deviceInfo.getNodeInstanceIdentifier();
         for (final QueueStatisticsUpdate queueStatisticsUpdate : data) {
@@ -366,7 +452,8 @@ public final class StatisticsGatheringUtils {
                     final QueueBuilder queueBuilder = new QueueBuilder()
                             .setKey(qKey)
                             .setQueueId(queueStat.getQueueId())
-                            // node-connector-id is already contained in parent node and the port-id here is of incompatible format
+                            // node-connector-id is already contained in parent node
+                            // and the port-id here is of incompatible format
                             .addAugmentation(FlowCapableNodeConnectorQueueStatisticsData.class, statBuild.build());
                     txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, queueIdent, queueBuilder.build());
                 }
@@ -375,12 +462,16 @@ public final class StatisticsGatheringUtils {
         txFacade.submitTransaction();
     }
 
-    private static void processFlowTableStatistics(final Iterable<FlowTableStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+    private static void processFlowTableStatistics(
+            final Iterable<FlowTableStatisticsUpdate> data,
+            final DeviceInfo deviceInfo,
+            final TxFacade txFacade) throws TransactionChainClosedException {
         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
         for (final FlowTableStatisticsUpdate flowTableStatisticsUpdate : data) {
 
             for (final FlowTableAndStatisticsMap tableStat : flowTableStatisticsUpdate.getFlowTableAndStatisticsMap()) {
-                final InstanceIdentifier<FlowTableStatistics> tStatIdent = fNodeIdent.child(Table.class, new TableKey(tableStat.getTableId().getValue()))
+                final InstanceIdentifier<FlowTableStatistics> tStatIdent
+                        = fNodeIdent.child(Table.class, new TableKey(tableStat.getTableId().getValue()))
                         .augmentation(FlowTableStatisticsData.class).child(FlowTableStatistics.class);
                 final FlowTableStatistics stats = new FlowTableStatisticsBuilder(tableStat).build();
                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tStatIdent, stats);
@@ -389,12 +480,17 @@ public final class StatisticsGatheringUtils {
         txFacade.submitTransaction();
     }
 
-    private static void processNodeConnectorStatistics(final Iterable<NodeConnectorStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+    private static void processNodeConnectorStatistics(
+            final Iterable<NodeConnectorStatisticsUpdate> data,
+            final DeviceInfo deviceInfo,
+            final TxFacade txFacade) throws TransactionChainClosedException {
         final InstanceIdentifier<Node> nodeIdent = deviceInfo.getNodeInstanceIdentifier();
         for (final NodeConnectorStatisticsUpdate nodeConnectorStatisticsUpdate : data) {
-            for (final NodeConnectorStatisticsAndPortNumberMap nConnectPort : nodeConnectorStatisticsUpdate.getNodeConnectorStatisticsAndPortNumberMap()) {
-                final FlowCapableNodeConnectorStatistics stats = new FlowCapableNodeConnectorStatisticsBuilder(nConnectPort).build();
-                final NodeConnectorKey key = new NodeConnectorKey(nConnectPort.getNodeConnectorId());
+            for (final NodeConnectorStatisticsAndPortNumberMap nodeConnectPort :
+                    nodeConnectorStatisticsUpdate.getNodeConnectorStatisticsAndPortNumberMap()) {
+                final FlowCapableNodeConnectorStatistics stats
+                        = new FlowCapableNodeConnectorStatisticsBuilder(nodeConnectPort).build();
+                final NodeConnectorKey key = new NodeConnectorKey(nodeConnectPort.getNodeConnectorId());
                 final InstanceIdentifier<NodeConnector> nodeConnectorIdent = nodeIdent.child(NodeConnector.class, key);
                 final InstanceIdentifier<FlowCapableNodeConnectorStatisticsData> nodeConnStatIdent = nodeConnectorIdent
                         .augmentation(FlowCapableNodeConnectorStatisticsData.class);
@@ -408,12 +504,12 @@ public final class StatisticsGatheringUtils {
 
     private static void processMetersStatistics(final Iterable<MeterStatisticsUpdated> data,
                                                 final DeviceInfo deviceInfo,
-                                                final TxFacade txFacade) throws Exception {
+                                                final TxFacade txFacade) throws TransactionChainClosedException {
         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
         for (final MeterStatisticsUpdated meterStatisticsUpdated : data) {
-            for (final MeterStats mStat : meterStatisticsUpdated.getMeterStats()) {
-                final MeterStatistics stats = new MeterStatisticsBuilder(mStat).build();
-                final MeterId meterId = mStat.getMeterId();
+            for (final MeterStats meterStats : meterStatisticsUpdated.getMeterStats()) {
+                final MeterStatistics stats = new MeterStatisticsBuilder(meterStats).build();
+                final MeterId meterId = meterStats.getMeterId();
                 final InstanceIdentifier<Meter> meterIdent = fNodeIdent.child(Meter.class, new MeterKey(meterId));
                 final InstanceIdentifier<NodeMeterStatistics> nodeMeterStatIdent = meterIdent
                         .augmentation(NodeMeterStatistics.class);
@@ -424,15 +520,22 @@ public final class StatisticsGatheringUtils {
         txFacade.submitTransaction();
     }
 
-    private static void deleteAllKnownMeters(final DeviceMeterRegistry meterRegistry, final InstanceIdentifier<FlowCapableNode> fNodeIdent, final TxFacade txFacade) throws Exception {
-        for (final MeterId meterId : meterRegistry.getAllMeterIds()) {
-            final InstanceIdentifier<Meter> meterIdent = fNodeIdent.child(Meter.class, new MeterKey(meterId));
+    private static void deleteAllKnownMeters(
+            final DeviceMeterRegistry meterRegistry,
+            final InstanceIdentifier<FlowCapableNode> flowNodeIdent,
+            final TxFacade txFacade) throws TransactionChainClosedException {
+        meterRegistry.forEach(meterId -> {
+            final InstanceIdentifier<Meter> meterIdent = flowNodeIdent.child(Meter.class, new MeterKey(meterId));
             txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, meterIdent);
-        }
-        meterRegistry.removeMarked();
+        });
+        meterRegistry.processMarks();
     }
 
-    private static void processGroupDescStats(final Iterable<GroupDescStatsUpdated> data, final DeviceInfo deviceInfo, final TxFacade txFacade, final DeviceGroupRegistry groupRegistry) throws Exception {
+    private static void processGroupDescStats(
+            final Iterable<GroupDescStatsUpdated> data,
+            final DeviceInfo deviceInfo,
+            final TxFacade txFacade,
+            final DeviceGroupRegistry groupRegistry) throws TransactionChainClosedException {
         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
         deleteAllKnownGroups(txFacade, fNodeIdent, groupRegistry);
 
@@ -453,20 +556,27 @@ public final class StatisticsGatheringUtils {
         txFacade.submitTransaction();
     }
 
-    private static void deleteAllKnownGroups(final TxFacade txFacade, final InstanceIdentifier<FlowCapableNode> fNodeIdent, final DeviceGroupRegistry groupRegistry) throws Exception {
-        for (final GroupId groupId : groupRegistry.getAllGroupIds()) {
-            final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupId));
+    private static void deleteAllKnownGroups(
+            final TxFacade txFacade,
+            final InstanceIdentifier<FlowCapableNode> flowNodeIdent,
+            final DeviceGroupRegistry groupRegistry) throws TransactionChainClosedException {
+        groupRegistry.forEach(groupId -> {
+            final InstanceIdentifier<Group> groupIdent = flowNodeIdent.child(Group.class, new GroupKey(groupId));
             txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, groupIdent);
-        }
-        groupRegistry.removeMarked();
+        });
+        groupRegistry.processMarks();
     }
 
-    private static void processGroupStatistics(final Iterable<GroupStatisticsUpdated> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+    private static void processGroupStatistics(
+            final Iterable<GroupStatisticsUpdated> data,
+            final DeviceInfo deviceInfo,
+            final TxFacade txFacade) throws TransactionChainClosedException {
         final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
         for (final GroupStatisticsUpdated groupStatistics : data) {
             for (final GroupStats groupStats : groupStatistics.getGroupStats()) {
 
-                final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupStats.getGroupId()));
+                final InstanceIdentifier<Group> groupIdent
+                        = fNodeIdent.child(Group.class, new GroupKey(groupStats.getGroupId()));
                 final InstanceIdentifier<NodeGroupStatistics> nGroupStatIdent = groupIdent
                         .augmentation(NodeGroupStatistics.class);
 
@@ -478,12 +588,13 @@ public final class StatisticsGatheringUtils {
         txFacade.submitTransaction();
     }
 
-    private static InstanceIdentifier<FlowCapableNode> assembleFlowCapableNodeInstanceIdentifier(final DeviceInfo deviceInfo) {
+    private static InstanceIdentifier<FlowCapableNode> assembleFlowCapableNodeInstanceIdentifier(
+            final DeviceInfo deviceInfo) {
         return deviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
     }
 
     /**
-     * Writes snapshot gathering start timestamp + cleans end mark
+     * Writes snapshot gathering start timestamp + cleans end mark.
      *
      * @param deviceContext txManager + node path keeper
      */
@@ -500,15 +611,16 @@ public final class StatisticsGatheringUtils {
                 .build();
         try {
             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusPath, gatheringStatus);
-        } catch (final Exception e) {
-            LOG.warn("Can't write to transaction: {}", e);
+        } catch (final TransactionChainClosedException e) {
+            LOG.warn("Can't write to transaction, transaction chain probably closed.");
+            LOG.trace("Write to transaction exception: ", e);
         }
 
         deviceContext.submitTransaction();
     }
 
     /**
-     * Writes snapshot gathering end timestamp + outcome
+     * Writes snapshot gathering end timestamp + outcome.
      *
      * @param deviceContext txManager + node path keeper
      * @param succeeded     outcome of currently finished gathering
@@ -525,8 +637,9 @@ public final class StatisticsGatheringUtils {
                 .build();
         try {
             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, statusEndPath, gatheringStatus);
-        } catch (Exception e) {
-            LOG.warn("Can't write to transaction: {}", e);
+        } catch (TransactionChainClosedException e) {
+            LOG.warn("Can't write to transaction, transaction chain probably closed.");
+            LOG.trace("Write to transaction exception: ", e);
         }
 
         deviceContext.submitTransaction();