Search in sources :

Example 6 with State

use of com.cloud.legacymodel.vm.VirtualMachine.State in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method destroyVm.

@Override
public UserVm destroyVm(final long vmId) throws ResourceUnavailableException, ConcurrentOperationException {
    // Account caller = CallContext.current().getCallingAccount();
    // Long userId = CallContext.current().getCallingUserId();
    final Long userId = 2L;
    // Verify input parameters
    final UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null || vm.getRemoved() != null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId");
        throw ex;
    }
    if (vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
        s_logger.trace("Vm id=" + vmId + " is already destroyed");
        return vm;
    }
    final boolean status;
    final State vmState = vm.getState();
    try {
        final VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        status = vmEntity.destroy(Long.toString(userId));
    } catch (final CloudException e) {
        final CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e);
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (status) {
        // Mark the account's volumes as destroyed
        final List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
        if (vmState != State.Error) {
            // Get serviceOffering for Virtual Machine
            final ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
            // Update Resource Count for the given account
            resourceCountDecrement(vm.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
        }
        return _vmDao.findById(vmId);
    } else {
        final CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
}
Also used : VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) AllocationState(com.cloud.model.enumeration.AllocationState) ResourceState(com.cloud.legacymodel.resource.ResourceState) State(com.cloud.legacymodel.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VirtualMachineEntity(com.cloud.engine.cloud.entity.api.VirtualMachineEntity) CloudException(com.cloud.legacymodel.exceptions.CloudException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Example 7 with State

use of com.cloud.legacymodel.vm.VirtualMachine.State in project cosmic by MissionCriticalCloud.

the class VolumeOrchestrator method volumeInactive.

@Override
public boolean volumeInactive(final Volume volume) {
    final Long vmId = volume.getInstanceId();
    if (vmId != null) {
        final UserVm vm = this._entityMgr.findById(UserVm.class, vmId);
        if (vm == null) {
            return true;
        }
        final State state = vm.getState();
        return state.equals(State.Stopped) || state.equals(State.Destroyed);
    }
    return false;
}
Also used : UserVm(com.cloud.uservm.UserVm) State(com.cloud.legacymodel.vm.VirtualMachine.State)

Example 8 with State

use of com.cloud.legacymodel.vm.VirtualMachine.State in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method changeToStartState.

@DB
private Ternary<VMInstanceVO, ReservationContext, ItWorkVO> changeToStartState(final VMInstanceVO vm, final User caller, final Account account) throws ConcurrentOperationException {
    final long vmId = vm.getId();
    ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
    int retry = VmOpLockStateRetry.value();
    while (retry-- != 0) {
        try {
            final ItWorkVO workFinal = work;
            final Ternary<VMInstanceVO, ReservationContext, ItWorkVO> result = Transaction.execute(new TransactionCallbackWithException<Ternary<VMInstanceVO, ReservationContext, ItWorkVO>, NoTransitionException>() {

                @Override
                public Ternary<VMInstanceVO, ReservationContext, ItWorkVO> doInTransaction(final TransactionStatus status) throws NoTransitionException {
                    final Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
                    final ItWorkVO work = _workDao.persist(workFinal);
                    final ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
                    if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
                        s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
                        return new Ternary<>(vm, context, work);
                    }
                    return new Ternary<>(null, null, work);
                }
            });
            work = result.third();
            if (result.first() != null) {
                return result;
            }
        } catch (final NoTransitionException e) {
            s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
        }
        final VMInstanceVO instance = _vmDao.findById(vmId);
        if (instance == null) {
            throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
        }
        s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ".  Retry=" + retry);
        final State state = instance.getState();
        if (state == State.Running) {
            s_logger.debug("VM is already started: " + vm);
            return null;
        }
        if (state.isTransitional()) {
            if (!checkWorkItems(vm, state)) {
                throw new ConcurrentOperationException("There are concurrent operations on " + vm);
            } else {
                continue;
            }
        }
        if (state != State.Stopped) {
            s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
            return null;
        }
    }
    throw new ConcurrentOperationException("Unable to change the state of " + vm);
}
Also used : Ternary(com.cloud.legacymodel.utils.Ternary) TransactionStatus(com.cloud.utils.db.TransactionStatus) Journal(com.cloud.utils.Journal) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) PowerState(com.cloud.legacymodel.vm.VirtualMachine.PowerState) State(com.cloud.legacymodel.vm.VirtualMachine.State) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) DB(com.cloud.utils.db.DB)

Example 9 with State

use of com.cloud.legacymodel.vm.VirtualMachine.State in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method stateTransitTo.

@Override
public boolean stateTransitTo(final VirtualMachine vm1, final VirtualMachine.Event e, final Long hostId) throws NoTransitionException {
    final VMInstanceVO vm = (VMInstanceVO) vm1;
    final State oldState = vm.getState();
    if (oldState == State.Starting) {
        if (e == Event.OperationSucceeded) {
            vm.setLastHostId(hostId);
        }
    } else if (oldState == State.Stopping) {
        if (e == Event.OperationSucceeded) {
            vm.setLastHostId(null);
        }
    }
    return new StateMachine2Transitions(_stateMachine).transitTo(vm, e, new Pair<>(vm.getHostId(), hostId), _vmDao);
}
Also used : StateMachine2Transitions(com.cloud.utils.fsm.StateMachine2Transitions) PowerState(com.cloud.legacymodel.vm.VirtualMachine.PowerState) State(com.cloud.legacymodel.vm.VirtualMachine.State)

Example 10 with State

use of com.cloud.legacymodel.vm.VirtualMachine.State in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method advanceStop.

private void advanceStop(final VMInstanceVO vm, final boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
    final State state = vm.getState();
    if (state == State.Stopped) {
        s_logger.debug("VM is already stopped: " + vm);
        return;
    }
    if (state == State.Destroyed || state == State.Expunging || state == State.Error) {
        s_logger.debug("Stopped called on " + vm + " but the state is " + state);
        return;
    }
    // grab outstanding work item if any
    final ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
    if (work != null) {
        s_logger.debug("Found an outstanding work item for this vm " + vm + " with state:" + vm.getState() + ", work id:" + work.getId());
    }
    final Long hostId = vm.getHostId();
    if (hostId == null) {
        if (!cleanUpEvenIfUnableToStop) {
            s_logger.debug("HostId is null but this is not a forced stop, cannot stop vm " + vm + " with state:" + vm.getState());
            throw new CloudRuntimeException("Unable to stop " + vm);
        }
        try {
            stateTransitTo(vm, Event.AgentReportStopped, null, null);
        } catch (final NoTransitionException e) {
            s_logger.warn(e.getMessage());
        }
        // mark outstanding work item if any as done
        if (work != null) {
            s_logger.debug("Updating work item to Done, id:" + work.getId());
            work.setStep(Step.Done);
            _workDao.update(work.getId(), work);
        }
        return;
    }
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    try {
        if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
            throw new ConcurrentOperationException("VM is being operated on.");
        }
    } catch (final NoTransitionException e1) {
        if (!cleanUpEvenIfUnableToStop) {
            throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState());
        }
        final boolean doCleanup = true;
        s_logger.debug("Unable to transition the state but we're moving on because it's forced stop");
        if (doCleanup) {
            if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.StopRequested, cleanUpEvenIfUnableToStop)) {
                try {
                    if (work != null) {
                        s_logger.debug("Updating work item to Done, id:" + work.getId());
                    }
                    if (!changeState(vm, Event.AgentReportStopped, null, work, Step.Done)) {
                        throw new CloudRuntimeException("Unable to stop " + vm);
                    }
                } catch (final NoTransitionException e) {
                    s_logger.warn("Unable to cleanup " + vm);
                    throw new CloudRuntimeException("Unable to stop " + vm, e);
                }
            } else {
                s_logger.debug("Failed to cleanup VM: " + vm);
                throw new CloudRuntimeException("Failed to cleanup " + vm + " , current state " + vm.getState());
            }
        }
    }
    if (vm.getState() != State.Stopping) {
        throw new CloudRuntimeException("We cannot proceed with stop VM " + vm + " since it is not in 'Stopping' state, current state: " + vm.getState());
    }
    vmGuru.prepareStop(profile);
    final StopCommand stop = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false, cleanUpEvenIfUnableToStop);
    boolean stopped = false;
    Answer answer = null;
    try {
        answer = _agentMgr.send(vm.getHostId(), stop);
        if (answer != null) {
            if (answer instanceof StopAnswer) {
                final StopAnswer stopAns = (StopAnswer) answer;
                if (vm.getType() == VirtualMachineType.User) {
                    final String platform = stopAns.getPlatform();
                    if (platform != null) {
                        final UserVmVO userVm = _userVmDao.findById(vm.getId());
                        _userVmDao.loadDetails(userVm);
                        userVm.setDetail("platform", platform);
                        _userVmDao.saveDetails(userVm);
                    }
                }
            }
            stopped = answer.getResult();
            if (!stopped) {
                throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails());
            }
            vmGuru.finalizeStop(profile, answer);
            final GPUDeviceTO gpuDevice = stop.getGpuDevice();
            if (gpuDevice != null) {
                _resourceMgr.updateGPUDetails(vm.getHostId(), gpuDevice.getGroupDetails());
            }
        } else {
            throw new CloudRuntimeException("Invalid answer received in response to a StopCommand on " + vm.instanceName);
        }
    } catch (final AgentUnavailableException e) {
        s_logger.warn("Unable to stop vm, agent unavailable: " + e.toString());
    } catch (final OperationTimedoutException e) {
        s_logger.warn("Unable to stop vm, operation timed out: " + e.toString());
    } finally {
        if (!stopped) {
            if (!cleanUpEvenIfUnableToStop) {
                s_logger.warn("Unable to stop vm " + vm);
                try {
                    stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
                } catch (final NoTransitionException e) {
                    s_logger.warn("Unable to transition the state " + vm);
                }
                throw new CloudRuntimeException("Unable to stop " + vm);
            } else {
                s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop");
                vmGuru.finalizeStop(profile, answer);
            }
        }
    }
    s_logger.debug(vm + " is stopped on the host.  Proceeding to release resource held.");
    try {
        _networkMgr.release(profile, cleanUpEvenIfUnableToStop);
        s_logger.debug("Successfully released network resources for the vm " + vm);
    } catch (final Exception e) {
        s_logger.warn("Unable to release some network resources.", e);
    }
    volumeMgr.release(profile);
    s_logger.debug("Successfully released storage resources for the vm " + vm);
    try {
        if (work != null) {
            s_logger.debug("Updating the outstanding work item to Done, id:" + work.getId());
            work.setStep(Step.Done);
            _workDao.update(work.getId(), work);
        }
        if (!stateTransitTo(vm, Event.OperationSucceeded, null)) {
            throw new CloudRuntimeException("unable to stop " + vm);
        }
    } catch (final NoTransitionException e) {
        s_logger.warn(e.getMessage());
        throw new CloudRuntimeException("Unable to stop " + vm);
    }
}
Also used : OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) GPUDeviceTO(com.cloud.legacymodel.to.GPUDeviceTO) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ConnectionException(com.cloud.legacymodel.exceptions.ConnectionException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) InsufficientServerCapacityException(com.cloud.legacymodel.exceptions.InsufficientServerCapacityException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) CloudException(com.cloud.legacymodel.exceptions.CloudException) SQLException(java.sql.SQLException) InsufficientVirtualNetworkCapacityException(com.cloud.legacymodel.exceptions.InsufficientVirtualNetworkCapacityException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) UnPlugNicAnswer(com.cloud.legacymodel.communication.answer.UnPlugNicAnswer) AgentControlAnswer(com.cloud.legacymodel.communication.answer.AgentControlAnswer) ClusterVMMetaDataSyncAnswer(com.cloud.legacymodel.communication.answer.ClusterVMMetaDataSyncAnswer) RestoreVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RestoreVMSnapshotAnswer) RebootAnswer(com.cloud.legacymodel.communication.answer.RebootAnswer) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) PlugNicAnswer(com.cloud.legacymodel.communication.answer.PlugNicAnswer) CheckVirtualMachineAnswer(com.cloud.legacymodel.communication.answer.CheckVirtualMachineAnswer) StopAnswer(com.cloud.legacymodel.communication.answer.StopAnswer) Answer(com.cloud.legacymodel.communication.answer.Answer) StopCommand(com.cloud.legacymodel.communication.command.StopCommand) PowerState(com.cloud.legacymodel.vm.VirtualMachine.PowerState) State(com.cloud.legacymodel.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) StopAnswer(com.cloud.legacymodel.communication.answer.StopAnswer)

Aggregations

State (com.cloud.legacymodel.vm.VirtualMachine.State)13 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)5 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)5 PowerState (com.cloud.legacymodel.vm.VirtualMachine.PowerState)4 CloudException (com.cloud.legacymodel.exceptions.CloudException)3 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)3 NoTransitionException (com.cloud.legacymodel.exceptions.NoTransitionException)3 Account (com.cloud.legacymodel.user.Account)3 UserVmVO (com.cloud.vm.UserVmVO)3 ActionEvent (com.cloud.event.ActionEvent)2 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)2 ConnectionException (com.cloud.legacymodel.exceptions.ConnectionException)2 ExecutionException (com.cloud.legacymodel.exceptions.ExecutionException)2 InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)2 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)2 InsufficientServerCapacityException (com.cloud.legacymodel.exceptions.InsufficientServerCapacityException)2 InsufficientVirtualNetworkCapacityException (com.cloud.legacymodel.exceptions.InsufficientVirtualNetworkCapacityException)2 OperationTimedoutException (com.cloud.legacymodel.exceptions.OperationTimedoutException)2 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)2 StorageUnavailableException (com.cloud.legacymodel.exceptions.StorageUnavailableException)2