Bug 5692 - Direct statistics RPC
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceContextImpl.java
index 70de1190aa69736d31f1456ab2ba85dfea826cd7..1d82ea0f2f89d7e7784f5e12fc33088842ca7718 100644 (file)
@@ -9,34 +9,25 @@ package org.opendaylight.openflowplugin.impl.device;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Function;
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.base.Verify;
 import com.google.common.util.concurrent.AsyncFunction;
-import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
-import io.netty.util.HashedWheelTimer;
 import io.netty.util.Timeout;
 import java.math.BigInteger;
-import java.util.Collection;
-import java.util.Collections;
 import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
 import javax.annotation.CheckForNull;
 import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
-import org.opendaylight.controller.md.sal.binding.api.NotificationService;
 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.TransactionCommitFailedException;
 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
 import org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey;
@@ -48,8 +39,8 @@ import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
-import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextClosedHandler;
 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
@@ -75,8 +66,9 @@ import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl
 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
 import org.opendaylight.openflowplugin.impl.registry.group.DeviceGroupRegistryImpl;
 import org.opendaylight.openflowplugin.impl.registry.meter.DeviceMeterRegistryImpl;
+import org.opendaylight.openflowplugin.impl.rpc.RpcContextImpl;
 import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils;
-import org.opendaylight.openflowplugin.impl.util.MdSalRegistratorUtils;
+import org.opendaylight.openflowplugin.impl.util.MdSalRegistrationUtils;
 import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.message.service.rev151020.ExperimenterMessageFromDevBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
@@ -86,6 +78,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.ta
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
@@ -121,7 +114,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     private static final Logger LOG = LoggerFactory.getLogger(DeviceContextImpl.class);
 
     // TODO: drain factor should be parametrized
-    public static final float REJECTED_DRAIN_FACTOR = 0.25f;
+    private static final float REJECTED_DRAIN_FACTOR = 0.25f;
     // TODO: low water mark factor should be parametrized
     private static final float LOW_WATERMARK_FACTOR = 0.75f;
     // TODO: high water mark factor should be parametrized
@@ -130,18 +123,15 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     private final ConnectionContext primaryConnectionContext;
     private final DeviceState deviceState;
     private final DataBroker dataBroker;
-    private final HashedWheelTimer hashedWheelTimer;
     private final Map<SwitchConnectionDistinguisher, ConnectionContext> auxiliaryConnectionContexts;
     private final TransactionChainManager transactionChainManager;
     private final DeviceFlowRegistry deviceFlowRegistry;
     private final DeviceGroupRegistry deviceGroupRegistry;
     private final DeviceMeterRegistry deviceMeterRegistry;
-    private final Collection<DeviceContextClosedHandler> closeHandlers = new HashSet<>();
     private final PacketInRateLimiter packetInLimiter;
     private final MessageSpy messageSpy;
     private final ItemLifeCycleKeeper flowLifeCycleKeeper;
     private NotificationPublishService notificationPublishService;
-    private NotificationService notificationService;
     private final OutboundQueue outboundQueueProvider;
     private Timeout barrierTaskTimeout;
     private final MessageTranslator<PortGrouping, FlowCapableNodeConnector> portStatusTranslator;
@@ -154,15 +144,19 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     private ExtensionConverterProvider extensionConverterProvider;
 
     private final boolean switchFeaturesMandatory;
-    private StatisticsContext statCtx;
+    private StatisticsContext statisticsContext;
+
+    private final NodeId nodeId;
+
+    private volatile DEVICE_CONTEXT_STATE deviceCtxState;
+    private boolean isStatisticsRpcEnabled;
 
 
     @VisibleForTesting
     DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
                       @Nonnull final DeviceState deviceState,
                       @Nonnull final DataBroker dataBroker,
-                      @Nonnull final HashedWheelTimer hashedWheelTimer,
-                      @Nonnull final MessageSpy _messageSpy,
+                      @Nonnull final LifecycleConductor conductor,
                       @Nonnull final OutboundQueueProvider outboundQueueProvider,
                       @Nonnull final TranslatorLibrary translatorLibrary,
                       final boolean switchFeaturesMandatory) {
@@ -170,15 +164,14 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         this.primaryConnectionContext = Preconditions.checkNotNull(primaryConnectionContext);
         this.deviceState = Preconditions.checkNotNull(deviceState);
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
-        this.hashedWheelTimer = Preconditions.checkNotNull(hashedWheelTimer);
+        Preconditions.checkNotNull(conductor);
         this.outboundQueueProvider = Preconditions.checkNotNull(outboundQueueProvider);
-        primaryConnectionContext.setDeviceDisconnectedHandler(DeviceContextImpl.this);
-        this.transactionChainManager = new TransactionChainManager(dataBroker, deviceState);
+        this.transactionChainManager = new TransactionChainManager(dataBroker, deviceState, conductor);
         auxiliaryConnectionContexts = new HashMap<>();
         deviceFlowRegistry = new DeviceFlowRegistryImpl();
         deviceGroupRegistry = new DeviceGroupRegistryImpl();
         deviceMeterRegistry = new DeviceMeterRegistryImpl();
-        messageSpy = _messageSpy;
+        messageSpy = conductor.getMessageIntelligenceAgency();
 
         packetInLimiter = new PacketInRateLimiter(primaryConnectionContext.getConnectionAdapter(),
                 /*initial*/ 1000, /*initial*/2000, messageSpy, REJECTED_DRAIN_FACTOR);
@@ -197,6 +190,9 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         itemLifeCycleSourceRegistry = new ItemLifeCycleRegistryImpl();
         flowLifeCycleKeeper = new ItemLifeCycleSourceImpl();
         itemLifeCycleSourceRegistry.registerLifeCycleSource(flowLifeCycleKeeper);
+        deviceCtxState = DEVICE_CONTEXT_STATE.INITIALIZATION;
+
+        nodeId = primaryConnectionContext.getNodeId();
     }
 
     /**
@@ -208,12 +204,12 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public Long reservedXidForDeviceMessage() {
+    public Long reserveXidForDeviceMessage() {
         return outboundQueueProvider.reserveEntry();
     }
 
     @Override
-    public void addAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
+    public void addAuxiliaryConnectionContext(final ConnectionContext connectionContext) {
         final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
         auxiliaryConnectionContexts.put(connectionDistinguisher, connectionContext);
     }
@@ -223,8 +219,11 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public void removeAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
-        // TODO Auto-generated method stub
+    public void removeAuxiliaryConnectionContext(final ConnectionContext connectionContext) {
+        final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
+        LOG.debug("auxiliary connection dropped: {}, nodeId:{}", connectionContext.getConnectionAdapter()
+                .getRemoteAddress(), nodeId);
+        auxiliaryConnectionContexts.remove(connectionDistinguisher);
     }
 
     @Override
@@ -239,77 +238,69 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
 
     @Override
     public ListenableFuture<Void> onClusterRoleChange(final OfpRole oldRole, @CheckForNull final OfpRole role) {
-        LOG.trace("onClusterRoleChange {} for node:", role, deviceState.getNodeId());
+        LOG.trace("onClusterRoleChange {} for node:", role, nodeId);
         Preconditions.checkArgument(role != null);
         if (role.equals(oldRole)) {
-            LOG.debug("Demanded role change for device {} is not change OldRole: {}, NewRole {}", deviceState.getNodeId(), oldRole, role);
+            LOG.debug("Demanded role change for device {} is not changed. OldRole: {}, NewRole {}", nodeId, oldRole, role);
             return Futures.immediateFuture(null);
         }
         if (OfpRole.BECOMEMASTER.equals(role)) {
-            if (!deviceState.deviceSynchronized()) {
-                //TODO: no necessary code for yet - it needs for initialization phase only
-                LOG.debug("Setup Empty TxManager {} for initialization phase", getDeviceState().getNodeId());
-                transactionChainManager.activateTransactionManager();
-                return Futures.immediateCheckedFuture(null);
-            }
-            /* Relevant for no initial Slave-to-Master scenario in cluster */
-            return asyncClusterRoleChange(role);
-
+            return onDeviceTakeClusterLeadership();
         } else if (OfpRole.BECOMESLAVE.equals(role)) {
-            if (null != rpcContext) {
-                MdSalRegistratorUtils.registerSlaveServices(rpcContext, role);
-            }
-            return transactionChainManager.deactivateTransactionManager();
+            return onDeviceLostClusterLeadership();
         } else {
-            LOG.warn("Unknown OFCluster Role {} for Node {}", role, deviceState.getNodeId());
+            LOG.warn("Unknown OFCluster Role {} for Node {}", role, nodeId);
             if (null != rpcContext) {
-                MdSalRegistratorUtils.unregisterServices(rpcContext);
+                MdSalRegistrationUtils.unregisterServices(rpcContext);
             }
             return transactionChainManager.deactivateTransactionManager();
         }
     }
 
-    /*
-     * we don't have active TxManager so anything will not be stored to DS yet, but we have
-     * check all NodeInformation for statistics otherwise statistics will not contains
-     * all possible MultipartTypes for polling in StatTypeList
-     */
-    private ListenableFuture<Void> asyncClusterRoleChange(final OfpRole role) {
-        if (statCtx == null) {
-            final String errMsg = String.format("DeviceCtx {} is up but we are missing StatisticsContext", deviceState.getNodeId());
+    @Override
+    public ListenableFuture<Void> onDeviceLostClusterLeadership() {
+        LOG.trace("onDeviceLostClusterLeadership for node: {}", nodeId);
+        if (null != rpcContext) {
+            MdSalRegistrationUtils.registerSlaveServices(rpcContext, OfpRole.BECOMESLAVE);
+        }
+        return transactionChainManager.deactivateTransactionManager();
+    }
+
+    @Override
+    public ListenableFuture<Void> onDeviceTakeClusterLeadership() {
+        LOG.trace("onDeviceTakeClusterLeadership for node: {}", nodeId);
+        /* validation */
+        if (statisticsContext == null) {
+            final String errMsg = String.format("DeviceCtx %s is up but we are missing StatisticsContext", nodeId);
             LOG.warn(errMsg);
             return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
         }
+        if (rpcContext == null) {
+            final String errMsg = String.format("DeviceCtx %s is up but we are missing RpcContext", nodeId);
+            LOG.warn(errMsg);
+            return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
+        }
+        /* Routed RPC registration */
+        MdSalRegistrationUtils.registerMasterServices(getRpcContext(), DeviceContextImpl.this, OfpRole.BECOMEMASTER);
 
-        final InstanceIdentifier<FlowCapableNode> ofNodeII = deviceState.getNodeInstanceIdentifier()
-                .augmentation(FlowCapableNode.class);
-        final ReadOnlyTransaction readTx = getReadTransaction();
-        final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> readOfNodeFuture = readTx.read(
-                LogicalDatastoreType.OPERATIONAL, ofNodeII);
-
-        final ListenableFuture<Void> nodeInitInfoFuture = Futures.transform(readOfNodeFuture,
-                new AsyncFunction<Optional<FlowCapableNode>, Void>() {
-                    @Override
-                    public ListenableFuture<Void> apply(final Optional<FlowCapableNode> input) throws Exception {
-                        if (!input.isPresent() || input.get().getTable() != null || input.get().getTable().isEmpty()) {
-                            /* Last master close fail scenario so we would like to activate TxManager */
-                            LOG.debug("Operational DS for Device {} has to be replaced", deviceState.getNodeId());
-                            getDeviceState().setDeviceSynchronized(false);
-                            transactionChainManager.activateTransactionManager();
-                        }
-                        return DeviceInitializationUtils.initializeNodeInformation(DeviceContextImpl.this, switchFeaturesMandatory);
-                    }
-                });
+        if (isStatisticsRpcEnabled) {
+            MdSalRegistrationUtils.registerStatCompatibilityServices(getRpcContext(), this,
+                    notificationPublishService, new AtomicLong());
+        }
 
-        final ListenableFuture<Boolean> statPollFuture = Futures.transform(nodeInitInfoFuture,
+        /* Prepare init info collecting */
+        getDeviceState().setDeviceSynchronized(false);
+        transactionChainManager.activateTransactionManager();
+        /* Init Collecting NodeInfo */
+        final ListenableFuture<Void> initCollectingDeviceInfo = DeviceInitializationUtils.initializeNodeInformation(
+                DeviceContextImpl.this, switchFeaturesMandatory);
+        /* Init Collecting StatInfo */
+        final ListenableFuture<Boolean> statPollFuture = Futures.transform(initCollectingDeviceInfo,
                 new AsyncFunction<Void, Boolean>() {
 
                     @Override
-                    public ListenableFuture<Boolean> apply(final Void input) throws Exception {
+                    public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
                         getStatisticsContext().statListForCollectingInitialization();
-                        if (getDeviceState().deviceSynchronized()) {
-                            return Futures.immediateFuture(Boolean.TRUE);
-                        }
                         return getStatisticsContext().gatherDynamicData();
                     }
                 });
@@ -318,22 +309,20 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
 
             @Override
             public Void apply(final Boolean input) {
-                if (!input.booleanValue()) {
-                    LOG.warn("Get Initial Device {} information fails", getDeviceState().getNodeId());
-                    DeviceContextImpl.this.close();
-                    return null;
+                if (ConnectionContext.CONNECTION_STATE.RIP.equals(getPrimaryConnectionContext().getConnectionState())) {
+                    final String errMsg = String.format("We lost connection for Device %s, context has to be closed.",
+                            getDeviceState().getNodeId());
+                    LOG.warn(errMsg);
+                    throw new IllegalStateException(errMsg);
                 }
-                LOG.debug("Get Initial Device {} information is successful", getDeviceState().getNodeId());
-                getDeviceState().setDeviceSynchronized(true);
-                transactionChainManager.activateTransactionManager();
-                //TODO: This is relevant for slave to master scenario make verify
-                if (null != rpcContext) {
-                    MdSalRegistratorUtils.registerMasterServices(getRpcContext(), DeviceContextImpl.this, role);
-                    getRpcContext().registerStatCompatibilityServices();
-                } else {
-                    LOG.warn("No RpcCtx on deviceCtx: {}, cannot register services", this);
-                    // TODO : can we stay without RPCs or we need to call DeviceCtx.close ?
+                if (!input) {
+                    final String errMsg = String.format("Get Initial Device %s information fails",
+                            getDeviceState().getNodeId());
+                    LOG.warn(errMsg);
+                    throw new IllegalStateException(errMsg);
                 }
+                LOG.debug("Get Initial Device {} information is successful", nodeId);
+                getDeviceState().setDeviceSynchronized(true);
                 initialSubmitTransaction();
                 getDeviceState().setStatisticsPollingEnabledProp(true);
                 return null;
@@ -343,12 +332,17 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
 
     @Override
     public <T extends DataObject> void writeToTransaction(final LogicalDatastoreType store,
-                                                          final InstanceIdentifier<T> path, final T data) {
-        transactionChainManager.writeToTransaction(store, path, data);
+                                                          final InstanceIdentifier<T> path, final T data) throws Exception {
+        transactionChainManager.writeToTransaction(store, path, data, false);
     }
 
     @Override
-    public <T extends DataObject> void addDeleteToTxChain(final LogicalDatastoreType store, final InstanceIdentifier<T> path) {
+    public <T extends DataObject> void writeToTransactionWithParentsSlow(LogicalDatastoreType store, InstanceIdentifier<T> path, T data) throws Exception {
+        transactionChainManager.writeToTransaction(store, path, data, true);
+    }
+
+    @Override
+    public <T extends DataObject> void addDeleteToTxChain(final LogicalDatastoreType store, final InstanceIdentifier<T> path) throws Exception {
         transactionChainManager.addDeleteOperationTotTxChain(store, path);
     }
 
@@ -404,7 +398,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         if (itemLifecycleListener != null) {
             //1. translate to general flow (table, priority, match, cookie)
             final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved flowRemovedNotification =
-                    flowRemovedTranslator.translate(flowRemoved, this, null);
+                    flowRemovedTranslator.translate(flowRemoved, this.getDeviceState(), null);
             //2. create registry key
             final FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedNotification);
             //3. lookup flowId
@@ -428,19 +422,23 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     @Override
     public void processPortStatusMessage(final PortStatusMessage portStatus) {
         messageSpy.spyMessage(portStatus.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
-        final FlowCapableNodeConnector flowCapableNodeConnector = portStatusTranslator.translate(portStatus, this, null);
+        final FlowCapableNodeConnector flowCapableNodeConnector = portStatusTranslator.translate(portStatus, this.getDeviceState(), null);
 
         final KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> iiToNodeConnector = provideIIToNodeConnector(portStatus.getPortNo(), portStatus.getVersion());
-        if (portStatus.getReason().equals(PortReason.OFPPRADD) || portStatus.getReason().equals(PortReason.OFPPRMODIFY)) {
-            // because of ADD status node connector has to be created
-            final NodeConnectorBuilder nConnectorBuilder = new NodeConnectorBuilder().setKey(iiToNodeConnector.getKey());
-            nConnectorBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build());
-            nConnectorBuilder.addAugmentation(FlowCapableNodeConnector.class, flowCapableNodeConnector);
-            writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector, nConnectorBuilder.build());
-        } else if (portStatus.getReason().equals(PortReason.OFPPRDELETE)) {
-            addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector);
+        try {
+            if (portStatus.getReason().equals(PortReason.OFPPRADD) || portStatus.getReason().equals(PortReason.OFPPRMODIFY)) {
+                // because of ADD status node connector has to be created
+                final NodeConnectorBuilder nConnectorBuilder = new NodeConnectorBuilder().setKey(iiToNodeConnector.getKey());
+                nConnectorBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build());
+                nConnectorBuilder.addAugmentation(FlowCapableNodeConnector.class, flowCapableNodeConnector);
+                writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector, nConnectorBuilder.build());
+            } else if (portStatus.getReason().equals(PortReason.OFPPRDELETE)) {
+                addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector);
+            }
+            submitTransaction();
+        } catch (final Exception e) {
+            LOG.warn("Error processing port status message: {}", e.getMessage());
         }
-        submitTransaction();
     }
 
     private KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> provideIIToNodeConnector(final long portNo, final short version) {
@@ -454,11 +452,11 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     public void processPacketInMessage(final PacketInMessage packetInMessage) {
         messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH);
         final ConnectionAdapter connectionAdapter = getPrimaryConnectionContext().getConnectionAdapter();
-        final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, this, null);
+        final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, this.getDeviceState(), null);
 
         if (packetReceived == null) {
             LOG.debug("Received a null packet from switch {}", connectionAdapter.getRemoteAddress());
-            messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_SRC_FAILURE);
+            messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_SRC_FAILURE);
             return;
         } else {
             messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_OUT_SUCCESS);
@@ -471,7 +469,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
             return;
         }
 
-        final ListenableFuture<? extends Object> offerNotification = notificationPublishService.offerNotification(packetReceived);
+        final ListenableFuture<?> offerNotification = notificationPublishService.offerNotification(packetReceived);
         if (NotificationPublishService.REJECTED.equals(offerNotification)) {
             LOG.debug("notification offer rejected");
             messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED);
@@ -521,7 +519,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
             // publish
             notificationPublishService.offerNotification(experimenterMessageFromDevBld.build());
         } catch (final ConversionException e) {
-            LOG.warn("Conversion of experimenter notification failed", e);
+            LOG.error("Conversion of experimenter notification failed", e);
         }
     }
 
@@ -531,80 +529,12 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public HashedWheelTimer getTimer() {
-        return hashedWheelTimer;
-    }
-
-    @Override
-    public void close() {
+    public synchronized void close() {
         LOG.debug("closing deviceContext: {}, nodeId:{}",
                 getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress(),
                 getDeviceState().getNodeId());
-
-        tearDown();
-
-        primaryConnectionContext.closeConnection(false);
-    }
-
-    private synchronized void tearDown() {
-        LOG.trace("tearDown method for node {}", deviceState.getNodeId());
-        if (deviceState.isValid()) {
-            deviceState.setValid(false);
-
-            for (final ConnectionContext connectionContext : auxiliaryConnectionContexts.values()) {
-                connectionContext.closeConnection(false);
-            }
-
-            deviceGroupRegistry.close();
-            deviceFlowRegistry.close();
-            deviceMeterRegistry.close();
-
-            final CheckedFuture<Void, TransactionCommitFailedException> future = transactionChainManager.shuttingDown();
-            Futures.addCallback(future, new FutureCallback<Void>() {
-
-                @Override
-                public void onSuccess(final Void result) {
-                    LOG.info("TxChain {} was shutdown successfull.", getDeviceState().getNodeId());
-                    tearDownClean();
-                }
-
-                @Override
-                public void onFailure(final Throwable t) {
-                    LOG.warn("Shutdown TxChain {} fail.", getDeviceState().getNodeId(), t);
-                    tearDownClean();
-                }
-            });
-        }
-    }
-
-    protected void tearDownClean() {
-        LOG.info("Closing transaction chain manager without cleaning inventory operational");
-        Preconditions.checkState(!deviceState.isValid());
-        transactionChainManager.close();
-
-        final LinkedList<DeviceContextClosedHandler> reversedCloseHandlers = new LinkedList<>(closeHandlers);
-        Collections.reverse(reversedCloseHandlers);
-        for (final DeviceContextClosedHandler deviceContextClosedHandler : reversedCloseHandlers) {
-            deviceContextClosedHandler.onDeviceContextClosed(this);
-        }
-        closeHandlers.clear();
-    }
-
-    @Override
-    public void onDeviceDisconnected(final ConnectionContext connectionContext) {
-        if (getPrimaryConnectionContext().equals(connectionContext)) {
-            try {
-                tearDown();
-            } catch (final Exception e) {
-                LOG.trace("Error closing device context.");
-            }
-        } else {
-            LOG.debug("auxiliary connection dropped: {}, nodeId:{}",
-                    connectionContext.getConnectionAdapter().getRemoteAddress(),
-                    getDeviceState().getNodeId());
-            final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
-            auxiliaryConnectionContexts.remove(connectionDistinguisher);
-        }
+        // NOOP
+        throw new UnsupportedOperationException("Autocloseble.close will be removed soon");
     }
 
     @Override
@@ -617,11 +547,6 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         return barrierTaskTimeout;
     }
 
-    @Override
-    public void setNotificationService(final NotificationService notificationServiceParam) {
-        notificationService = notificationServiceParam;
-    }
-
     @Override
     public void setNotificationPublishService(final NotificationPublishService notificationPublishService) {
         this.notificationPublishService = notificationPublishService;
@@ -632,13 +557,10 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         return messageSpy;
     }
 
-    @Override
-    public void addDeviceContextClosedHandler(final DeviceContextClosedHandler deviceContextClosedHandler) {
-        closeHandlers.add(deviceContextClosedHandler);
-    }
-
     @Override
     public void onPublished() {
+        Verify.verify(DEVICE_CONTEXT_STATE.INITIALIZATION.equals(deviceCtxState));
+        deviceCtxState = DEVICE_CONTEXT_STATE.WORKING;
         primaryConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
         for (final ConnectionContext switchAuxConnectionContext : auxiliaryConnectionContexts.values()) {
             switchAuxConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
@@ -656,7 +578,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public void storeNodeConnectorRef(final Long portNumber, final NodeConnectorRef nodeConnectorRef) {
+    public void storeNodeConnectorRef(@Nonnull final Long portNumber, @Nonnull final NodeConnectorRef nodeConnectorRef) {
         nodeConnectorCache.put(
                 Preconditions.checkNotNull(portNumber),
                 Preconditions.checkNotNull(nodeConnectorRef));
@@ -694,11 +616,59 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
 
     @Override
     public void setStatisticsContext(final StatisticsContext statisticsContext) {
-        this.statCtx = statisticsContext;
+        this.statisticsContext = statisticsContext;
     }
 
     @Override
     public StatisticsContext getStatisticsContext() {
-        return statCtx;
+        return statisticsContext;
+    }
+
+    @Override
+    public synchronized void shutdownConnection() {
+        LOG.debug("Shutdown method for node {}", nodeId);
+        deviceState.setValid(false);
+        if (DEVICE_CONTEXT_STATE.TERMINATION.equals(deviceCtxState)) {
+            LOG.debug("DeviceCtx for Node {} is in termination process.", nodeId);
+            return;
+        }
+        deviceCtxState = DEVICE_CONTEXT_STATE.TERMINATION;
+
+        if (ConnectionContext.CONNECTION_STATE.RIP.equals(getPrimaryConnectionContext().getConnectionState())) {
+            LOG.debug("ConnectionCtx for Node {} is in RIP state.", deviceState.getNodeId());
+            return;
+        }
+        /* Terminate Auxiliary Connection */
+        for (final ConnectionContext connectionContext : auxiliaryConnectionContexts.values()) {
+            LOG.debug("Closing auxiliary connection {}", connectionContext.getNodeId());
+            connectionContext.closeConnection(false);
+        }
+        /* Terminate Primary Connection */
+        getPrimaryConnectionContext().closeConnection(true);
+        /* Close all Group Registry */
+        deviceGroupRegistry.close();
+        deviceFlowRegistry.close();
+        deviceMeterRegistry.close();
+    }
+
+    @Override
+    public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
+        this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
+    }
+
+    @Override
+    public DEVICE_CONTEXT_STATE getDeviceContextState() {
+        return deviceCtxState;
+    }
+
+    @Override
+    public ListenableFuture<Void> shuttingDownDataStoreTransactions() {
+        deviceState.setValid(false);
+        return transactionChainManager.shuttingDown();
+    }
+
+    @VisibleForTesting
+    TransactionChainManager getTransactionChainManager() {
+        return this.transactionChainManager;
     }
 }