DeviceState changes
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / role / RoleContextImpl.java
index f43aec88bf2dc96e20d67ad35adb8d9035dc26d9..e0392a7cc95dce245b214aaa9b9e2ca55d0e8e26 100644 (file)
  */
 package org.opendaylight.openflowplugin.impl.role;
 
+import com.google.common.base.Preconditions;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
-import java.util.concurrent.Future;
-
-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.SettableFuture;
 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
-import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
-import org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl;
-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.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.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Created by kramesha on 9/12/15.
+ * Role context hold information about entity ownership registration,
+ * register and unregister candidate (main and tx)
  */
-public class RoleContextImpl implements RoleContext {
+class RoleContextImpl implements RoleContext {
+
     private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
+    private static final int TIMEOUT = 12;
 
+    private final DeviceInfo deviceInfo;
     private final EntityOwnershipService entityOwnershipService;
-    private EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration;
-    private final RpcProviderRegistry rpcProviderRegistry;
-    private final DeviceContext deviceContext;
+    private volatile EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration = null;
+    private volatile EntityOwnershipCandidateRegistration txEntityOwnershipCandidateRegistration = null;
+
     private final Entity entity;
-    private final OpenflowOwnershipListener openflowOwnershipListener;
-    private SalRoleService salRoleService;
+    private final Entity txEntity;
 
-    private final SettableFuture<OfpRole> initRoleChangeFuture;
+    private SalRoleService salRoleService = null;
 
-    public RoleContextImpl(final DeviceContext deviceContext, final RpcProviderRegistry rpcProviderRegistry,
-                           final EntityOwnershipService entityOwnershipService, final OpenflowOwnershipListener openflowOwnershipListener) {
-        this.entityOwnershipService = entityOwnershipService;
-        this.rpcProviderRegistry = rpcProviderRegistry;
-        this.deviceContext = deviceContext;
-        entity = new Entity(RoleManager.ENTITY_TYPE, deviceContext.getPrimaryConnectionContext().getNodeId().getValue());
+    private final Semaphore roleChangeGuard = new Semaphore(1, true);
 
-        this.openflowOwnershipListener =  openflowOwnershipListener;
-        salRoleService = new SalRoleServiceImpl(this, deviceContext);
+    private final LifecycleConductor conductor;
 
-        initRoleChangeFuture = SettableFuture.create();
+    RoleContextImpl(final DeviceInfo deviceInfo, final EntityOwnershipService entityOwnershipService, final Entity entity, final Entity txEntity, final LifecycleConductor lifecycleConductor) {
+        this.entityOwnershipService = entityOwnershipService;
+        this.entity = entity;
+        this.txEntity = txEntity;
+        this.deviceInfo = deviceInfo;
+        this.conductor = lifecycleConductor;
     }
 
     @Override
-    public Future<OfpRole> initialization() throws CandidateAlreadyRegisteredException {
-        LOG.debug("Initialization requestOpenflowEntityOwnership for entity {}", entity);
-        openflowOwnershipListener.registerRoleChangeListener(this);
-        entityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity);
-        LOG.info("RoleContextImpl : Candidate registered with ownership service for device :{}", deviceContext
-                .getPrimaryConnectionContext().getNodeId().getValue());
-        return initRoleChangeFuture;
+    public boolean initialization() {
+        LOG.info("Initialization main candidate for node {}", deviceInfo.getNodeId());
+        return registerCandidate(this.entity);
     }
 
     @Override
-    public void onRoleChanged(final OfpRole oldRole, final OfpRole newRole) {
-        LOG.trace("onRoleChanged method call for Entity {}", entity);
-
-        if (!isDeviceConnected()) {
-            // this can happen as after the disconnect, we still get a last messsage from EntityOwnershipService.
-            LOG.info("Device {} is disconnected from this node. Hence not attempting a role change.",
-                    deviceContext.getPrimaryConnectionContext().getNodeId());
-            if (!initRoleChangeFuture.isDone()) {
-                LOG.debug("RoleChange is not valid for initialization Entity {} anymore - Device is disconnected", entity);
-                initRoleChangeFuture.cancel(true);
-            }
-            return;
+    public void unregisterAllCandidates() {
+        LOG.info("Role context closed, unregistering all candidates for ownership for node {}", deviceInfo.getNodeId());
+        if (isMainCandidateRegistered()) {
+            unregisterCandidate(this.entity);
         }
-
-        if (!initRoleChangeFuture.isDone()) {
-            LOG.debug("Initialization Role for entity {} is chosed {}", entity, newRole);
-            initRoleChangeFuture.set(newRole);
-            deviceContext.onInitClusterRoleChange(newRole);
+        if (isTxCandidateRegistered()) {
+            unregisterCandidate(this.txEntity);
         }
+    }
 
-        LOG.debug("Role change received from ownership listener from {} to {} for device:{}", oldRole, newRole,
-                deviceContext.getPrimaryConnectionContext().getNodeId());
-
-        final SetRoleInput setRoleInput = (new SetRoleInputBuilder())
-                .setControllerRole(newRole)
-                .setNode(new NodeRef(deviceContext.getDeviceState().getNodeInstanceIdentifier()))
-                .build();
-
-        final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture = salRoleService.setRole(setRoleInput);
-
-        Futures.addCallback(JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture), new FutureCallback<RpcResult<SetRoleOutput>>() {
-            @Override
-            public void onSuccess(final RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
-                LOG.debug("Rolechange {} successful made on switch :{}", newRole,
-                        deviceContext.getPrimaryConnectionContext().getNodeId());
-                deviceContext.getDeviceState().setRole(newRole);
-                deviceContext.onClusterRoleChange(newRole);
-            }
-
+    @Nullable
+    @Override
+    public <T> RequestContext<T> createRequestContext() {
+        return new AbstractRequestContext<T>(conductor.reserveXidForDeviceMessage(deviceInfo)) {
             @Override
-            public void onFailure(final Throwable throwable) {
-                LOG.error("Error in setRole {} for device {} ", newRole,
-                        deviceContext.getPrimaryConnectionContext().getNodeId(), throwable);
+            public void close() {
             }
-        });
+        };
     }
 
     @Override
-    public void close() throws Exception {
-        if (entityOwnershipCandidateRegistration != null) {
-            LOG.debug("Closing EntityOwnershipCandidateRegistration for {}", entity);
-            entityOwnershipCandidateRegistration.close();
-        }
-        if (OfpRole.BECOMESLAVE.equals(deviceContext.getDeviceState().getRole())
-                || deviceContext.getDeviceState() == null) {
-            // FIXME : there still stay small time window when we can unregistered
-            //         master DeviceCtx (RoleCtx) without the DS clean action
-            //         - RoleCtx doasn't send/receive RpcResult<SetRoleOutput> for
-            //           Master change role for/from Device
-            openflowOwnershipListener.unregisterRoleChangeListener(this);
-        }
+    public void setSalRoleService(@Nonnull final SalRoleService salRoleService) {
+        Preconditions.checkNotNull(salRoleService);
+        this.salRoleService = salRoleService;
     }
 
     @Override
-    public void onDeviceContextClosed(final DeviceContext deviceContext) {
-        try {
-            LOG.debug("onDeviceContextClosed called");
-            this.close();
-        } catch (final Exception e) {
-            LOG.error("Exception in onDeviceContextClosed of RoleContext", e);
-        }
+    public SalRoleService getSalRoleService() {
+        return this.salRoleService;
     }
 
     @Override
     public Entity getEntity() {
-        return entity;
+        return this.entity;
+    }
+
+    @Override
+    public Entity getTxEntity() {
+        return this.txEntity;
     }
 
     @Override
-    public void onDeviceDisconnectedFromCluster(final boolean removeNodeFromDS) {
-        LOG.debug("Called onDeviceDisconnectedFromCluster in DeviceContext for entity:{}", entity);
-        deviceContext.onDeviceDisconnectedFromCluster(removeNodeFromDS);
+    public DeviceInfo getDeviceInfo() {
+        return deviceInfo;
     }
 
-    private boolean isDeviceConnected() {
-        return ConnectionContext.CONNECTION_STATE.WORKING.equals(
-                deviceContext.getPrimaryConnectionContext().getConnectionState());
+    @Override
+    public boolean isMainCandidateRegistered() {
+        return entityOwnershipCandidateRegistration != null;
     }
 
-    @Nullable
     @Override
-    public <T> RequestContext<T> createRequestContext() {
-        final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceContext.getReservedXid()) {
-            @Override
-            public void close() {
+    public boolean isTxCandidateRegistered() {
+        return txEntityOwnershipCandidateRegistration != null;
+    }
+
+    @Override
+    public boolean registerCandidate(final Entity entity_) {
+        boolean permit = false;
+        try {
+            permit = roleChangeGuard.tryAcquire(TIMEOUT, TimeUnit.SECONDS);
+            if(permit) {
+                LOG.debug("Register candidate for entity {}", entity_);
+                if (entity_.equals(this.entity)) {
+                    entityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity_);
+                } else {
+                    txEntityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity_);
+                }
+            } else {
+                return false;
             }
-        };
-        return ret;
+        } catch (final CandidateAlreadyRegisteredException e) {
+            LOG.warn("Candidate for entity {} is already registered.", entity_.getType());
+            return false;
+        } catch (final InterruptedException e) {
+            LOG.warn("Cannot acquire semaphore for register entity {} candidate.", entity_.getType());
+            return false;
+        } finally {
+            if (permit) {
+                roleChangeGuard.release();
+            }
+        }
+        return true;
     }
 
-    @VisibleForTesting
-    void setSalRoleService(final SalRoleService salRoleService) {
-        this.salRoleService = salRoleService;
+    @Override
+    public boolean unregisterCandidate(final Entity entity_) {
+        boolean permit = false;
+        try {
+            permit = roleChangeGuard.tryAcquire(TIMEOUT, TimeUnit.SECONDS);
+            if(permit) {
+                if (entity_.equals(this.entity)) {
+                    if (entityOwnershipCandidateRegistration != null) {
+                        LOG.debug("Unregister candidate for entity {}", entity_);
+                        entityOwnershipCandidateRegistration.close();
+                        entityOwnershipCandidateRegistration = null;
+                    }
+                } else {
+                    if (txEntityOwnershipCandidateRegistration != null) {
+                        LOG.debug("Unregister candidate for tx entity {}", entity_);
+                        txEntityOwnershipCandidateRegistration.close();
+                        txEntityOwnershipCandidateRegistration = null;
+                    }
+                }
+            } else {
+                return false;
+            }
+        } catch (final InterruptedException e) {
+            LOG.warn("Cannot acquire semaphore for unregister entity {} candidate.", entity_.getType());
+            return false;
+        } finally {
+            if (permit) {
+                roleChangeGuard.release();
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void close() {
+        unregisterAllCandidates();
+    }
+
+    public boolean isMaster(){
+        return (txEntityOwnershipCandidateRegistration != null && entityOwnershipCandidateRegistration != null);
     }
 }