*/
package org.opendaylight.openflowplugin.impl.role;
-import javax.annotation.Nullable;
-import java.util.concurrent.Future;
-
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
import com.google.common.base.Preconditions;
-import com.google.common.base.Verify;
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.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 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.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
+import org.opendaylight.openflowplugin.api.openflow.device.handlers.ClusterInitializationPhaseHandler;
+import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
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.slf4j.LoggerFactory;
/**
- * Created by kramesha on 9/12/15.
+ * Role context try to make change device role on device
*/
-public class RoleContextImpl implements RoleContext {
- private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
+class RoleContextImpl implements RoleContext {
- private final EntityOwnershipService entityOwnershipService;
- private EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration;
- private final DeviceContext deviceContext;
- private final Entity entity;
- private SalRoleService salRoleService;
-
- private final SettableFuture<OfpRole> initRoleChangeFuture;
+ private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
- private EntityOwnershipCandidateRegistration txEntityOwnershipCandidateRegistration;
- private SettableFuture<Void> txRoleChangeFuture;
- private final Entity txEntity;
+ private SalRoleService salRoleService = null;
+ private final HashedWheelTimer hashedWheelTimer;
+ private final DeviceInfo deviceInfo;
+ private CONTEXT_STATE state;
+ private final RoleManager myManager;
+ private ClusterInitializationPhaseHandler clusterInitializationPhaseHandler;
+ private final LifecycleService lifecycleService;
+
+ RoleContextImpl(final DeviceInfo deviceInfo,
+ final HashedWheelTimer hashedWheelTimer,
+ final RoleManager myManager,
+ final LifecycleService lifecycleService) {
+ this.deviceInfo = deviceInfo;
+ this.state = CONTEXT_STATE.WORKING;
+ this.myManager = myManager;
+ this.hashedWheelTimer = hashedWheelTimer;
+ this.lifecycleService = lifecycleService;
+ }
- public RoleContextImpl(final DeviceContext deviceContext, final EntityOwnershipService entityOwnershipService,
- final Entity entity, final Entity txEnitity) {
- this.entityOwnershipService = Preconditions.checkNotNull(entityOwnershipService);
- this.deviceContext = Preconditions.checkNotNull(deviceContext);
- this.entity = Preconditions.checkNotNull(entity);
- this.txEntity = Preconditions.checkNotNull(txEnitity);
+ @Nullable
+ @Override
+ public <T> RequestContext<T> createRequestContext() {
+ return new AbstractRequestContext<T>(deviceInfo.reserveXidForDeviceMessage()) {
+ @Override
+ public void close() {
+ }
+ };
+ }
- salRoleService = new SalRoleServiceImpl(this, deviceContext);
- initRoleChangeFuture = SettableFuture.create();
+ @Override
+ public void setSalRoleService(@Nonnull final SalRoleService salRoleService) {
+ Preconditions.checkNotNull(salRoleService);
+ this.salRoleService = salRoleService;
}
@Override
- public ListenableFuture<OfpRole> initialization() {
- LOG.debug("Initialization requestOpenflowEntityOwnership for entity {}", entity);
- try {
- entityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity);
- LOG.debug("RoleContextImpl : Candidate registered with ownership service for device :{}", deviceContext
- .getPrimaryConnectionContext().getNodeId().getValue());
- } catch (final CandidateAlreadyRegisteredException e) {
- completeInitRoleChangeFuture(null, e);
- }
- return initRoleChangeFuture;
+ public CONTEXT_STATE getState() {
+ return this.state;
}
@Override
- public void onRoleChanged(final OfpRole oldRole, final OfpRole newRole, final FutureCallback<Void> callback) {
- 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());
- completeInitRoleChangeFuture(null, null);
- return;
- }
+ public void setState(CONTEXT_STATE state) {
+ this.state = state;
+ }
- LOG.debug("Role change received from ownership listener from {} to {} for device:{}", oldRole, newRole,
- deviceContext.getPrimaryConnectionContext().getNodeId());
+ @Override
+ public ServiceGroupIdentifier getServiceIdentifier() {
+ return this.deviceInfo.getServiceIdentifier();
+ }
- final SetRoleInput setRoleInput = (new SetRoleInputBuilder())
- .setControllerRole(newRole)
- .setNode(new NodeRef(deviceContext.getDeviceState().getNodeInstanceIdentifier()))
- .build();
+ @Override
+ public DeviceInfo getDeviceInfo() {
+ return this.deviceInfo;
+ }
- final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture = salRoleService.setRole(setRoleInput);
+ public void startupClusterServices() throws ExecutionException, InterruptedException {
+ Futures.addCallback(sendRoleChangeToDevice(OfpRole.BECOMEMASTER), new RpcResultFutureCallback());
+ }
- 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.getDeviceState().getNodeId());
- deviceContext.getDeviceState().setRole(newRole);
- final ListenableFuture<Void> future = deviceContext.onClusterRoleChange(newRole);
- if (callback != null) {
- Futures.addCallback(future, callback);
+ @Override
+ 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());
+ }
}
- completeInitRoleChangeFuture(newRole, null);
- }
-
- @Override
- public void onFailure(final Throwable throwable) {
- LOG.error("Error in setRole {} for device {} ", newRole,
- deviceContext.getPrimaryConnectionContext().getNodeId(), throwable);
- completeInitRoleChangeFuture(null, throwable);
- }
- });
- }
- void completeInitRoleChangeFuture(@Nullable final OfpRole role, @Nullable final Throwable throwable) {
- if (initRoleChangeFuture.isDone()) {
- return;
- }
- if (!isDeviceConnected()) {
- LOG.debug("Device {} is disconnected from this node. Hence not attempting a role change.", deviceContext
- .getPrimaryConnectionContext().getNodeId());
- initRoleChangeFuture.cancel(true);
- return;
- }
- if (throwable != null) {
- LOG.warn("Connection Role change fail for entity {}", entity);
- initRoleChangeFuture.setException(throwable);
- } else if (role != null) {
- LOG.debug("Initialization Role for entity {} is chosed {}", entity, role);
- initRoleChangeFuture.set(role);
+ @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);
+ }
+ });
+ return future;
} else {
- LOG.debug("Unexpected initialization Role Change close for entity {}", entity);
- initRoleChangeFuture.cancel(true);
+ return myManager.removeDeviceFromOperationalDS(deviceInfo);
}
}
@Override
- public ListenableFuture<Void> setupTxCandidate() {
- LOG.debug("setupTxCandidate for entity {} and Transaction entity {}", entity, txEntity);
- Verify.verify(txEntity != null);
-
- try {
- txEntityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(txEntity);
- txRoleChangeFuture = SettableFuture.<Void> create();
- } catch (final CandidateAlreadyRegisteredException e) {
- return Futures.<Void> immediateFailedFuture(e);
- }
-
- return txRoleChangeFuture;
+ public ListenableFuture<RpcResult<SetRoleOutput>> makeDeviceSlave(){
+ return sendRoleChangeToDevice(OfpRole.BECOMESLAVE);
}
- @Override
- public void onTxRoleChange(final OfpRole oldRole, final OfpRole newRole) {
- LOG.trace("onTxRoleChange method call for Entity {}", entity);
-
- Verify.verify(txRoleChangeFuture != null, "TxRoleChangeFuture for entity {} is null", 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 (!txRoleChangeFuture.isDone()) {
- txRoleChangeFuture.cancel(true);
- }
- return;
+ @VisibleForTesting
+ ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Sending new role {} to device {}", newRole, deviceInfo.getNodeId());
}
-
- Verify.verify(txEntity != null, "TxEntity for Entity {} is null", entity);
- if (OfpRole.BECOMEMASTER.equals(newRole)) {
- if (!txRoleChangeFuture.isDone()) {
- txRoleChangeFuture.set(null);
- }
- } else if (OfpRole.BECOMESLAVE.equals(newRole)) {
- // NOOP
+ 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 5 sec", newRole, deviceInfo.getLOGValue());
+ setRoleOutputFuture.cancel(true);
+ }
+ };
+ hashedWheelTimer.newTimeout(timerTask, 5, TimeUnit.SECONDS);
} else {
- LOG.warn("Unexpected Role for entity {} TxEntity {}", entity, txEntity);
+ LOG.info("Device: {} with version: {} does not support role", deviceInfo.getLOGValue(), deviceInfo.getVersion());
+ return Futures.immediateFuture(null);
}
+ return JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture);
}
@Override
- public void close() {
- if (entityOwnershipCandidateRegistration != null) {
- LOG.debug("Closing EntityOwnershipCandidateRegistration for {}", entity);
- entityOwnershipCandidateRegistration.close();
- }
+ public void setLifecycleInitializationPhaseHandler(final ClusterInitializationPhaseHandler handler) {
+ this.clusterInitializationPhaseHandler = handler;
}
@Override
- public Entity getEntity() {
- return entity;
- }
+ public boolean onContextInstantiateService(final ConnectionContext connectionContext) {
- @Override
- public Entity getTxEntity() {
- return txEntity;
- }
+ if (connectionContext.getConnectionState().equals(ConnectionContext.CONNECTION_STATE.RIP)) {
+ LOG.warn("Connection on device {} was interrupted, will stop starting master services.", deviceInfo.getLOGValue());
+ return false;
+ }
- private boolean isDeviceConnected() {
- return ConnectionContext.CONNECTION_STATE.WORKING.equals(
- deviceContext.getPrimaryConnectionContext().getConnectionState());
+ Futures.addCallback(sendRoleChangeToDevice(OfpRole.BECOMEMASTER), new RpcResultFutureCallback());
+ return this.clusterInitializationPhaseHandler.onContextInstantiateService(connectionContext);
}
- @Nullable
- @Override
- public <T> RequestContext<T> createRequestContext() {
- final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceContext.getReservedXid()) {
- @Override
- public void close() {
+ private class RpcResultFutureCallback implements 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());
}
- };
- return ret;
- }
-
- @VisibleForTesting
- void setSalRoleService(final SalRoleService salRoleService) {
- this.salRoleService = salRoleService;
- }
-
- @Override
- public DeviceState getDeviceState() {
- return deviceContext.getDeviceState();
- }
+ }
- @Override
- public void suspendTxCandidate() {
- if (txEntityOwnershipCandidateRegistration != null) {
- txEntityOwnershipCandidateRegistration.close();
- txEntityOwnershipCandidateRegistration = null;
+ @Override
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Was not able to set MASTER role on device, node {}", deviceInfo.getLOGValue());
+ lifecycleService.closeConnection();
}
}
}