Bump odlparent to 5.0.0
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceContextImpl.java
index 7b4ba521f00b048562c08b29ec1977d436d0a030..4f660f55b4511420dcd50313d3c5383b1c6c70ae 100644 (file)
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -10,16 +10,16 @@ package org.opendaylight.openflowplugin.impl.device;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import io.netty.util.HashedWheelTimer;
-import io.netty.util.TimerTask;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
@@ -27,10 +27,10 @@ import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
 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.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.NotificationPublishService;
+import org.opendaylight.mdsal.binding.api.ReadTransaction;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
 import org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey;
@@ -44,33 +44,28 @@ 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.MultiMsgCollector;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChain;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainHolder;
 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipState;
 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipWatcher;
 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainState;
 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
 import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
-import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
-import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
-import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleKeeper;
-import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
+import org.opendaylight.openflowplugin.common.txchain.TransactionChainManager;
 import org.opendaylight.openflowplugin.extension.api.ConvertorMessageFromOFJava;
 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
-import org.opendaylight.openflowplugin.extension.api.exception.ConversionException;
 import org.opendaylight.openflowplugin.extension.api.path.MessagePath;
-import org.opendaylight.openflowplugin.impl.common.ItemLifeCycleSourceImpl;
 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProvider;
 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProviderFactory;
 import org.opendaylight.openflowplugin.impl.device.initialization.AbstractDeviceInitializer;
 import org.opendaylight.openflowplugin.impl.device.initialization.DeviceInitializerProvider;
 import org.opendaylight.openflowplugin.impl.device.listener.MultiMsgCollectorImpl;
 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.AbstractRequestContext;
@@ -81,9 +76,6 @@ import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil
 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;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
@@ -106,16 +98,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.Pa
 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleOutput;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -130,9 +116,6 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     // TODO: high water mark factor should be parametrized
     private static final float HIGH_WATERMARK_FACTOR = 0.95f;
 
-    // Timeout in seconds after what we will give up on propagating role
-    private static final int SET_ROLE_TIMEOUT = 10;
-
     // Timeout in milliseconds after what we will give up on initializing device
     private static final int DEVICE_INIT_TIMEOUT = 9000;
 
@@ -146,14 +129,13 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     private final HashedWheelTimer hashedWheelTimer;
     private final DeviceState deviceState;
     private final DataBroker dataBroker;
-    private final Collection<RequestContext<?>> requestContexts = new HashSet<>();
+    private final Collection<RequestContext<?>> requestContexts = ConcurrentHashMap.newKeySet();
     private final MessageSpy messageSpy;
-    private final ItemLifeCycleKeeper flowLifeCycleKeeper;
     private final MessageTranslator<PortGrouping, FlowCapableNodeConnector> portStatusTranslator;
     private final MessageTranslator<PacketInMessage, PacketReceived> packetInTranslator;
-    private final MessageTranslator<FlowRemoved, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved> flowRemovedTranslator;
+    private final MessageTranslator<FlowRemoved, org.opendaylight.yang.gen.v1.urn.opendaylight
+            .flow.service.rev130819.FlowRemoved> flowRemovedTranslator;
     private final TranslatorLibrary translatorLibrary;
-    private final ItemLifeCycleRegistry itemLifeCycleSourceRegistry;
     private final ConvertorExecutor convertorExecutor;
     private final DeviceInitializerProvider deviceInitializerProvider;
     private final PacketInRateLimiter packetInLimiter;
@@ -166,27 +148,27 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     private final AtomicBoolean initialized = new AtomicBoolean(false);
     private final AtomicBoolean hasState = new AtomicBoolean(false);
     private final AtomicBoolean isInitialTransactionSubmitted = new AtomicBoolean(false);
+    private final ContextChainHolder contextChainHolder;
     private NotificationPublishService notificationPublishService;
     private TransactionChainManager transactionChainManager;
     private DeviceFlowRegistry deviceFlowRegistry;
     private DeviceGroupRegistry deviceGroupRegistry;
     private DeviceMeterRegistry deviceMeterRegistry;
     private ExtensionConverterProvider extensionConverterProvider;
-    private SalRoleService salRoleService;
     private ContextChainMastershipWatcher contextChainMastershipWatcher;
 
-    DeviceContextImpl(
-            @Nonnull final ConnectionContext primaryConnectionContext,
-            @Nonnull final DataBroker dataBroker,
-            @Nonnull final MessageSpy messageSpy,
-            @Nonnull final TranslatorLibrary translatorLibrary,
-            final ConvertorExecutor convertorExecutor,
-            final boolean skipTableFeatures,
-            final HashedWheelTimer hashedWheelTimer,
-            final boolean useSingleLayerSerialization,
-            final DeviceInitializerProvider deviceInitializerProvider,
-            final boolean isFlowRemovedNotificationOn,
-            final boolean switchFeaturesMandatory) {
+    DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
+                      @Nonnull final DataBroker dataBroker,
+                      @Nonnull final MessageSpy messageSpy,
+                      @Nonnull final TranslatorLibrary translatorLibrary,
+                      final ConvertorExecutor convertorExecutor,
+                      final boolean skipTableFeatures,
+                      final HashedWheelTimer hashedWheelTimer,
+                      final boolean useSingleLayerSerialization,
+                      final DeviceInitializerProvider deviceInitializerProvider,
+                      final boolean isFlowRemovedNotificationOn,
+                      final boolean switchFeaturesMandatory,
+                      final ContextChainHolder contextChainHolder) {
 
         this.primaryConnectionContext = primaryConnectionContext;
         this.deviceInfo = primaryConnectionContext.getDeviceInfo();
@@ -197,6 +179,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         this.deviceState = new DeviceStateImpl();
         this.dataBroker = dataBroker;
         this.messageSpy = messageSpy;
+        this.contextChainHolder = contextChainHolder;
 
         this.packetInLimiter = new PacketInRateLimiter(primaryConnectionContext.getConnectionAdapter(),
                 /*initial*/ LOW_WATERMARK, /*initial*/HIGH_WATERMARK, this.messageSpy, REJECTED_DRAIN_FACTOR);
@@ -205,14 +188,12 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         this.portStatusTranslator = translatorLibrary.lookupTranslator(
                 new TranslatorKey(deviceInfo.getVersion(), PortGrouping.class.getName()));
         this.packetInTranslator = translatorLibrary.lookupTranslator(
-                new TranslatorKey(deviceInfo.getVersion(), org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
+                new TranslatorKey(deviceInfo.getVersion(), org.opendaylight.yang.gen.v1.urn.opendaylight.openflow
+                        .protocol.rev130731
                         .PacketIn.class.getName()));
         this.flowRemovedTranslator = translatorLibrary.lookupTranslator(
                 new TranslatorKey(deviceInfo.getVersion(), FlowRemoved.class.getName()));
 
-        this.itemLifeCycleSourceRegistry = new ItemLifeCycleRegistryImpl();
-        this.flowLifeCycleKeeper = new ItemLifeCycleSourceImpl();
-        this.itemLifeCycleSourceRegistry.registerLifeCycleSource(flowLifeCycleKeeper);
         this.convertorExecutor = convertorExecutor;
         this.skipTableFeatures = skipTableFeatures;
         this.useSingleLayerSerialization = useSingleLayerSerialization;
@@ -236,7 +217,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public ReadOnlyTransaction getReadTransaction() {
+    public ReadTransaction getReadTransaction() {
         return dataBroker.newReadOnlyTransaction();
     }
 
@@ -248,7 +229,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     @Override
     public <T extends DataObject> void writeToTransaction(final LogicalDatastoreType store,
                                                           final InstanceIdentifier<T> path,
-                                                          final T data){
+                                                          final T data) {
         if (initialized.get()) {
             transactionChainManager.writeToTransaction(store, path, data, false);
         }
@@ -257,22 +238,28 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     @Override
     public <T extends DataObject> void writeToTransactionWithParentsSlow(final LogicalDatastoreType store,
                                                                          final InstanceIdentifier<T> path,
-                                                                         final T data){
+                                                                         final T data) {
         if (initialized.get()) {
             transactionChainManager.writeToTransaction(store, path, data, true);
         }
     }
 
     @Override
-    public <T extends DataObject> void addDeleteToTxChain(final LogicalDatastoreType store, final InstanceIdentifier<T> path) {
+    public <T extends DataObject> void addDeleteToTxChain(final LogicalDatastoreType store,
+                                                          final InstanceIdentifier<T> path) {
         if (initialized.get()) {
-            transactionChainManager.addDeleteOperationTotTxChain(store, path);
+            transactionChainManager.addDeleteOperationToTxChain(store, path);
         }
     }
 
     @Override
     public boolean submitTransaction() {
-        return initialized.get() && transactionChainManager.submitWriteTransaction();
+        return initialized.get() && transactionChainManager.submitTransaction();
+    }
+
+    @Override
+    public boolean syncSubmitTransaction() {
+        return initialized.get() && transactionChainManager.submitTransaction(true);
     }
 
     @Override
@@ -299,7 +286,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     public void processReply(final OfHeader ofHeader) {
         messageSpy.spyMessage(
                 ofHeader.getImplementedInterface(),
-                (ofHeader instanceof Error)
+                ofHeader instanceof Error
                         ? MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_FAILURE
                         : MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_SUCCESS);
     }
@@ -308,55 +295,41 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     public void processReply(final Xid xid, final List<? extends OfHeader> ofHeaderList) {
         ofHeaderList.forEach(header -> messageSpy.spyMessage(
                 header.getImplementedInterface(),
-                (header instanceof Error)
+                header instanceof Error
                         ? MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_FAILURE
                         : MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_SUCCESS));
     }
 
     @Override
     public void processFlowRemovedMessage(final FlowRemoved flowRemoved) {
-        //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, deviceInfo, null);
-
-        if (isFlowRemovedNotificationOn) {
-            // Trigger off a notification
-            notificationPublishService.offerNotification(flowRemovedNotification);
-        }
-
-        final ItemLifecycleListener itemLifecycleListener = flowLifeCycleKeeper.getItemLifecycleListener();
-        if (itemLifecycleListener != null) {
-            //2. create registry key
-            final FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(getDeviceInfo().getVersion(), flowRemovedNotification);
-            //3. lookup flowId
-            final FlowDescriptor flowDescriptor = deviceFlowRegistry.retrieveDescriptor(flowRegKey);
-            //4. if flowId present:
-            if (flowDescriptor != null) {
-                // a) construct flow path
-                final KeyedInstanceIdentifier<Flow, FlowKey> flowPath = getDeviceInfo().getNodeInstanceIdentifier()
-                        .augmentation(FlowCapableNode.class)
-                        .child(Table.class, flowDescriptor.getTableKey())
-                        .child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
-                // b) notify listener
-                itemLifecycleListener.onRemoved(flowPath);
-            } else {
-                LOG.debug("flow id not found: nodeId={} tableId={}, priority={}",
-                        getDeviceInfo().getNodeId(), flowRegKey.getTableId(), flowRemovedNotification.getPriority());
+        if (isMasterOfDevice()) {
+            //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, deviceInfo, null);
+
+            if (isFlowRemovedNotificationOn) {
+                // Trigger off a notification
+                notificationPublishService.offerNotification(flowRemovedNotification);
             }
+        } else {
+            LOG.debug("Controller is not owner of the device {}, skipping Flow Removed message",
+                    deviceInfo.getLOGValue());
         }
     }
 
     @Override
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public void processPortStatusMessage(final PortStatusMessage portStatus) {
-        messageSpy.spyMessage(portStatus.getImplementedInterface(), MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_SUCCESS);
+        messageSpy.spyMessage(portStatus.getImplementedInterface(), MessageSpy.StatisticsGroup
+                .FROM_SWITCH_PUBLISHED_SUCCESS);
 
         if (initialized.get()) {
             try {
                 writePortStatusMessage(portStatus);
-                submitTransaction();
             } catch (final Exception e) {
                 LOG.warn("Error processing port status message for port {} on device {}",
-                        portStatus.getPortNo(), getDeviceInfo().getLOGValue(), e);
+                        portStatus.getPortNo(), getDeviceInfo(), e);
             }
         } else if (!hasState.get()) {
             primaryConnectionContext.handlePortStatusMessage(portStatus);
@@ -375,22 +348,36 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
                                 portStatusMessage.getPortNo(),
                                 OpenflowVersion.get(deviceInfo.getVersion()))));
 
-        if (PortReason.OFPPRADD.equals(portStatusMessage.getReason()) || PortReason.OFPPRMODIFY.equals(portStatusMessage.getReason())) {
-            // because of ADD status node connector has to be created
-            writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector, new NodeConnectorBuilder()
-                    .setKey(iiToNodeConnector.getKey())
-                    .addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build())
-                    .addAugmentation(FlowCapableNodeConnector.class, flowCapableNodeConnector)
-                    .build());
-        } else if (PortReason.OFPPRDELETE.equals(portStatusMessage.getReason())) {
+        writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector, new NodeConnectorBuilder()
+                .withKey(iiToNodeConnector.getKey())
+                .addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new
+                        FlowCapableNodeConnectorStatisticsDataBuilder().build())
+                .addAugmentation(FlowCapableNodeConnector.class, flowCapableNodeConnector)
+                .build());
+        syncSubmitTransaction();
+        if (PortReason.OFPPRDELETE.equals(portStatusMessage.getReason())) {
             addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector);
+            syncSubmitTransaction();
         }
     }
 
     @Override
     public void processPacketInMessage(final PacketInMessage packetInMessage) {
-        final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, getDeviceInfo(), null);
-        handlePacketInMessage(packetReceived, packetInMessage.getImplementedInterface(), packetReceived.getMatch());
+        if (isMasterOfDevice()) {
+            final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, getDeviceInfo(), null);
+            handlePacketInMessage(packetReceived, packetInMessage.getImplementedInterface(), packetReceived.getMatch());
+        } else {
+            LOG.debug("Controller is not owner of the device {}, skipping packet_in message", deviceInfo.getLOGValue());
+        }
+    }
+
+    private Boolean isMasterOfDevice() {
+        final ContextChain contextChain = contextChainHolder.getContextChain(deviceInfo);
+        boolean result = false;
+        if (contextChain != null) {
+            result = contextChain.isMastered(ContextChainMastershipState.CHECK, false);
+        }
+        return result;
     }
 
     private void handlePacketInMessage(final PacketIn packetIn,
@@ -408,7 +395,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         final OpenflowVersion openflowVersion = OpenflowVersion.get(deviceInfo.getVersion());
 
         // Try to get ingress from match
-        final NodeConnectorRef nodeConnectorRef = Objects.nonNull(packetIn.getIngress())
+        final NodeConnectorRef nodeConnectorRef = packetIn.getIngress() != null
                 ? packetIn.getIngress() : Optional.ofNullable(match)
                 .map(Match::getInPort)
                 .map(nodeConnectorId -> InventoryDataServiceUtil
@@ -427,7 +414,8 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         if (!packetInLimiter.acquirePermit()) {
             LOG.debug("Packet limited");
             // TODO: save packet into emergency slot if possible
-            messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_PACKET_IN_LIMIT_REACHED_AND_DROPPED);
+            messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup
+                    .FROM_SWITCH_PACKET_IN_LIMIT_REACHED_AND_DROPPED);
             return;
         }
 
@@ -455,52 +443,59 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_NOTIFICATION_REJECTED);
-                LOG.debug("notification offer failed: {}", t.getMessage());
-                LOG.trace("notification offer failed..", t);
+            public void onFailure(final Throwable throwable) {
+                messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup
+                        .FROM_SWITCH_NOTIFICATION_REJECTED);
+                LOG.debug("notification offer failed: {}", throwable.getMessage());
+                LOG.trace("notification offer failed..", throwable);
                 packetInLimiter.releasePermit();
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 
     @Override
     public void processExperimenterMessage(final ExperimenterMessage notification) {
-        // lookup converter
-        final ExperimenterDataOfChoice vendorData = notification.getExperimenterDataOfChoice();
-        final MessageTypeKey<? extends ExperimenterDataOfChoice> key = new MessageTypeKey<>(
-                getDeviceInfo().getVersion(),
-                (Class<? extends ExperimenterDataOfChoice>) vendorData.getImplementedInterface());
-        final ConvertorMessageFromOFJava<ExperimenterDataOfChoice, MessagePath> messageConverter = extensionConverterProvider.getMessageConverter(key);
-        if (messageConverter == null) {
-            LOG.warn("custom converter for {}[OF:{}] not found",
-                    notification.getExperimenterDataOfChoice().getImplementedInterface(),
-                    getDeviceInfo().getVersion());
-            return;
-        }
-        // build notification
-        final ExperimenterMessageOfChoice messageOfChoice;
-        try {
+        if (isMasterOfDevice()) {
+            // lookup converter
+            final ExperimenterDataOfChoice vendorData = notification.getExperimenterDataOfChoice();
+            final MessageTypeKey<? extends ExperimenterDataOfChoice> key = new MessageTypeKey<>(
+                    getDeviceInfo().getVersion(),
+                    (Class<? extends ExperimenterDataOfChoice>) vendorData.getImplementedInterface());
+            final ConvertorMessageFromOFJava<ExperimenterDataOfChoice, MessagePath> messageConverter =
+                    extensionConverterProvider.getMessageConverter(key);
+            if (messageConverter == null) {
+                LOG.warn("custom converter for {}[OF:{}] not found",
+                        notification.getExperimenterDataOfChoice().getImplementedInterface(),
+                        getDeviceInfo().getVersion());
+                return;
+            }
+            // build notification
+            final ExperimenterMessageOfChoice messageOfChoice;
             messageOfChoice = messageConverter.convert(vendorData, MessagePath.MESSAGE_NOTIFICATION);
-            final ExperimenterMessageFromDevBuilder experimenterMessageFromDevBld = new ExperimenterMessageFromDevBuilder()
+            final ExperimenterMessageFromDevBuilder experimenterMessageFromDevBld = new
+                    ExperimenterMessageFromDevBuilder()
                     .setNode(new NodeRef(getDeviceInfo().getNodeInstanceIdentifier()))
                     .setExperimenterMessageOfChoice(messageOfChoice);
             // publish
             notificationPublishService.offerNotification(experimenterMessageFromDevBld.build());
-        } catch (final ConversionException e) {
-            LOG.error("Conversion of experimenter notification failed", e);
+        } else {
+            LOG.debug("Controller is not owner of the device {}, skipping experimenter message",
+                    deviceInfo.getLOGValue());
         }
     }
 
     @Override
+    // The cast to PacketInMessage is safe as the implemented interface is verified before the cas tbut FB doesn't
+    // recognize it.
+    @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
     public boolean processAlienMessage(final OfHeader message) {
         final Class<? extends DataContainer> implementedInterface = message.getImplementedInterface();
 
-        if (Objects.nonNull(implementedInterface) && org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service
-                .rev130709.PacketInMessage.class.equals(implementedInterface)) {
+        if (org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketInMessage.class
+                .equals(implementedInterface)) {
             final org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709
-                    .PacketInMessage packetInMessage = org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service
-                    .rev130709.PacketInMessage.class.cast(message);
+                    .PacketInMessage packetInMessage = (org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service
+                .rev130709.PacketInMessage) message;
 
             handlePacketInMessage(packetInMessage, implementedInterface, packetInMessage.getMatch());
             return true;
@@ -530,18 +525,15 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public <T extends OfHeader> MultiMsgCollector<T> getMultiMsgCollector(final RequestContext<List<T>> requestContext) {
+    public <T extends OfHeader> MultiMsgCollector<T> getMultiMsgCollector(final RequestContext<List<T>>
+                                                                                      requestContext) {
         return new MultiMsgCollectorImpl<>(this, requestContext);
     }
 
     @Override
     public void updatePacketInRateLimit(final long upperBound) {
-        packetInLimiter.changeWaterMarks((int) (LOW_WATERMARK_FACTOR * upperBound), (int) (HIGH_WATERMARK_FACTOR * upperBound));
-    }
-
-    @Override
-    public ItemLifeCycleRegistry getItemLifeCycleSourceRegistry() {
-        return itemLifeCycleSourceRegistry;
+        packetInLimiter.changeWaterMarks((int) (LOW_WATERMARK_FACTOR * upperBound),
+                (int) (HIGH_WATERMARK_FACTOR * upperBound));
     }
 
     @Override
@@ -560,12 +552,12 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public ListenableFuture<Void> closeServiceInstance() {
-        final ListenableFuture<Void> listenableFuture = initialized.get()
+    public ListenableFuture<?> closeServiceInstance() {
+        final ListenableFuture<?> listenableFuture = initialized.get()
                 ? transactionChainManager.deactivateTransactionManager()
                 : Futures.immediateFuture(null);
 
-        hashedWheelTimer.newTimeout((t) -> {
+        hashedWheelTimer.newTimeout((timerTask) -> {
             if (!listenableFuture.isDone() && !listenableFuture.isCancelled()) {
                 listenableFuture.cancel(true);
             }
@@ -580,8 +572,8 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
     }
 
     @Override
-    public void registerMastershipWatcher(@Nonnull final ContextChainMastershipWatcher contextChainMastershipWatcher) {
-        this.contextChainMastershipWatcher = contextChainMastershipWatcher;
+    public void registerMastershipWatcher(@Nonnull final ContextChainMastershipWatcher newWatcher) {
+        this.contextChainMastershipWatcher = newWatcher;
     }
 
     @Nonnull
@@ -598,21 +590,21 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
             deviceFlowRegistry.close();
             deviceMeterRegistry.close();
 
-            final ListenableFuture<Void> txChainShuttingDown = transactionChainManager.shuttingDown();
+            final ListenableFuture<?> txChainShuttingDown = transactionChainManager.shuttingDown();
 
-            Futures.addCallback(txChainShuttingDown, new FutureCallback<Void>() {
+            Futures.addCallback(txChainShuttingDown, new FutureCallback<Object>() {
                 @Override
-                public void onSuccess(@Nullable final Void result) {
+                public void onSuccess(final Object result) {
                     transactionChainManager.close();
                     transactionChainManager = null;
                 }
 
                 @Override
-                public void onFailure(final Throwable t) {
+                public void onFailure(final Throwable throwable) {
                     transactionChainManager.close();
                     transactionChainManager = null;
                 }
-            });
+            }, MoreExecutors.directExecutor());
         }
 
         requestContexts.forEach(requestContext -> RequestContextUtil
@@ -625,12 +617,9 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         return useSingleLayerSerialization && getDeviceInfo().getVersion() >= OFConstants.OFP_VERSION_1_3;
     }
 
+    // TODO: exception handling should be fixed by using custom checked exception, never RuntimeExceptions
     @Override
-    public void setSalRoleService(@Nonnull SalRoleService salRoleService) {
-        this.salRoleService = salRoleService;
-    }
-
-    @Override
+    @SuppressWarnings({"checkstyle:IllegalCatch"})
     public void instantiateServiceInstance() {
         lazyTransactionManagerInitialization();
 
@@ -642,8 +631,7 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
             submitTransaction();
         } catch (final Exception ex) {
             throw new RuntimeException(String.format("Error processing port status messages from device %s: %s",
-                    deviceInfo.toString(),
-                    ex.toString()));
+                    deviceInfo.toString(), ex.toString()), ex);
         }
 
         final Optional<AbstractDeviceInitializer> initializer = deviceInitializerProvider
@@ -659,13 +647,10 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
             } catch (TimeoutException ex) {
                 initialize.cancel(true);
                 throw new RuntimeException(String.format("Failed to initialize device %s in %ss: %s",
-                        deviceInfo.toString(),
-                        String.valueOf(DEVICE_INIT_TIMEOUT / 1000),
-                        ex.toString()));
+                        deviceInfo.toString(), String.valueOf(DEVICE_INIT_TIMEOUT / 1000), ex.toString()), ex);
             } catch (ExecutionException | InterruptedException ex) {
-                throw new RuntimeException(String.format("Device %s cannot be initialized: %s",
-                        deviceInfo.toString(),
-                        ex.toString()));
+                throw new RuntimeException(
+                        String.format("Device %s cannot be initialized: %s", deviceInfo.toString(), ex.toString()), ex);
             }
         } else {
             throw new RuntimeException(String.format("Unsupported version %s for device %s",
@@ -673,22 +658,22 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
                     deviceInfo.toString()));
         }
 
-        Futures.addCallback(sendRoleChangeToDevice(OfpRole.BECOMEMASTER),
-                new RpcResultFutureCallback(contextChainMastershipWatcher));
-
-        final ListenableFuture<List<com.google.common.base.Optional<FlowCapableNode>>> deviceFlowRegistryFill = getDeviceFlowRegistry().fill();
+        final ListenableFuture<List<Optional<FlowCapableNode>>> deviceFlowRegistryFill =
+                getDeviceFlowRegistry().fill();
         Futures.addCallback(deviceFlowRegistryFill,
-                new DeviceFlowRegistryCallback(deviceFlowRegistryFill, contextChainMastershipWatcher));
+                new DeviceFlowRegistryCallback(deviceFlowRegistryFill, contextChainMastershipWatcher),
+                MoreExecutors.directExecutor());
     }
 
     @VisibleForTesting
     void lazyTransactionManagerInitialization() {
         if (!this.initialized.get()) {
             if (LOG.isDebugEnabled()) {
-                LOG.debug("Transaction chain manager for node {} created", deviceInfo.getLOGValue());
+                LOG.debug("Transaction chain manager for node {} created", deviceInfo);
             }
-            this.transactionChainManager = new TransactionChainManager(dataBroker, deviceInfo);
-            this.deviceFlowRegistry = new DeviceFlowRegistryImpl(deviceInfo.getVersion(), dataBroker, deviceInfo.getNodeInstanceIdentifier());
+            this.transactionChainManager = new TransactionChainManager(dataBroker, deviceInfo.getNodeId().getValue());
+            this.deviceFlowRegistry = new DeviceFlowRegistryImpl(deviceInfo.getVersion(), dataBroker,
+                    deviceInfo.getNodeInstanceIdentifier());
             this.deviceGroupRegistry = new DeviceGroupRegistryImpl();
             this.deviceMeterRegistry = new DeviceMeterRegistryImpl();
         }
@@ -713,85 +698,24 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
         return abstractRequestContext;
     }
 
-    private ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole) {
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Sending new role {} to device {}", newRole, deviceInfo.getNodeId());
-        }
-
-        final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture;
-
-        if (deviceInfo.getVersion() >= OFConstants.OFP_VERSION_1_3) {
-            final SetRoleInput setRoleInput = (new SetRoleInputBuilder()).setControllerRole(newRole)
-                    .setNode(new NodeRef(deviceInfo.getNodeInstanceIdentifier())).build();
-
-            setRoleOutputFuture = this.salRoleService.setRole(setRoleInput);
-
-            final TimerTask timerTask = timeout -> {
-                if (!setRoleOutputFuture.isDone()) {
-                    LOG.warn("New role {} was not propagated to device {} during {} sec", newRole, deviceInfo.getLOGValue(), SET_ROLE_TIMEOUT);
-                    setRoleOutputFuture.cancel(true);
-                }
-            };
-
-            hashedWheelTimer.newTimeout(timerTask, SET_ROLE_TIMEOUT, TimeUnit.SECONDS);
-        } else {
-            LOG.info("Device: {} with version: {} does not support role", deviceInfo.getLOGValue(), deviceInfo.getVersion());
-            return Futures.immediateFuture(null);
-        }
-
-        return JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture);
-    }
-
-    @Override
-    public ListenableFuture<RpcResult<SetRoleOutput>> makeDeviceSlave() {
-        return sendRoleChangeToDevice(OfpRole.BECOMESLAVE);
-    }
-
     @Override
     public void onStateAcquired(final ContextChainState state) {
         hasState.set(true);
     }
 
-    private class RpcResultFutureCallback implements FutureCallback<RpcResult<SetRoleOutput>> {
-
-        private final ContextChainMastershipWatcher contextChainMastershipWatcher;
-
-        RpcResultFutureCallback(final ContextChainMastershipWatcher contextChainMastershipWatcher) {
-            this.contextChainMastershipWatcher = contextChainMastershipWatcher;
-        }
-
-        @Override
-        public void onSuccess(@Nullable RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
-            this.contextChainMastershipWatcher.onMasterRoleAcquired(
-                    deviceInfo,
-                    ContextChainMastershipState.MASTER_ON_DEVICE
-            );
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Role MASTER was successfully set on device, node {}", deviceInfo);
-            }
-        }
-
-        @Override
-        public void onFailure(final Throwable throwable) {
-            contextChainMastershipWatcher.onNotAbleToStartMastershipMandatory(
-                    deviceInfo,
-                    "Was not able to set MASTER role on device");
-        }
-    }
-
-    private class DeviceFlowRegistryCallback implements FutureCallback<List<com.google.common.base.Optional<FlowCapableNode>>> {
-        private final ListenableFuture<List<com.google.common.base.Optional<FlowCapableNode>>> deviceFlowRegistryFill;
+    private class DeviceFlowRegistryCallback implements FutureCallback<List<Optional<FlowCapableNode>>> {
+        private final ListenableFuture<List<Optional<FlowCapableNode>>> deviceFlowRegistryFill;
         private final ContextChainMastershipWatcher contextChainMastershipWatcher;
 
         DeviceFlowRegistryCallback(
-                ListenableFuture<List<com.google.common.base.Optional<FlowCapableNode>>> deviceFlowRegistryFill,
+                ListenableFuture<List<Optional<FlowCapableNode>>> deviceFlowRegistryFill,
                 ContextChainMastershipWatcher contextChainMastershipWatcher) {
             this.deviceFlowRegistryFill = deviceFlowRegistryFill;
             this.contextChainMastershipWatcher = contextChainMastershipWatcher;
         }
 
         @Override
-        public void onSuccess(@Nullable List<com.google.common.base.Optional<FlowCapableNode>> result) {
+        public void onSuccess(List<Optional<FlowCapableNode>> result) {
             if (LOG.isDebugEnabled()) {
                 // Count all flows we read from datastore for debugging purposes.
                 // This number do not always represent how many flows were actually added
@@ -802,7 +726,8 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
                         .stream()
                         .flatMap(Collection::stream)
                         .filter(Objects::nonNull)
-                        .flatMap(flowCapableNodeOptional -> flowCapableNodeOptional.asSet().stream())
+                        .flatMap(flowCapableNodeOptional
+                            -> com.google.common.base.Optional.fromJavaUtil(flowCapableNodeOptional).asSet().stream())
                         .filter(Objects::nonNull)
                         .filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable()))
                         .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
@@ -812,19 +737,20 @@ public class DeviceContextImpl implements DeviceContext, ExtensionConverterProvi
                         .filter(Objects::nonNull)
                         .count();
 
-                LOG.debug("Finished filling flow registry with {} flows for node: {}", flowCount, deviceInfo.getLOGValue());
+                LOG.debug("Finished filling flow registry with {} flows for node: {}", flowCount, deviceInfo);
             }
-            this.contextChainMastershipWatcher.onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.INITIAL_FLOW_REGISTRY_FILL);
+            this.contextChainMastershipWatcher.onMasterRoleAcquired(deviceInfo, ContextChainMastershipState
+                    .INITIAL_FLOW_REGISTRY_FILL);
         }
 
         @Override
-        public void onFailure(Throwable t) {
+        public void onFailure(Throwable throwable) {
             if (deviceFlowRegistryFill.isCancelled()) {
                 if (LOG.isDebugEnabled()) {
-                    LOG.debug("Cancelled filling flow registry with flows for node: {}", deviceInfo.getLOGValue());
+                    LOG.debug("Cancelled filling flow registry with flows for node: {}", deviceInfo);
                 }
             } else {
-                LOG.warn("Failed filling flow registry with flows for node: {} with exception: {}", deviceInfo.getLOGValue(), t);
+                LOG.warn("Failed filling flow registry with flows for node: {}", deviceInfo, throwable);
             }
             contextChainMastershipWatcher.onNotAbleToStartMastership(
                     deviceInfo,