Search in sources :

Example 41 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class BaremetalManagerImpl method postStateTransitionEvent.

@Override
public boolean postStateTransitionEvent(StateMachine2.Transition<State, Event> transition, VirtualMachine vo, boolean status, Object opaque) {
    State newState = transition.getToState();
    State oldState = transition.getCurrentState();
    if (newState != State.Starting && newState != State.Error && newState != State.Expunging) {
        return true;
    }
    if (vo.getHypervisorType() != HypervisorType.BareMetal) {
        return true;
    }
    HostVO host = _hostDao.findById(vo.getHostId());
    if (host == null) {
        s_logger.debug("Skip oldState " + oldState + " to " + "newState " + newState + " transimtion");
        return true;
    }
    _hostDao.loadDetails(host);
    if (newState == State.Starting) {
        host.setDetail("vmName", vo.getInstanceName());
        s_logger.debug("Add vmName " + host.getDetail("vmName") + " to host " + host.getId() + " details");
    } else {
        if (host.getDetail("vmName") != null && host.getDetail("vmName").equalsIgnoreCase(vo.getInstanceName())) {
            s_logger.debug("Remove vmName " + host.getDetail("vmName") + " from host " + host.getId() + " details");
            host.getDetails().remove("vmName");
        }
    }
    _hostDao.saveDetails(host);
    return true;
}
Also used : State(com.cloud.vm.VirtualMachine.State) HostVO(com.cloud.host.HostVO)

Example 42 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class VolumeOrchestrator method volumeInactive.

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

Example 43 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

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;
    /*
         *  Remove the hacking logic here.
                // if there are active vm snapshots task, state change is not allowed
                if (_vmSnapshotMgr.hasActiveVMSnapshotTasks(vm.getId())) {
                    s_logger.error("State transit with event: " + e + " failed due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
                    return false;
                }
         */
    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(vm.getHostId());
        }
    }
    return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
}
Also used : PowerState(com.cloud.vm.VirtualMachine.PowerState) State(com.cloud.vm.VirtualMachine.State)

Example 44 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

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) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is already stopped: " + vm);
        }
        return;
    }
    if (state == State.Destroyed || state == State.Expunging || state == State.Error) {
        if (s_logger.isDebugEnabled()) {
            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) {
        if (s_logger.isDebugEnabled()) {
            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) {
            if (s_logger.isDebugEnabled()) {
                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) {
            if (s_logger.isDebugEnabled()) {
                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;
        if (s_logger.isDebugEnabled()) {
            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 (s_logger.isDebugEnabled() && 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 {
                if (s_logger.isDebugEnabled()) {
                    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);
    StopCommand stpCmd = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false);
    stpCmd.setControlIp(getControlNicIpForVM(vm));
    final StopCommand stop = stpCmd;
    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() == VirtualMachine.Type.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);
            }
        }
    }
    if (s_logger.isDebugEnabled()) {
        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);
    }
    try {
        if (vm.getHypervisorType() != HypervisorType.BareMetal) {
            volumeMgr.release(profile);
            s_logger.debug("Successfully released storage resources for the vm " + vm);
        }
    } catch (final Exception e) {
        s_logger.warn("Unable to release storage resources.", e);
    }
    try {
        if (work != null) {
            if (s_logger.isDebugEnabled()) {
                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.exception.OperationTimedoutException) GPUDeviceTO(com.cloud.agent.api.to.GPUDeviceTO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ExecutionException(com.cloud.utils.exception.ExecutionException) ConnectionException(com.cloud.exception.ConnectionException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) AffinityConflictException(com.cloud.exception.AffinityConflictException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) ConfigurationException(javax.naming.ConfigurationException) AgentControlAnswer(com.cloud.agent.api.AgentControlAnswer) RebootAnswer(com.cloud.agent.api.RebootAnswer) StartAnswer(com.cloud.agent.api.StartAnswer) RestoreVMSnapshotAnswer(com.cloud.agent.api.RestoreVMSnapshotAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) StopAnswer(com.cloud.agent.api.StopAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) ClusterVMMetaDataSyncAnswer(com.cloud.agent.api.ClusterVMMetaDataSyncAnswer) CheckVirtualMachineAnswer(com.cloud.agent.api.CheckVirtualMachineAnswer) StopCommand(com.cloud.agent.api.StopCommand) PowerState(com.cloud.vm.VirtualMachine.PowerState) State(com.cloud.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) StopAnswer(com.cloud.agent.api.StopAnswer)

Example 45 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class VirtualMachineManagerImpl method changeToStartState.

@DB
protected Ternary<VMInstanceVO, ReservationContext, ItWorkVO> changeToStartState(final VirtualMachineGuru vmGuru, 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())) {
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
                        }
                        return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(vm, context, work);
                    }
                    return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(null, null, work);
                }
            });
            work = result.third();
            if (result.first() != null) {
                return result;
            }
        } catch (final NoTransitionException e) {
            if (s_logger.isDebugEnabled()) {
                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);
        }
        if (s_logger.isDebugEnabled()) {
            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) {
            if (s_logger.isDebugEnabled()) {
                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.utils.Ternary) TransactionStatus(com.cloud.utils.db.TransactionStatus) Journal(com.cloud.utils.Journal) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) PowerState(com.cloud.vm.VirtualMachine.PowerState) State(com.cloud.vm.VirtualMachine.State) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) DB(com.cloud.utils.db.DB)

Aggregations

State (com.cloud.vm.VirtualMachine.State)45 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 ConfigurationException (javax.naming.ConfigurationException)11 HashMap (java.util.HashMap)9 PowerState (com.cloud.vm.VirtualMachine.PowerState)8 LibvirtException (org.libvirt.LibvirtException)8 CheckVirtualMachineAnswer (com.cloud.agent.api.CheckVirtualMachineAnswer)7 StartAnswer (com.cloud.agent.api.StartAnswer)7 StopAnswer (com.cloud.agent.api.StopAnswer)7 Map (java.util.Map)7 Connect (org.libvirt.Connect)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)5 Ovm3ResourceException (com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException)5 FileNotFoundException (java.io.FileNotFoundException)5 IOException (java.io.IOException)5 VmState (com.cloud.agent.api.StartupRoutingCommand.VmState)4 VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)4 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)4 Answer (com.cloud.agent.api.Answer)3 NicTO (com.cloud.agent.api.to.NicTO)3