Bug 5596 - restart devices management improvement
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / role / RoleContextImpl.java
index 8cd41133159384c3f360f5538b085a2086590388..888a4e9590f5853bde315c33c6bf9094465093cd 100644 (file)
@@ -7,24 +7,34 @@
  */
 package org.opendaylight.openflowplugin.impl.role;
 
+import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
-
-import java.util.concurrent.Semaphore;
+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 io.netty.util.HashedWheelTimer;
+import io.netty.util.TimerTask;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
-
-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.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.openflowplugin.api.OFConstants;
+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.impl.LifecycleConductorImpl;
+import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
+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;
 
@@ -35,51 +45,28 @@ import org.slf4j.LoggerFactory;
 class RoleContextImpl implements RoleContext {
 
     private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
-    private static final int TIMEOUT = 12;
-
-    private final NodeId nodeId;
-    private final EntityOwnershipService entityOwnershipService;
-    private volatile EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration = null;
-    private volatile EntityOwnershipCandidateRegistration txEntityOwnershipCandidateRegistration = null;
-
-    private final Entity entity;
-    private final Entity txEntity;
+    // Maximum limit of timeout retries when cleaning DS, to prevent infinite recursive loops
+    private static final int MAX_CLEAN_DS_RETRIES = 3;
 
     private SalRoleService salRoleService = null;
-
-    private final Semaphore roleChangeGuard = new Semaphore(1, true);
-
-    private final LifecycleConductor conductor;
-
-    public RoleContextImpl(final NodeId nodeId, final EntityOwnershipService entityOwnershipService, final Entity entity, final Entity txEntity, final LifecycleConductor lifecycleConductor) {
-        this.entityOwnershipService = entityOwnershipService;
-        this.entity = entity;
-        this.txEntity = txEntity;
-        this.nodeId = nodeId;
-        this.conductor = lifecycleConductor;
-    }
-
-    @Override
-    public boolean initialization() {
-        LOG.info("Initialization main candidate for node {}", nodeId);
-        return registerCandidate(this.entity);
-    }
-
-    @Override
-    public void unregisterAllCandidates() {
-        LOG.info("Role context closed, unregistering all candidates for ownership for node {}", nodeId);
-        if (isMainCandidateRegistered()) {
-            unregisterCandidate(this.entity);
-        }
-        if (isTxCandidateRegistered()) {
-            unregisterCandidate(this.txEntity);
-        }
+    private final HashedWheelTimer hashedWheelTimer;
+    private final DeviceInfo deviceInfo;
+    private CONTEXT_STATE state;
+    private final RoleManager myManager;
+
+    RoleContextImpl(final DeviceInfo deviceInfo,
+                    final HashedWheelTimer hashedWheelTimer,
+                    final RoleManager myManager) {
+        this.deviceInfo = deviceInfo;
+        state = CONTEXT_STATE.WORKING;
+        this.myManager = myManager;
+        this.hashedWheelTimer = hashedWheelTimer;
     }
 
     @Nullable
     @Override
     public <T> RequestContext<T> createRequestContext() {
-        return new AbstractRequestContext<T>(conductor.reserveXidForDeviceMessage(nodeId)) {
+        return new AbstractRequestContext<T>(deviceInfo.reserveXidForDeviceMessage()) {
             @Override
             public void close() {
             }
@@ -98,98 +85,104 @@ class RoleContextImpl implements RoleContext {
     }
 
     @Override
-    public Entity getEntity() {
-        return this.entity;
-    }
-
-    @Override
-    public Entity getTxEntity() {
-        return this.txEntity;
+    public CONTEXT_STATE getState() {
+        return this.state;
     }
 
     @Override
-    public NodeId getNodeId() {
-        return nodeId;
+    public void setState(CONTEXT_STATE state) {
+        this.state = state;
     }
 
     @Override
-    public boolean isMainCandidateRegistered() {
-        return entityOwnershipCandidateRegistration != null;
+    public ServiceGroupIdentifier getServiceIdentifier() {
+        return this.deviceInfo.getServiceIdentifier();
     }
 
     @Override
-    public boolean isTxCandidateRegistered() {
-        return txEntityOwnershipCandidateRegistration != null;
+    public DeviceInfo getDeviceInfo() {
+        return this.deviceInfo;
     }
 
-    @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_);
+    public void startupClusterServices() throws ExecutionException, InterruptedException {
+        Futures.addCallback(sendRoleChangeToDevice(OfpRole.BECOMEMASTER), new FutureCallback<RpcResult<SetRoleOutput>>() {
+            @Override
+            public void onSuccess(@Nullable RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Role MASTER was successfully set on device, node {}", deviceInfo.getLOGValue());
                 }
-            } else {
-                return false;
             }
-        } 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();
+
+            @Override
+            public void onFailure(final Throwable throwable) {
+                LOG.warn("Was not able to set MASTER role on device, node {}", deviceInfo.getLOGValue());
             }
-        }
-        return true;
+        });
     }
 
     @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;
+    public ListenableFuture<Void> stopClusterServices(final boolean deviceDisconnected) {
+
+        if (!deviceDisconnected) {
+            ListenableFuture<Void> future = Futures.transform(makeDeviceSlave(), new Function<RpcResult<SetRoleOutput>, Void>() {
+                @Nullable
+                @Override
+                public Void apply(@Nullable RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
+                    return null;
+                }
+            });
+
+            Futures.addCallback(future, new FutureCallback<Void>() {
+                @Override
+                public void onSuccess(@Nullable Void aVoid) {
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("Role SLAVE was successfully propagated on device, node {}", deviceInfo.getLOGValue());
                     }
                 }
-            } 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();
-            }
+
+                @Override
+                public void onFailure(final Throwable throwable) {
+                    LOG.warn("Was not able to set role SLAVE to device on node {} ", deviceInfo.getLOGValue());
+                    LOG.trace("Error occurred on device role setting, probably connection loss: ", throwable);
+                    myManager.removeDeviceFromOperationalDS(deviceInfo, MAX_CLEAN_DS_RETRIES);
+
+                }
+            });
+            return future;
+        } else {
+            return myManager.removeDeviceFromOperationalDS(deviceInfo, MAX_CLEAN_DS_RETRIES);
         }
-        return true;
     }
 
     @Override
-    public void close() {
-        unregisterAllCandidates();
+    public ListenableFuture<RpcResult<SetRoleOutput>> makeDeviceSlave(){
+        return sendRoleChangeToDevice(OfpRole.BECOMESLAVE);
     }
 
-    public boolean isMaster(){
-        return (txEntityOwnershipCandidateRegistration != null && entityOwnershipCandidateRegistration != null);
+    private ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole) {
+        LOG.debug("Sending new role {} to device {}", newRole, deviceInfo.getNodeId());
+        final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture;
+        final Short version = deviceInfo.getVersion();
+        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(deviceInfo.getNodeId()))).build();
+            setRoleOutputFuture = getSalRoleService().setRole(setRoleInput);
+            final TimerTask timerTask = timeout -> {
+                if (!setRoleOutputFuture.isDone()) {
+                    LOG.warn("New role {} was not propagated to device {} during 10 sec", newRole, deviceInfo.getLOGValue());
+                    setRoleOutputFuture.cancel(true);
+                }
+            };
+            hashedWheelTimer.newTimeout(timerTask, 10, TimeUnit.SECONDS);
+        }
+        return JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture);
     }
+
 }