Merge "BUG-5839: Removing groups and meters on being stale-marked"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / role / RoleManagerImpl.java
index d932c28cce1c755272d2ec0096237c02cb6d6b85..9e8d940babe3245f63ae61414196a70b45148e13 100644 (file)
@@ -7,19 +7,29 @@
  */
 package org.opendaylight.openflowplugin.impl.role;
 
-import com.google.common.base.Optional;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Verify;
-import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.collect.Iterators;
 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.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
-import java.util.Map;
+import io.netty.util.Timeout;
+import io.netty.util.TimerTask;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 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.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
@@ -27,47 +37,57 @@ import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipC
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.openflowplugin.api.OFConstants;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
-import org.opendaylight.openflowplugin.api.openflow.role.RoleChangeListener;
+import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.RoleChangeListener;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.ServiceChangeListener;
 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
 import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
-import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils;
+import org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl;
+import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
 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.role.service.rev150727.OfpRole;
+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.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * Gets invoked from RpcManagerInitial, registers a candidate with EntityOwnershipService.
- * On receipt of the ownership notification, makes an rpc call to SalRoleSevice.
+ * On receipt of the ownership notification, makes an rpc call to SalRoleService.
  *
  * Hands over to StatisticsManager at the end.
  */
-public class RoleManagerImpl implements RoleManager, EntityOwnershipListener {
+public class RoleManagerImpl implements RoleManager, EntityOwnershipListener, ServiceChangeListener {
     private static final Logger LOG = LoggerFactory.getLogger(RoleManagerImpl.class);
 
     private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
+    private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
     private final DataBroker dataBroker;
     private final EntityOwnershipService entityOwnershipService;
-    private final ConcurrentMap<Entity, RoleContext> contexts = new ConcurrentHashMap<>();
-    private final ConcurrentMap<Entity, RoleContext> txContexts = new ConcurrentHashMap<>();
+    private final ConcurrentMap<NodeId, RoleContext> contexts = new ConcurrentHashMap<>();
+    private final ConcurrentMap<Entity, RoleContext> watchingEntities = new ConcurrentHashMap<>();
     private final EntityOwnershipListenerRegistration entityOwnershipListenerRegistration;
     private final EntityOwnershipListenerRegistration txEntityOwnershipListenerRegistration;
-    private final boolean switchFeaturesMandatory;
+    private List<RoleChangeListener> listeners = new ArrayList<>();
+
+    private final LifecycleConductor conductor;
 
-    public RoleManagerImpl(final EntityOwnershipService entityOwnershipService, final DataBroker dataBroker, final boolean switchFeaturesMandatory) {
+    public RoleManagerImpl(final EntityOwnershipService entityOwnershipService, final DataBroker dataBroker, final LifecycleConductor lifecycleConductor) {
         this.entityOwnershipService = Preconditions.checkNotNull(entityOwnershipService);
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
-        this.switchFeaturesMandatory = switchFeaturesMandatory;
         this.entityOwnershipListenerRegistration = Preconditions.checkNotNull(entityOwnershipService.registerListener(RoleManager.ENTITY_TYPE, this));
         this.txEntityOwnershipListenerRegistration = Preconditions.checkNotNull(entityOwnershipService.registerListener(TX_ENTITY_TYPE, this));
-        LOG.debug("Registering OpenflowOwnershipListener listening to all entity ownership changes");
+        this.conductor = lifecycleConductor;
+        LOG.debug("Register OpenflowOwnershipListener to all entity ownership changes");
     }
 
     @Override
@@ -76,262 +96,297 @@ public class RoleManagerImpl implements RoleManager, EntityOwnershipListener {
     }
 
     @Override
-    public void onDeviceContextLevelUp(@CheckForNull final DeviceContext deviceContext) {
-        LOG.debug("RoleManager called for device:{}", deviceContext.getPrimaryConnectionContext().getNodeId());
-        if (deviceContext.getDeviceState().getFeatures().getVersion() < OFConstants.OFP_VERSION_1_3) {
-            // Roles are not supported before OF1.3, so move forward.
-            deviceInitializationPhaseHandler.onDeviceContextLevelUp(deviceContext);
-            return;
-        }
-
-        final RoleContext roleContext = new RoleContextImpl(deviceContext, entityOwnershipService,
-                makeEntity(deviceContext.getDeviceState().getNodeId()),
-                makeTxEntity(deviceContext.getDeviceState().getNodeId()));
-        // if the device context gets closed (mostly on connection close), we would need to cleanup
-        deviceContext.addDeviceContextClosedHandler(this);
-        Verify.verify(contexts.putIfAbsent(roleContext.getEntity(), roleContext) == null,
-                "RoleCtx for master Node {} is still not close.", deviceContext.getDeviceState().getNodeId());
-
-        final ListenableFuture<OfpRole> roleChangeFuture = roleContext.initialization();
-
-        final ListenableFuture<Void> txFreeFuture = Futures.transform(roleChangeFuture, new AsyncFunction<OfpRole, Void>() {
-            @Override
-            public ListenableFuture<Void> apply(final OfpRole input) throws Exception {
-                final ListenableFuture<Void> nextFuture;
-                if (OfpRole.BECOMEMASTER.equals(input)) {
-                    LOG.debug("Node {} has marked as LEADER", deviceContext.getDeviceState().getNodeId());
-                    Verify.verify(txContexts.putIfAbsent(roleContext.getTxEntity(), roleContext) == null,
-                            "RoleCtx for TxEntity {} master Node {} is still not close.",
-                            roleContext.getTxEntity(), deviceContext.getDeviceState().getNodeId());
-                    nextFuture = roleContext.setupTxCandidate();
-                } else {
-                    LOG.debug("Node {} was marked as FOLLOWER", deviceContext.getDeviceState().getNodeId());
-                    nextFuture = Futures.immediateFuture(null);
-                }
-                return nextFuture;
-            }
-        });
-
-        final ListenableFuture<Void> initDeviceFuture = Futures.transform(txFreeFuture,new AsyncFunction<Void, Void>() {
-            @Override
-            public ListenableFuture<Void> apply(final Void input) throws Exception {
-                LOG.debug("Node {} will be initialized", deviceContext.getDeviceState().getNodeId());
-                return DeviceInitializationUtils.initializeNodeInformation(deviceContext, switchFeaturesMandatory);
-            }
-        });
-
-        Futures.addCallback(initDeviceFuture, new FutureCallback<Void>() {
-            @Override
-            public void onSuccess(final Void result) {
-                LOG.debug("Initialization Node {} is done.", deviceContext.getDeviceState().getNodeId());
-                getRoleContextLevelUp(deviceContext);
-            }
-
-            @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("Unexpected error for Node {} initialization", deviceContext.getDeviceState().getNodeId(), t);
-                deviceContext.close();
-            }
-        });
-    }
-
-    void getRoleContextLevelUp(final DeviceContext deviceContext) {
-        LOG.debug("Created role context for node {}", deviceContext.getDeviceState().getNodeId());
-        LOG.debug("roleChangeFuture success for device:{}. Moving to StatisticsManager", deviceContext.getDeviceState().getNodeId());
-        deviceInitializationPhaseHandler.onDeviceContextLevelUp(deviceContext);
+    public void onDeviceContextLevelUp(@CheckForNull final NodeId nodeId) throws Exception {
+        final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
+        final RoleContext roleContext = new RoleContextImpl(nodeId, entityOwnershipService, makeEntity(nodeId), makeTxEntity(nodeId), conductor);
+        roleContext.setSalRoleService(new SalRoleServiceImpl(roleContext, deviceContext));
+        Verify.verify(contexts.putIfAbsent(nodeId, roleContext) == null, "Role context for master Node %s is still not closed.", nodeId);
+        makeDeviceRoleChange(OfpRole.BECOMESLAVE, roleContext, true);
+        notifyListenersRoleInitializationDone(roleContext.getNodeId(), roleContext.initialization());
+        watchingEntities.put(roleContext.getEntity(), roleContext);
+        deviceInitializationPhaseHandler.onDeviceContextLevelUp(nodeId);
     }
 
     @Override
-    public void close() throws Exception {
+    public void close() {
+        LOG.debug("Close method on role manager was called.");
         entityOwnershipListenerRegistration.close();
-        for (final Map.Entry<Entity, RoleContext> roleContextEntry : contexts.entrySet()) {
+        txEntityOwnershipListenerRegistration.close();
+        for (final Iterator<RoleContext> iterator = Iterators.consumingIterator(contexts.values().iterator()); iterator.hasNext();) {
             // got here because last known role is LEADER and DS might need clearing up
-            final Entity entity = roleContextEntry.getKey();
-            final Optional<EntityOwnershipState> ownershipState = entityOwnershipService.getOwnershipState(entity);
-            final NodeId nodeId = roleContextEntry.getValue().getDeviceState().getNodeId();
-            if (ownershipState.isPresent()) {
-                if ((!ownershipState.get().hasOwner())) {
-                    LOG.trace("Last role is LEADER and ownershipService returned hasOwner=false for node: {}; " +
-                            "cleaning DS as being probably the last owner", nodeId);
-                    removeDeviceFromOperDS(roleContextEntry.getValue());
-                } else {
-                    // NOOP - there is another owner
-                    LOG.debug("Last role is LEADER and ownershipService returned hasOwner=true for node: {}; " +
-                            "leaving DS untouched", nodeId);
-                }
+            final RoleContext roleContext = iterator.next();
+            watchingEntities.remove(roleContext.getEntity());
+            watchingEntities.remove(roleContext.getTxEntity());
+            contexts.remove(roleContext.getNodeId());
+            if (roleContext.isTxCandidateRegistered()) {
+                LOG.info("Node {} was holder txEntity, so trying to remove device from operational DS.");
+                removeDeviceFromOperationalDS(roleContext.getNodeId());
             } else {
-                // TODO: is this safe? When could this happen?
-                LOG.warn("Last role is LEADER but ownershipService returned empty ownership info for node: {}; " +
-                        "cleaning DS ANYWAY!", nodeId);
-                removeDeviceFromOperDS(roleContextEntry.getValue());
+                roleContext.close();
             }
         }
-        contexts.clear();
     }
 
     @Override
-    public void onDeviceContextClosed(final DeviceContext deviceContext) {
-        final NodeId nodeId = deviceContext.getDeviceState().getNodeId();
-        LOG.debug("onDeviceContextClosed for node {}", nodeId);
-        final Entity entity = makeEntity(nodeId);
-        final RoleContext roleContext = contexts.get(entity);
+    public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
+        final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId();
+        LOG.trace("onDeviceContextLevelDown for node {}", nodeId);
+        final RoleContext roleContext = contexts.get(nodeId);
         if (roleContext != null) {
-            LOG.debug("Found roleContext associated to deviceContext: {}, now closing the roleContext", nodeId);
-            final Optional<EntityOwnershipState> actState = entityOwnershipService.getOwnershipState(entity);
-            if (actState.isPresent()) {
-                if (!actState.get().isOwner()) {
-                    LOG.debug("No DS commitment for device {} - LEADER is somewhere else", nodeId);
-                    contexts.remove(entity, roleContext);
-                }
+            LOG.debug("Found roleContext associated to deviceContext: {}, now trying close the roleContext", nodeId);
+            if (roleContext.isMainCandidateRegistered()) {
+                roleContext.unregisterCandidate(roleContext.getEntity());
             } else {
-                LOG.warn("EntityOwnershipService doesn't return state for entity: {} in close proces", entity);
+                contexts.remove(nodeId, roleContext);
+                roleContext.close();
             }
-            roleContext.close();
         }
+        deviceTerminationPhaseHandler.onDeviceContextLevelDown(deviceContext);
     }
 
-    private static Entity makeEntity(final NodeId nodeId) {
+    @VisibleForTesting
+    static Entity makeEntity(final NodeId nodeId) {
         return new Entity(RoleManager.ENTITY_TYPE, nodeId.getValue());
     }
 
-    private static Entity makeTxEntity(final NodeId nodeId) {
+    @VisibleForTesting
+    static Entity makeTxEntity(final NodeId nodeId) {
         return new Entity(RoleManager.TX_ENTITY_TYPE, nodeId.getValue());
     }
 
     @Override
     public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
+
         Preconditions.checkArgument(ownershipChange != null);
-        final RoleContext roleContext = contexts.get(ownershipChange.getEntity());
+        final RoleContext roleContext = watchingEntities.get(ownershipChange.getEntity());
+
+        LOG.debug("Received EOS message: wasOwner:{} isOwner:{} hasOwner:{} for entity type {} and node {}",
+                ownershipChange.wasOwner(), ownershipChange.isOwner(), ownershipChange.hasOwner(),
+                ownershipChange.getEntity().getType(),
+                roleContext != null ? roleContext.getNodeId() : "-> no watching entity, disregarding notification <-");
+
         if (roleContext != null) {
-            changeForEntity(ownershipChange, roleContext);
-        } else {
-            final RoleContext txRoleContext = txContexts.get(ownershipChange.getEntity());
-            if (txRoleContext != null) {
-                changeForTxEntity(ownershipChange, txRoleContext);
+            if (ownershipChange.getEntity().equals(roleContext.getEntity())) {
+                changeOwnershipForMainEntity(ownershipChange, roleContext);
             } else {
-                LOG.debug("We are not alble to find Entity {} ownershipChange {}", ownershipChange.getEntity(), ownershipChange);
+                changeOwnershipForTxEntity(ownershipChange, roleContext);
             }
+        } else {
+            LOG.debug("OwnershipChange {}", ownershipChange);
         }
+
     }
 
-    private void changeForTxEntity(final EntityOwnershipChange ownershipChange, final RoleContext roleTxChangeListener) {
-        LOG.info("Received EntityOwnershipChange:{}, roleChangeListener-present={}", ownershipChange, (roleTxChangeListener != null));
-
-        if (roleTxChangeListener != null) {
-            if (ownershipChange.wasOwner() && !ownershipChange.isOwner()) {
-                txContexts.remove(roleTxChangeListener.getTxEntity(), roleTxChangeListener);
-            } else if (!ownershipChange.wasOwner() && ownershipChange.isOwner()) {
-                LOG.debug("TxRoleChange for entity {}", ownershipChange.getEntity());
-                final OfpRole newRole = ownershipChange.isOwner() ? OfpRole.BECOMEMASTER : OfpRole.BECOMESLAVE;
-                final OfpRole oldRole = ownershipChange.wasOwner() ? OfpRole.BECOMEMASTER : OfpRole.BECOMESLAVE;
-                roleTxChangeListener.onTxRoleChange(oldRole, newRole);
+    @VisibleForTesting
+    void changeOwnershipForMainEntity(final EntityOwnershipChange ownershipChange, final RoleContext roleContext) {
+
+        if (roleContext.isMainCandidateRegistered()) {
+            LOG.debug("Main-EntityOwnershipRegistration is active for entity type {} and node {}",
+                    ownershipChange.getEntity().getType(), roleContext.getNodeId());
+            if (!ownershipChange.wasOwner() && ownershipChange.isOwner()) {
+                // SLAVE -> MASTER
+                LOG.debug("SLAVE to MASTER for node {}", roleContext.getNodeId());
+                if (roleContext.registerCandidate(roleContext.getTxEntity())) {
+                    LOG.debug("Starting watching tx entity for node {}", roleContext.getNodeId());
+                    watchingEntities.putIfAbsent(roleContext.getTxEntity(), roleContext);
+                }
+            } else if (ownershipChange.wasOwner() && !ownershipChange.isOwner()) {
+                // MASTER -> SLAVE
+                LOG.debug("MASTER to SLAVE for node {}", roleContext.getNodeId());
+                conductor.addOneTimeListenerWhenServicesChangesDone(this, roleContext.getNodeId());
+                makeDeviceRoleChange(OfpRole.BECOMESLAVE, roleContext, false);
+            }
+        } else {
+            LOG.debug("Main-EntityOwnershipRegistration is not active for entity type {} and node {}",
+                    ownershipChange.getEntity(), roleContext.getNodeId());
+            watchingEntities.remove(ownershipChange.getEntity(), roleContext);
+            if (roleContext.isTxCandidateRegistered()) {
+                LOG.debug("tx candidate still registered for node {}, probably connection lost, trying to unregister tx candidate", roleContext.getNodeId());
+                roleContext.unregisterCandidate(roleContext.getTxEntity());
+                if (ownershipChange.wasOwner() && !ownershipChange.isOwner() && !ownershipChange.hasOwner()) {
+                    LOG.debug("Trying to remove from operational node: {}", roleContext.getNodeId());
+                    removeDeviceFromOperationalDS(roleContext.getNodeId());
+                }
             } else {
-                LOG.warn("Unexpected state for TxEntity {} ", roleTxChangeListener.getTxEntity());
+                final NodeId nodeId = roleContext.getNodeId();
+                contexts.remove(nodeId, roleContext);
+                roleContext.close();
+                conductor.closeConnection(nodeId);
             }
         }
     }
 
-    private static FutureCallback<Void> makeTxEntitySupendCallback(final RoleContext roleChangeListener) {
-        return new FutureCallback<Void>() {
-            @Override
-            public void onSuccess(final Void result) {
-                roleChangeListener.suspendTxCandidate();
-            }
+    @VisibleForTesting
+    void changeOwnershipForTxEntity(final EntityOwnershipChange ownershipChange,
+            @Nonnull final RoleContext roleContext) {
 
-            @Override
-            public void onFailure(final Throwable t) {
-                roleChangeListener.suspendTxCandidate();
+        if (roleContext.isTxCandidateRegistered()) {
+            LOG.debug("Tx-EntityOwnershipRegistration is active for entity type {} and node {}",
+                    ownershipChange.getEntity().getType(),
+                    roleContext.getNodeId());
+            if (!ownershipChange.wasOwner() && ownershipChange.isOwner()) {
+                // SLAVE -> MASTER
+                LOG.debug("SLAVE to MASTER for node {}", roleContext.getNodeId());
+                makeDeviceRoleChange(OfpRole.BECOMEMASTER, roleContext,false);
+            } else if (ownershipChange.wasOwner() && !ownershipChange.isOwner()) {
+                // MASTER -> SLAVE
+                LOG.debug("MASTER to SLAVE for node {}", roleContext.getNodeId());
+                LOG.warn("Tx-EntityOwnershipRegistration lost leadership entity type {} and node {}",
+                        ownershipChange.getEntity().getType(),roleContext.getNodeId());
+                watchingEntities.remove(roleContext.getTxEntity(), roleContext);
+                watchingEntities.remove(roleContext.getEntity(), roleContext);
+                roleContext.unregisterCandidate(roleContext.getEntity());
+                roleContext.unregisterCandidate(roleContext.getTxEntity());
+                if (!ownershipChange.hasOwner()) {
+                    LOG.debug("Trying to remove from operational node: {}", roleContext.getNodeId());
+                    removeDeviceFromOperationalDS(roleContext.getNodeId());
+                } else {
+                    final NodeId nodeId = roleContext.getNodeId();
+                    contexts.remove(nodeId, roleContext);
+                    roleContext.close();
+                    conductor.closeConnection(nodeId);
+                }
             }
-        };
+        } else {
+            LOG.debug("Tx-EntityOwnershipRegistration is not active for entity {}", ownershipChange.getEntity().getType());
+            watchingEntities.remove(roleContext.getTxEntity(), roleContext);
+            final NodeId nodeId = roleContext.getNodeId();
+            contexts.remove(nodeId, roleContext);
+            roleContext.close();
+            conductor.closeConnection(nodeId);
+        }
     }
 
-    private static FutureCallback<Void> makeTxEntitySetupCallbakck(final RoleContext roleChangeListener) {
-        return new FutureCallback<Void>() {
+    @VisibleForTesting
+    void makeDeviceRoleChange(final OfpRole role, final RoleContext roleContext, final Boolean init) {
+        final ListenableFuture<RpcResult<SetRoleOutput>> roleChangeFuture = sendRoleChangeToDevice(role, roleContext);
+        Futures.addCallback(roleChangeFuture, new FutureCallback<RpcResult<SetRoleOutput>>() {
             @Override
-            public void onSuccess(final Void result) {
-                roleChangeListener.setupTxCandidate();
+            public void onSuccess(@Nullable final RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
+                LOG.info("Role {} successfully set on device {}", role, roleContext.getNodeId());
+                notifyListenersRoleChangeOnDevice(roleContext.getNodeId(), true, role, init);
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("Unexpected state but we want continue txEntity {}", roleChangeListener.getTxEntity(), t);
-                roleChangeListener.setupTxCandidate();
+            public void onFailure(@Nonnull final Throwable throwable) {
+                LOG.warn("Unable to set role {} on device {}", role, roleContext.getNodeId());
+                notifyListenersRoleChangeOnDevice(roleContext.getNodeId(), false, role, init);
             }
-        };
+        });
     }
 
-    private void changeForEntity(final EntityOwnershipChange ownershipChange, final RoleContext roleChangeListener) {
-        //FIXME : check again implementation for double candidate scenario
-        LOG.info("Received EntityOwnershipChange:{}, roleChangeListener-present={}", ownershipChange, (roleChangeListener != null));
-        if (roleChangeListener != null) {
-            if (roleChangeListener.getDeviceState().isValid()) {
-                LOG.debug("RoleChange for entity {}", ownershipChange.getEntity());
-                final OfpRole newRole = ownershipChange.isOwner() ? OfpRole.BECOMEMASTER : OfpRole.BECOMESLAVE;
-                final OfpRole oldRole = ownershipChange.wasOwner() ? OfpRole.BECOMEMASTER : OfpRole.BECOMESLAVE;
-                // send even if they are same. we do the check for duplicates in SalRoleService and maintain a lastKnownRole
-                final FutureCallback<Void> callback;
-                if (ownershipChange.wasOwner() && !ownershipChange.isOwner() && ownershipChange.hasOwner()) {
-                    callback = makeTxEntitySupendCallback(roleChangeListener);
-                } else if (!ownershipChange.wasOwner() && ownershipChange.isOwner() && ownershipChange.isOwner()) {
-                    // FIXME : make different code path deviceContext.onClusterRoleChange(newRole); has to call from onTxRoleChange (for master)
-                    callback = makeTxEntitySetupCallbakck(roleChangeListener);
-                } else {
-                    callback = null;
-                }
-                roleChangeListener.onRoleChanged(oldRole, newRole, callback);
-            } else {
-                LOG.debug("We are closing connection for entity {}", ownershipChange.getEntity());
-                if (!ownershipChange.hasOwner() && !ownershipChange.isOwner() && ownershipChange.wasOwner()) {
-                    unregistrationHelper(ownershipChange, roleChangeListener);
-                } else if (ownershipChange.hasOwner() && !ownershipChange.isOwner() && ownershipChange.wasOwner()) {
-                    contexts.remove(ownershipChange.getEntity(), roleChangeListener);
-                    roleChangeListener.suspendTxCandidate();
-                } else {
-                    LOG.info("Unexpected role change msg {} for entity {}", ownershipChange, ownershipChange.getEntity());
+
+    private ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole, final RoleContext roleContext) {
+        LOG.debug("Sending new role {} to device {}", newRole, roleContext.getNodeId());
+        final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture;
+        final Short version = conductor.gainVersionSafely(roleContext.getNodeId());
+        if (null == version) {
+            LOG.debug("Device version is null");
+            return Futures.immediateFuture(null);
+        }
+        if (version < OFConstants.OFP_VERSION_1_3) {
+            LOG.debug("Device version not support ROLE");
+            return Futures.immediateFuture(null);
+        } else {
+            final SetRoleInput setRoleInput = (new SetRoleInputBuilder()).setControllerRole(newRole)
+                    .setNode(new NodeRef(DeviceStateUtil.createNodeInstanceIdentifier(roleContext.getNodeId()))).build();
+            setRoleOutputFuture = roleContext.getSalRoleService().setRole(setRoleInput);
+            final TimerTask timerTask = new TimerTask() {
+
+                @Override
+                public void run(final Timeout timeout) throws Exception {
+                    if (!setRoleOutputFuture.isDone()) {
+                        LOG.warn("New role {} was not propagated to device {} during 10 sec", newRole, roleContext.getNodeId());
+                        setRoleOutputFuture.cancel(true);
+                    }
                 }
-            }
+            };
+            conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
         }
+        return JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture);
     }
 
-    private CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperDS(
-            final RoleChangeListener roleChangeListener) {
-        Preconditions.checkArgument(roleChangeListener != null);
-        final DeviceState deviceState = roleChangeListener.getDeviceState();
+    @VisibleForTesting
+    CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperationalDS(final NodeId nodeId) {
+
         final WriteTransaction delWtx = dataBroker.newWriteOnlyTransaction();
-        delWtx.delete(LogicalDatastoreType.OPERATIONAL, deviceState.getNodeInstanceIdentifier());
+        delWtx.delete(LogicalDatastoreType.OPERATIONAL, DeviceStateUtil.createNodeInstanceIdentifier(nodeId));
         final CheckedFuture<Void, TransactionCommitFailedException> delFuture = delWtx.submit();
         Futures.addCallback(delFuture, new FutureCallback<Void>() {
 
             @Override
             public void onSuccess(final Void result) {
-                LOG.debug("Delete Node {} was successful", deviceState.getNodeId());
+                LOG.debug("Delete Node {} was successful", nodeId);
+                final RoleContext roleContext = contexts.remove(nodeId);
+                if (roleContext != null) {
+                    roleContext.close();
+                }
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("Delete Node {} fail.", deviceState.getNodeId(), t);
+            public void onFailure(@Nonnull final Throwable t) {
+                LOG.warn("Delete Node {} failed. {}", nodeId, t);
+                contexts.remove(nodeId);
+                final RoleContext roleContext = contexts.remove(nodeId);
+                if (roleContext != null) {
+                    roleContext.close();
+                }
             }
         });
         return delFuture;
     }
 
-    private void unregistrationHelper(final EntityOwnershipChange ownershipChange, final RoleChangeListener roleChangeListener) {
-        LOG.info("Initiate removal from operational. Possibly the last node to be disconnected for :{}. ", ownershipChange);
-        Futures.addCallback(removeDeviceFromOperDS(roleChangeListener), new FutureCallback<Void>() {
-            @Override
-            public void onSuccess(@Nullable final Void aVoid) {
-                LOG.debug("Freeing roleContext slot for device: {}", roleChangeListener.getDeviceState().getNodeId());
-                contexts.remove(ownershipChange.getEntity(), roleChangeListener);
-                ((RoleContext) roleChangeListener).suspendTxCandidate();
-            }
+    @Override
+    public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
+        deviceTerminationPhaseHandler = handler;
+    }
 
-            @Override
-            public void onFailure(final Throwable throwable) {
-                LOG.warn("NOT freeing roleContext slot for device: {}, {}", roleChangeListener.getDeviceState()
-                        .getNodeId(), throwable.getMessage());
-                contexts.remove(ownershipChange.getEntity(), roleChangeListener);
-                ((RoleContext) roleChangeListener).suspendTxCandidate();
-            }
-        });
+    @Override
+    public void servicesChangeDone(final NodeId nodeId, final boolean success) {
+        LOG.debug("Services stopping done for node {} as " + (success ? "successful" : "unsuccessful"), nodeId);
+        final RoleContext roleContext = contexts.get(nodeId);
+        if (null != roleContext) {
+            /* Services stopped or failure */
+            roleContext.unregisterCandidate(roleContext.getTxEntity());
+        }
+    }
+
+    @VisibleForTesting
+    RoleContext getRoleContext(final NodeId nodeId){
+        return contexts.get(nodeId);
     }
+
+    @Override
+    public void addRoleChangeListener(final RoleChangeListener roleChangeListener) {
+        this.listeners.add(roleChangeListener);
+    }
+
+    /**
+     * Invoked when initialization phase is done
+     * @param nodeId node identification
+     * @param success true if initialization done ok, false otherwise
+     */
+    @VisibleForTesting
+    void notifyListenersRoleInitializationDone(final NodeId nodeId, final boolean success){
+        LOG.debug("Notifying registered listeners for role initialization done, no. of listeners {}", listeners.size());
+        for (final RoleChangeListener listener : listeners) {
+            listener.roleInitializationDone(nodeId, success);
+        }
+    }
+
+    /**
+     * Notifies registered listener on role change. Role is the new role on device
+     * If initialization phase is true, we may skip service starting
+     * @param success true if role change on device done ok, false otherwise
+     * @param role new role meant to be set on device
+     * @param initializationPhase if true, then skipp services start
+     */
+    @VisibleForTesting
+    void notifyListenersRoleChangeOnDevice(final NodeId nodeId, final boolean success, final OfpRole role, final boolean initializationPhase){
+        LOG.debug("Notifying registered listeners for role change, no. of listeners {}", listeners.size());
+        for (final RoleChangeListener listener : listeners) {
+            listener.roleChangeOnDevice(nodeId, success, role, initializationPhase);
+        }
+    }
+
 }