Search in sources :

Example 1 with NoTransitionException

use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.

the class ResourceManagerImpl method resourceStateTransitTo.

@Override
public boolean resourceStateTransitTo(final Host host, final ResourceState.Event event, final long msId) throws NoTransitionException {
    final ResourceState currentState = host.getResourceState();
    final ResourceState nextState = currentState.getNextState(event);
    if (nextState == null) {
        throw new NoTransitionException("No next resource state found for current state = " + currentState + " event = " + event);
    }
    // TO DO - Make it more granular and have better conversion into capacity type
    if (host.getType() == Type.Routing) {
        final CapacityState capacityState = nextState == ResourceState.Enabled ? CapacityState.Enabled : CapacityState.Disabled;
        final short[] capacityTypes = { Capacity.CAPACITY_TYPE_CPU, Capacity.CAPACITY_TYPE_MEMORY };
        _capacityDao.updateCapacityState(null, null, null, host.getId(), capacityState.toString(), capacityTypes);
    }
    return _hostDao.updateResourceState(currentState, event, nextState, host);
}
Also used : CapacityState(com.cloud.capacity.CapacityState) NoTransitionException(com.cloud.utils.fsm.NoTransitionException)

Example 2 with NoTransitionException

use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.

the class ResourceManagerImpl method doDeleteHost.

@DB
protected boolean doDeleteHost(final long hostId, final boolean isForced, final boolean isForceDeleteStorage) {
    _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
    // Verify that host exists
    final HostVO host = _hostDao.findById(hostId);
    if (host == null) {
        throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist");
    }
    _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), host.getDataCenterId());
    if (!isForced && host.getResourceState() != ResourceState.Maintenance) {
        throw new CloudRuntimeException("Host " + host.getUuid() + " cannot be deleted as it is not in maintenance mode. Either put the host into maintenance or perform a forced deletion.");
    }
    // Get storage pool host mappings here because they can be removed as a
    // part of handleDisconnect later
    // TODO: find out the bad boy, what's a buggy logic!
    final List<StoragePoolHostVO> pools = _storagePoolHostDao.listByHostIdIncludingRemoved(hostId);
    final ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(ResourceStateAdapter.Event.DELETE_HOST, false, host, isForced, isForceDeleteStorage);
    if (answer == null) {
        throw new CloudRuntimeException("No resource adapter respond to DELETE_HOST event for " + host.getName() + " id = " + hostId + ", hypervisorType is " + host.getHypervisorType() + ", host type is " + host.getType());
    }
    if (answer.getIsException()) {
        return false;
    }
    if (!answer.getIsContinue()) {
        return true;
    }
    Long clusterId = host.getClusterId();
    _agentMgr.notifyMonitorsOfHostAboutToBeRemoved(host.getId());
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            _dcDao.releasePrivateIpAddress(host.getPrivateIpAddress(), host.getDataCenterId(), null);
            _agentMgr.disconnectWithoutInvestigation(hostId, Status.Event.Remove);
            // delete host details
            _hostDetailsDao.deleteDetails(hostId);
            // if host is GPU enabled, delete GPU entries
            _hostGpuGroupsDao.deleteGpuEntries(hostId);
            // delete host tags
            _hostTagsDao.deleteTags(hostId);
            host.setGuid(null);
            final Long clusterId = host.getClusterId();
            host.setClusterId(null);
            _hostDao.update(host.getId(), host);
            _hostDao.remove(hostId);
            if (clusterId != null) {
                final List<HostVO> hosts = listAllHostsInCluster(clusterId);
                if (hosts.size() == 0) {
                    final ClusterVO cluster = _clusterDao.findById(clusterId);
                    cluster.setGuid(null);
                    _clusterDao.update(clusterId, cluster);
                }
            }
            try {
                resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId);
            } catch (final NoTransitionException e) {
                s_logger.debug("Cannot transmit host " + host.getId() + " to Enabled state", e);
            }
            // Delete the associated entries in host ref table
            _storagePoolHostDao.deletePrimaryRecordsForHost(hostId);
            // Make sure any VMs that were marked as being on this host are cleaned up
            final List<VMInstanceVO> vms = _vmDao.listByHostId(hostId);
            for (final VMInstanceVO vm : vms) {
                // this is how VirtualMachineManagerImpl does it when it syncs VM states
                vm.setState(State.Stopped);
                vm.setHostId(null);
                _vmDao.persist(vm);
            }
            // where
            for (final StoragePoolHostVO pool : pools) {
                final Long poolId = pool.getPoolId();
                final StoragePoolVO storagePool = _storagePoolDao.findById(poolId);
                if (storagePool.isLocal() && isForceDeleteStorage) {
                    storagePool.setUuid(null);
                    storagePool.setClusterId(null);
                    _storagePoolDao.update(poolId, storagePool);
                    _storagePoolDao.remove(poolId);
                    s_logger.debug("Local storage id=" + poolId + " is removed as a part of host removal id=" + hostId);
                }
            }
            // delete the op_host_capacity entry
            final Object[] capacityTypes = { Capacity.CAPACITY_TYPE_CPU, Capacity.CAPACITY_TYPE_MEMORY };
            final SearchCriteria<CapacityVO> hostCapacitySC = _capacityDao.createSearchCriteria();
            hostCapacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId);
            hostCapacitySC.addAnd("capacityType", SearchCriteria.Op.IN, capacityTypes);
            _capacityDao.remove(hostCapacitySC);
            // remove from dedicated resources
            final DedicatedResourceVO dr = _dedicatedDao.findByHostId(hostId);
            if (dr != null) {
                _dedicatedDao.remove(dr.getId());
            }
        }
    });
    if (clusterId != null) {
        _agentMgr.notifyMonitorsOfRemovedHost(host.getId(), clusterId);
    }
    return true;
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) SearchCriteria(com.cloud.utils.db.SearchCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Example 3 with NoTransitionException

use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.

the class ResourceManagerImpl method doCancelMaintenance.

private boolean doCancelMaintenance(final long hostId) {
    HostVO host;
    host = _hostDao.findById(hostId);
    if (host == null || host.getRemoved() != null) {
        s_logger.warn("Unable to find host " + hostId);
        return true;
    }
    /*
         * TODO: think twice about returning true or throwing out exception, I
         * really prefer to exception that always exposes bugs
         */
    if (host.getResourceState() != ResourceState.PrepareForMaintenance && host.getResourceState() != ResourceState.Maintenance && host.getResourceState() != ResourceState.ErrorInMaintenance) {
        throw new CloudRuntimeException("Cannot perform cancelMaintenance when resource state is " + host.getResourceState() + ", hostId = " + hostId);
    }
    /* TODO: move to listener */
    _haMgr.cancelScheduledMigrations(host);
    boolean vms_migrating = false;
    final List<VMInstanceVO> vms = _haMgr.findTakenMigrationWork();
    for (final VMInstanceVO vm : vms) {
        if (vm.getHostId() != null && vm.getHostId() == hostId) {
            s_logger.warn("Unable to cancel migration because the vm is being migrated: " + vm + ", hostId = " + hostId);
            vms_migrating = true;
        }
    }
    try {
        resourceStateTransitTo(host, ResourceState.Event.AdminCancelMaintenance, _nodeId);
        _agentMgr.pullAgentOutMaintenance(hostId);
        // for kvm, need to log into kvm host, restart cloudstack-agent
        if ((host.getHypervisorType() == HypervisorType.KVM && !vms_migrating) || host.getHypervisorType() == HypervisorType.LXC) {
            final boolean sshToAgent = Boolean.parseBoolean(_configDao.getValue(Config.KvmSshToAgentEnabled.key()));
            if (!sshToAgent) {
                s_logger.info("Configuration tells us not to SSH into Agents. Please restart the Agent (" + hostId + ")  manually");
                return true;
            }
            _hostDao.loadDetails(host);
            final String password = host.getDetail("password");
            final String username = host.getDetail("username");
            if (password == null || username == null) {
                s_logger.debug("Can't find password/username");
                return false;
            }
            final com.trilead.ssh2.Connection connection = SSHCmdHelper.acquireAuthorizedConnection(host.getPrivateIpAddress(), 22, username, password);
            if (connection == null) {
                s_logger.debug("Failed to connect to host: " + host.getPrivateIpAddress());
                return false;
            }
            try {
                SSHCmdHelper.sshExecuteCmdOneShot(connection, "service cloudstack-agent restart");
            } catch (final SshException e) {
                return false;
            }
        }
        return true;
    } catch (final NoTransitionException e) {
        s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", e);
        return false;
    }
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) VMInstanceVO(com.cloud.vm.VMInstanceVO) SshException(com.cloud.utils.ssh.SshException) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO)

Example 4 with NoTransitionException

use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.

the class NetworkOrchestrator method shutdownNetwork.

@Override
@DB
public boolean shutdownNetwork(final long networkId, final ReservationContext context, final boolean cleanupElements) {
    NetworkVO network = _networksDao.findById(networkId);
    if (network.getState() == Network.State.Allocated) {
        s_logger.debug("Network is already shutdown: " + network);
        return true;
    }
    if (network.getState() != Network.State.Implemented && network.getState() != Network.State.Shutdown) {
        s_logger.debug("Network is not implemented: " + network);
        return false;
    }
    try {
        //do global lock for the network
        network = _networksDao.acquireInLockTable(networkId, NetworkLockTimeout.value());
        if (network == null) {
            s_logger.warn("Unable to acquire lock for the network " + network + " as a part of network shutdown");
            return false;
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Lock is acquired for network " + network + " as a part of network shutdown");
        }
        if (network.getState() == Network.State.Allocated) {
            s_logger.debug("Network is already shutdown: " + network);
            return true;
        }
        if (network.getState() != Network.State.Implemented && network.getState() != Network.State.Shutdown) {
            s_logger.debug("Network is not implemented: " + network);
            return false;
        }
        if (isSharedNetworkWithServices(network)) {
            network.setState(Network.State.Shutdown);
            _networksDao.update(network.getId(), network);
        } else {
            try {
                stateTransitTo(network, Event.DestroyNetwork);
            } catch (final NoTransitionException e) {
                network.setState(Network.State.Shutdown);
                _networksDao.update(network.getId(), network);
            }
        }
        final boolean success = shutdownNetworkElementsAndResources(context, cleanupElements, network);
        final NetworkVO networkFinal = network;
        final boolean result = Transaction.execute(new TransactionCallback<Boolean>() {

            @Override
            public Boolean doInTransaction(final TransactionStatus status) {
                boolean result = false;
                if (success) {
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Network id=" + networkId + " is shutdown successfully, cleaning up corresponding resources now.");
                    }
                    final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
                    final NetworkProfile profile = convertNetworkToNetworkProfile(networkFinal.getId());
                    guru.shutdown(profile, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId()));
                    applyProfileToNetwork(networkFinal, profile);
                    final DataCenterVO zone = _dcDao.findById(networkFinal.getDataCenterId());
                    if (isSharedNetworkOfferingWithServices(networkFinal.getNetworkOfferingId()) && zone.getNetworkType() == NetworkType.Advanced) {
                        networkFinal.setState(Network.State.Setup);
                    } else {
                        try {
                            stateTransitTo(networkFinal, Event.OperationSucceeded);
                        } catch (final NoTransitionException e) {
                            networkFinal.setState(Network.State.Allocated);
                            networkFinal.setRestartRequired(false);
                        }
                    }
                    _networksDao.update(networkFinal.getId(), networkFinal);
                    _networksDao.clearCheckForGc(networkId);
                    result = true;
                } else {
                    try {
                        stateTransitTo(networkFinal, Event.OperationFailed);
                    } catch (final NoTransitionException e) {
                        networkFinal.setState(Network.State.Implemented);
                        _networksDao.update(networkFinal.getId(), networkFinal);
                    }
                    result = false;
                }
                return result;
            }
        });
        return result;
    } finally {
        if (network != null) {
            _networksDao.releaseFromLockTable(network.getId());
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Lock is released for network " + network + " as a part of network shutdown");
            }
        }
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkProfile(com.cloud.network.NetworkProfile) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) NetworkGuru(com.cloud.network.guru.NetworkGuru) TransactionStatus(com.cloud.utils.db.TransactionStatus) DB(com.cloud.utils.db.DB)

Example 5 with NoTransitionException

use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.

the class XenserverSnapshotStrategy method deleteSnapshot.

@Override
public boolean deleteSnapshot(Long snapshotId) {
    SnapshotVO snapshotVO = snapshotDao.findById(snapshotId);
    if (snapshotVO.getState() == Snapshot.State.Allocated) {
        snapshotDao.remove(snapshotId);
        return true;
    }
    if (snapshotVO.getState() == Snapshot.State.Destroyed) {
        return true;
    }
    if (Snapshot.State.Error.equals(snapshotVO.getState())) {
        List<SnapshotDataStoreVO> storeRefs = snapshotStoreDao.findBySnapshotId(snapshotId);
        for (SnapshotDataStoreVO ref : storeRefs) {
            snapshotStoreDao.expunge(ref.getId());
        }
        snapshotDao.remove(snapshotId);
        return true;
    }
    if (snapshotVO.getState() == Snapshot.State.CreatedOnPrimary) {
        s_logger.debug("delete snapshot on primary storage:");
        snapshotVO.setState(Snapshot.State.Destroyed);
        snapshotDao.update(snapshotId, snapshotVO);
        return true;
    }
    if (!Snapshot.State.BackedUp.equals(snapshotVO.getState()) && !Snapshot.State.Error.equals(snapshotVO.getState())) {
        throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is in " + snapshotVO.getState() + " Status");
    }
    // first mark the snapshot as destroyed, so that ui can't see it, but we
    // may not destroy the snapshot on the storage, as other snapshots may
    // depend on it.
    SnapshotInfo snapshotOnImage = snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Image);
    if (snapshotOnImage == null) {
        s_logger.debug("Can't find snapshot on backup storage, delete it in db");
        snapshotDao.remove(snapshotId);
        return true;
    }
    SnapshotObject obj = (SnapshotObject) snapshotOnImage;
    try {
        obj.processEvent(Snapshot.Event.DestroyRequested);
    } catch (NoTransitionException e) {
        s_logger.debug("Failed to set the state to destroying: ", e);
        return false;
    }
    try {
        boolean result = deleteSnapshotChain(snapshotOnImage);
        obj.processEvent(Snapshot.Event.OperationSucceeded);
        if (result) {
            //snapshot is deleted on backup storage, need to delete it on primary storage
            SnapshotDataStoreVO snapshotOnPrimary = snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Primary);
            if (snapshotOnPrimary != null) {
                SnapshotInfo snapshotOnPrimaryInfo = snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
                long volumeId = snapshotOnPrimary.getVolumeId();
                VolumeVO volumeVO = volumeDao.findById(volumeId);
                if (((PrimaryDataStoreImpl) snapshotOnPrimaryInfo.getDataStore()).getPoolType() == StoragePoolType.RBD && volumeVO != null) {
                    snapshotSvr.deleteSnapshot(snapshotOnPrimaryInfo);
                }
                snapshotOnPrimary.setState(State.Destroyed);
                snapshotStoreDao.update(snapshotOnPrimary.getId(), snapshotOnPrimary);
            }
        }
    } catch (Exception e) {
        s_logger.debug("Failed to delete snapshot: ", e);
        try {
            obj.processEvent(Snapshot.Event.OperationFailed);
        } catch (NoTransitionException e1) {
            s_logger.debug("Failed to change snapshot state: " + e.toString());
        }
        return false;
    }
    return true;
}
Also used : SnapshotInfo(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PrimaryDataStoreImpl(org.apache.cloudstack.storage.datastore.PrimaryDataStoreImpl) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) SnapshotDataStoreVO(org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Aggregations

NoTransitionException (com.cloud.utils.fsm.NoTransitionException)47 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)36 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)17 HostVO (com.cloud.host.HostVO)12 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)11 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)11 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)10 DB (com.cloud.utils.db.DB)9 Answer (com.cloud.agent.api.Answer)7 CopyCommandResult (org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult)7 CreateCmdResult (org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult)7 VolumeVO (com.cloud.storage.VolumeVO)6 VMInstanceVO (com.cloud.vm.VMInstanceVO)6 AgentControlAnswer (com.cloud.agent.api.AgentControlAnswer)5 CheckVirtualMachineAnswer (com.cloud.agent.api.CheckVirtualMachineAnswer)5 ClusterVMMetaDataSyncAnswer (com.cloud.agent.api.ClusterVMMetaDataSyncAnswer)5 PlugNicAnswer (com.cloud.agent.api.PlugNicAnswer)5 RebootAnswer (com.cloud.agent.api.RebootAnswer)5 RestoreVMSnapshotAnswer (com.cloud.agent.api.RestoreVMSnapshotAnswer)5 StartAnswer (com.cloud.agent.api.StartAnswer)5