Search in sources :

Example 16 with State

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

the class TemplateManagerImpl method detachIso.

@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_DETACH, eventDescription = "detaching ISO", async = true)
public boolean detachIso(long vmId) {
    Account caller = CallContext.current().getCallingAccount();
    Long userId = CallContext.current().getCallingUserId();
    // Verify input parameters
    UserVmVO vmInstanceCheck = _userVmDao.findById(vmId);
    if (vmInstanceCheck == null) {
        throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
    }
    UserVm userVM = _userVmDao.findById(vmId);
    if (userVM == null) {
        throw new InvalidParameterValueException("Please specify a valid VM.");
    }
    _accountMgr.checkAccess(caller, null, true, userVM);
    Long isoId = userVM.getIsoId();
    if (isoId == null) {
        throw new InvalidParameterValueException("The specified VM has no ISO attached to it.");
    }
    CallContext.current().setEventDetails("Vm Id: " + vmId + " ISO Id: " + isoId);
    State vmState = userVM.getState();
    if (vmState != State.Running && vmState != State.Stopped) {
        throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
    }
    // attach=false
    boolean result = attachISOToVM(vmId, userId, isoId, false);
    // => detach
    if (result) {
        return result;
    } else {
        throw new CloudRuntimeException("Failed to detach iso");
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) State(com.cloud.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Example 17 with State

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

the class CapacityManagerImpl method postStateTransitionEvent.

@Override
public boolean postStateTransitionEvent(StateMachine2.Transition<State, Event> transition, VirtualMachine vm, boolean status, Object opaque) {
    if (!status) {
        return false;
    }
    @SuppressWarnings("unchecked") Pair<Long, Long> hosts = (Pair<Long, Long>) opaque;
    Long oldHostId = hosts.first();
    State oldState = transition.getCurrentState();
    State newState = transition.getToState();
    Event event = transition.getEvent();
    s_logger.debug("VM state transitted from :" + oldState + " to " + newState + " with event: " + event + "vm's original host id: " + vm.getLastHostId() + " new host id: " + vm.getHostId() + " host id before state transition: " + oldHostId);
    if (oldState == State.Starting) {
        if (newState != State.Running) {
            releaseVmCapacity(vm, false, false, oldHostId);
        }
    } else if (oldState == State.Running) {
        if (event == Event.AgentReportStopped) {
            releaseVmCapacity(vm, false, true, oldHostId);
        } else if (event == Event.AgentReportMigrated) {
            releaseVmCapacity(vm, false, false, oldHostId);
        }
    } else if (oldState == State.Migrating) {
        if (event == Event.AgentReportStopped) {
            /* Release capacity from original host */
            releaseVmCapacity(vm, false, false, vm.getLastHostId());
            releaseVmCapacity(vm, false, false, oldHostId);
        } else if (event == Event.OperationFailed) {
            /* Release from dest host */
            releaseVmCapacity(vm, false, false, oldHostId);
        } else if (event == Event.OperationSucceeded) {
            releaseVmCapacity(vm, false, false, vm.getLastHostId());
        }
    } else if (oldState == State.Stopping) {
        if (event == Event.OperationSucceeded) {
            releaseVmCapacity(vm, false, true, oldHostId);
        } else if (event == Event.AgentReportStopped) {
            releaseVmCapacity(vm, false, false, oldHostId);
        } else if (event == Event.AgentReportMigrated) {
            releaseVmCapacity(vm, false, false, oldHostId);
        }
    } else if (oldState == State.Stopped) {
        if (event == Event.DestroyRequested || event == Event.ExpungeOperation) {
            releaseVmCapacity(vm, true, false, vm.getLastHostId());
        } else if (event == Event.AgentReportMigrated) {
            releaseVmCapacity(vm, false, false, oldHostId);
        }
    }
    if ((newState == State.Starting || newState == State.Migrating || event == Event.AgentReportMigrated) && vm.getHostId() != null) {
        boolean fromLastHost = false;
        if (vm.getHostId().equals(vm.getLastHostId())) {
            s_logger.debug("VM starting again on the last host it was stopped on");
            fromLastHost = true;
        }
        allocateVmCapacity(vm, fromLastHost);
    }
    if (newState == State.Stopped) {
        if (vm.getType() == VirtualMachine.Type.User) {
            UserVmVO userVM = _userVMDao.findById(vm.getId());
            _userVMDao.loadDetails(userVM);
            // free the message sent flag if it exists
            userVM.setDetail(MESSAGE_RESERVED_CAPACITY_FREED_FLAG, "false");
            _userVMDao.saveDetails(userVM);
        }
    }
    return true;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ResourceState(com.cloud.resource.ResourceState) State(com.cloud.vm.VirtualMachine.State) Event(com.cloud.vm.VirtualMachine.Event) Pair(com.cloud.utils.Pair)

Example 18 with State

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

the class VirtualMachineManagerImpl method cleanup.

protected boolean cleanup(final VirtualMachineGuru guru, final VirtualMachineProfile profile, final ItWorkVO work, final Event event, final boolean cleanUpEvenIfUnableToStop) {
    final VirtualMachine vm = profile.getVirtualMachine();
    final State state = vm.getState();
    s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
    try {
        if (state == State.Starting) {
            if (work != null) {
                final Step step = work.getStep();
                if (step == Step.Starting && !cleanUpEvenIfUnableToStop) {
                    s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step);
                    return false;
                }
                if (step == Step.Started || step == Step.Starting || step == Step.Release) {
                    if (vm.getHostId() != null) {
                        if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) {
                            s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
                            return false;
                        }
                    }
                }
                if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) {
                    s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step);
                    return true;
                }
            } else {
                if (vm.getHostId() != null) {
                    if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) {
                        s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
                        return false;
                    }
                }
            }
        } else if (state == State.Stopping) {
            if (vm.getHostId() != null) {
                if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) {
                    s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process");
                    return false;
                }
            }
        } else if (state == State.Migrating) {
            if (vm.getHostId() != null) {
                if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) {
                    s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
                    return false;
                }
            }
            if (vm.getLastHostId() != null) {
                if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) {
                    s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
                    return false;
                }
            }
        } else if (state == State.Running) {
            if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) {
                s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process");
                return false;
            }
        }
    } finally {
        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 cleanued up resources for the vm " + vm + " in " + state + " state");
    }
    return true;
}
Also used : PowerState(com.cloud.vm.VirtualMachine.PowerState) State(com.cloud.vm.VirtualMachine.State) Step(com.cloud.vm.ItWorkVO.Step) 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)

Example 19 with State

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

the class Ovm3VmSupport method execute.

/* do migrations of VMs in a simple way just inside a cluster for now */
public MigrateAnswer execute(final MigrateCommand cmd) {
    final String vmName = cmd.getVmName();
    String destUuid = cmd.getHostGuid();
    String destIp = cmd.getDestinationIp();
    State state = State.Error;
    /*
         * TODO: figure out non pooled migration, works from CLI but not from
         * the agent... perhaps pause the VM and then migrate it ? for now just
         * stop the VM.
         */
    String msg = "Migrating " + vmName + " to " + destIp;
    LOGGER.info(msg);
    if (!config.getAgentInOvm3Cluster() && !config.getAgentInOvm3Pool()) {
        try {
            Xen xen = new Xen(c);
            Xen.Vm vm = xen.getRunningVmConfig(vmName);
            HostVO destHost = resourceMgr.findHostByGuid(destUuid);
            if (destHost == null) {
                msg = "Unable to find migration target host in DB " + destUuid + " with ip " + destIp;
                LOGGER.info(msg);
                return new MigrateAnswer(cmd, false, msg, null);
            }
            xen.stopVm(ovmObject.deDash(vm.getVmRootDiskPoolId()), vm.getVmUuid());
            msg = destHost.toString();
            state = State.Stopping;
            return new MigrateAnswer(cmd, false, msg, null);
        } catch (Ovm3ResourceException e) {
            msg = "Unpooled VM Migrate of " + vmName + " to " + destUuid + " failed due to: " + e.getMessage();
            LOGGER.debug(msg, e);
            return new MigrateAnswer(cmd, false, msg, null);
        } finally {
            /* shouldn't we just reinitialize completely as a last resort ? */
            hypervisor.setVmState(vmName, state);
        }
    } else {
        try {
            Xen xen = new Xen(c);
            Xen.Vm vm = xen.getRunningVmConfig(vmName);
            if (vm == null) {
                state = State.Stopped;
                msg = vmName + " is no running on " + config.getAgentHostname();
                return new MigrateAnswer(cmd, false, msg, null);
            }
            /* not a storage migration!!! */
            xen.migrateVm(ovmObject.deDash(vm.getVmRootDiskPoolId()), vm.getVmUuid(), destIp);
            state = State.Stopping;
            msg = "Migration of " + vmName + " successfull";
            return new MigrateAnswer(cmd, true, msg, null);
        } catch (Ovm3ResourceException e) {
            msg = "Pooled VM Migrate" + ": Migration of " + vmName + " to " + destIp + " failed due to " + e.getMessage();
            LOGGER.debug(msg, e);
            return new MigrateAnswer(cmd, false, msg, null);
        } finally {
            hypervisor.setVmState(vmName, state);
        }
    }
}
Also used : Xen(com.cloud.hypervisor.ovm3.objects.Xen) MigrateAnswer(com.cloud.agent.api.MigrateAnswer) State(com.cloud.vm.VirtualMachine.State) Ovm3ResourceException(com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException) HostVO(com.cloud.host.HostVO)

Example 20 with State

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

the class Ovm3HypervisorSupportTest method ReportedVmStatesTest.

@Test
public void ReportedVmStatesTest() throws ConfigurationException, Ovm3ResourceException {
    Ovm3Configuration config = new Ovm3Configuration(configTest.getParams());
    con.setResult(xen.getMultipleVmsListXML());
    Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, config);
    hypervisor.vmStateMapClear();
    State vmState = hypervisor.getVmState(vmName);
    results.basicStringTest(vmState.toString(), State.Running.toString());
    hypervisor.setVmStateStarting(vmName);
    results.basicStringTest(hypervisor.getVmState(vmName).toString(), State.Starting.toString());
    hypervisor.setVmState(vmName, State.Running);
    results.basicStringTest(hypervisor.getVmState(vmName).toString(), State.Running.toString());
    hypervisor.revmoveVmState(vmName);
    assertNull(hypervisor.getVmState(vmName));
}
Also used : State(com.cloud.vm.VirtualMachine.State) Test(org.junit.Test) ConnectionTest(com.cloud.hypervisor.ovm3.objects.ConnectionTest) LinuxTest(com.cloud.hypervisor.ovm3.objects.LinuxTest) NetworkTest(com.cloud.hypervisor.ovm3.objects.NetworkTest) XenTest(com.cloud.hypervisor.ovm3.objects.XenTest) Ovm3SupportTest(com.cloud.hypervisor.ovm3.support.Ovm3SupportTest) XmlTestResultTest(com.cloud.hypervisor.ovm3.objects.XmlTestResultTest)

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