Search in sources :

Example 6 with GPUDeviceTO

use of com.cloud.agent.api.to.GPUDeviceTO 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() == 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);
            }
        }
    }
    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.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) CloudException(com.cloud.exception.CloudException) 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) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) AffinityConflictException(com.cloud.exception.AffinityConflictException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) 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 7 with GPUDeviceTO

use of com.cloud.agent.api.to.GPUDeviceTO 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;
    }
    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());
        }
        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;
    } else {
        HostVO host = _hostDao.findById(hostId);
        if (!cleanUpEvenIfUnableToStop && vm.getState() == State.Running && host.getResourceState() == ResourceState.PrepareForMaintenance) {
            s_logger.debug("Host is in PrepareForMaintenance state - Stop VM operation on the VM id: " + vm.getId() + " is not allowed");
            throw new CloudRuntimeException("Stop VM operation on the VM id: " + vm.getId() + " is not allowed as host is preparing for maintenance mode");
        }
    }
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    try {
        if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
            throw new ConcurrentOperationException(String.format("%s is being operated on.", vm.toString()));
        }
    } 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.warn("Unable to transition the state but we're moving on because it's forced stop", e1);
        }
        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);
    Map<String, Boolean> vlanToPersistenceMap = getVlanToPersistenceMapForVM(vm.getId());
    final StopCommand stop = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false, cleanUpEvenIfUnableToStop);
    stop.setControlIp(getControlNicIpForVM(vm));
    if (MapUtils.isNotEmpty(vlanToPersistenceMap)) {
        stop.setVlanToPersistenceMap(vlanToPersistenceMap);
    }
    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(VmDetailConstants.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 (AgentUnavailableException | OperationTimedoutException e) {
        s_logger.warn(String.format("Unable to stop %s due to [%s].", profile.toString(), e.toString()), e);
    } 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, e);
                }
                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);
            }
        } else {
            if (VirtualMachine.systemVMs.contains(vm.getType())) {
                HostVO systemVmHost = ApiDBUtils.findHostByTypeNameAndZoneId(vm.getDataCenterId(), vm.getHostName(), VirtualMachine.Type.SecondaryStorageVm.equals(vm.getType()) ? Host.Type.SecondaryStorageVM : Host.Type.ConsoleProxy);
                if (systemVmHost != null) {
                    _agentMgr.agentStatusTransitTo(systemVmHost, Status.Event.ShutdownRequested, _nodeId);
                }
            }
        }
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug(vm + " is stopped on the host.  Proceeding to release resource held.");
    }
    releaseVmResources(profile, cleanUpEvenIfUnableToStop);
    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);
        }
        boolean result = stateTransitTo(vm, Event.OperationSucceeded, null);
        if (result) {
            if (VirtualMachine.Type.User.equals(vm.type) && ResourceCountRunningVMsonly.value()) {
                ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
                resourceCountDecrement(vm.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
            }
        } else {
            throw new CloudRuntimeException("unable to stop " + vm);
        }
    } catch (final NoTransitionException e) {
        String message = String.format("Unable to stop %s due to [%s].", vm.toString(), e.getMessage());
        s_logger.warn(message, e);
        throw new CloudRuntimeException(message, e);
    }
}
Also used : OperationTimedoutException(com.cloud.exception.OperationTimedoutException) GPUDeviceTO(com.cloud.agent.api.to.GPUDeviceTO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) HostVO(com.cloud.host.HostVO) MigrateVmToPoolAnswer(com.cloud.agent.api.MigrateVmToPoolAnswer) StopAnswer(com.cloud.agent.api.StopAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) AgentControlAnswer(com.cloud.agent.api.AgentControlAnswer) RebootAnswer(com.cloud.agent.api.RebootAnswer) StartAnswer(com.cloud.agent.api.StartAnswer) ReplugNicAnswer(com.cloud.agent.api.ReplugNicAnswer) RestoreVMSnapshotAnswer(com.cloud.agent.api.RestoreVMSnapshotAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) ClusterVMMetaDataSyncAnswer(com.cloud.agent.api.ClusterVMMetaDataSyncAnswer) CheckVirtualMachineAnswer(com.cloud.agent.api.CheckVirtualMachineAnswer) PrepareForMigrationAnswer(com.cloud.agent.api.PrepareForMigrationAnswer) StopCommand(com.cloud.agent.api.StopCommand) ResourceState(com.cloud.resource.ResourceState) State(com.cloud.vm.VirtualMachine.State) PowerState(com.cloud.vm.VirtualMachine.PowerState) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) StopAnswer(com.cloud.agent.api.StopAnswer)

Example 8 with GPUDeviceTO

use of com.cloud.agent.api.to.GPUDeviceTO in project cloudstack by apache.

the class VirtualMachineManagerImpl method sendStop.

protected boolean sendStop(final VirtualMachineGuru guru, final VirtualMachineProfile profile, final boolean force, final boolean checkBeforeCleanup) {
    final VirtualMachine vm = profile.getVirtualMachine();
    Map<String, Boolean> vlanToPersistenceMap = getVlanToPersistenceMapForVM(vm.getId());
    StopCommand stpCmd = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), checkBeforeCleanup);
    if (MapUtils.isNotEmpty(vlanToPersistenceMap)) {
        stpCmd.setVlanToPersistenceMap(vlanToPersistenceMap);
    }
    stpCmd.setControlIp(getControlNicIpForVM(vm));
    stpCmd.setVolumesToDisconnect(getVolumesToDisconnect(vm));
    final StopCommand stop = stpCmd;
    try {
        Answer answer = null;
        if (vm.getHostId() != null) {
            answer = _agentMgr.send(vm.getHostId(), stop);
        }
        if (answer != null && 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(VmDetailConstants.PLATFORM, platform);
                    _userVmDao.saveDetails(userVm);
                }
            }
            final GPUDeviceTO gpuDevice = stop.getGpuDevice();
            if (gpuDevice != null) {
                _resourceMgr.updateGPUDetails(vm.getHostId(), gpuDevice.getGroupDetails());
            }
            if (!answer.getResult()) {
                final String details = answer.getDetails();
                s_logger.debug("Unable to stop VM due to " + details);
                return false;
            }
            guru.finalizeStop(profile, answer);
            final UserVmVO userVm = _userVmDao.findById(vm.getId());
            if (vm.getType() == VirtualMachine.Type.User) {
                if (userVm != null) {
                    userVm.setPowerState(PowerState.PowerOff);
                    _userVmDao.update(userVm.getId(), userVm);
                }
            }
        } else {
            s_logger.error("Invalid answer received in response to a StopCommand for " + vm.getInstanceName());
            return false;
        }
    } catch (final AgentUnavailableException | OperationTimedoutException e) {
        s_logger.warn(String.format("Unable to stop %s due to [%s].", vm.toString(), e.getMessage()), e);
        if (!force) {
            return false;
        }
    }
    return true;
}
Also used : MigrateVmToPoolAnswer(com.cloud.agent.api.MigrateVmToPoolAnswer) StopAnswer(com.cloud.agent.api.StopAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) AgentControlAnswer(com.cloud.agent.api.AgentControlAnswer) RebootAnswer(com.cloud.agent.api.RebootAnswer) StartAnswer(com.cloud.agent.api.StartAnswer) ReplugNicAnswer(com.cloud.agent.api.ReplugNicAnswer) RestoreVMSnapshotAnswer(com.cloud.agent.api.RestoreVMSnapshotAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) ClusterVMMetaDataSyncAnswer(com.cloud.agent.api.ClusterVMMetaDataSyncAnswer) CheckVirtualMachineAnswer(com.cloud.agent.api.CheckVirtualMachineAnswer) PrepareForMigrationAnswer(com.cloud.agent.api.PrepareForMigrationAnswer) StopCommand(com.cloud.agent.api.StopCommand) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) GPUDeviceTO(com.cloud.agent.api.to.GPUDeviceTO) StopAnswer(com.cloud.agent.api.StopAnswer)

Example 9 with GPUDeviceTO

use of com.cloud.agent.api.to.GPUDeviceTO in project cloudstack by apache.

the class CitrixStartCommandWrapper method execute.

@Override
public Answer execute(final StartCommand command, final CitrixResourceBase citrixResourceBase) {
    final Connection conn = citrixResourceBase.getConnection();
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final String vmName = vmSpec.getName();
    VmPowerState state = VmPowerState.HALTED;
    VM vm = null;
    // if a VDI is created, record its UUID and its type (ex. VHD) to send back to the CS MS
    final Map<String, Map<String, String>> iqnToData = new HashMap<>();
    try {
        final Set<VM> vms = VM.getByNameLabel(conn, vmName);
        if (vms != null) {
            for (final VM v : vms) {
                final VM.Record vRec = v.getRecord(conn);
                if (vRec.powerState == VmPowerState.HALTED) {
                    v.destroy(conn);
                } else if (vRec.powerState == VmPowerState.RUNNING) {
                    final String host = vRec.residentOn.getUuid(conn);
                    final String msg = "VM " + vmName + " is runing on host " + host;
                    s_logger.debug(msg);
                    return new StartAnswer(command, msg, host);
                } else {
                    final String msg = "There is already a VM having the same name " + vmName + " vm record " + vRec.toString();
                    s_logger.warn(msg);
                    return new StartAnswer(command, msg);
                }
            }
        }
        s_logger.debug("1. The VM " + vmName + " is in Starting state.");
        final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
        vm = citrixResourceBase.createVmFromTemplate(conn, vmSpec, host);
        final GPUDeviceTO gpuDevice = vmSpec.getGpuDevice();
        if (gpuDevice != null) {
            s_logger.debug("Creating VGPU for of VGPU type: " + gpuDevice.getVgpuType() + " in GPU group " + gpuDevice.getGpuGroup() + " for VM " + vmName);
            citrixResourceBase.createVGPU(conn, command, vm, gpuDevice);
        }
        if (vmSpec.getType() != VirtualMachine.Type.User) {
            citrixResourceBase.createPatchVbd(conn, vmName, vm);
        }
        prepareDisks(vmSpec, citrixResourceBase, conn, iqnToData, vmName, vm);
        for (final NicTO nic : vmSpec.getNics()) {
            citrixResourceBase.createVif(conn, vmName, vm, vmSpec, nic);
        }
        citrixResourceBase.startVM(conn, host, vm, vmName);
        if (citrixResourceBase.isOvs()) {
            // TODO(Salvatore-orlando): This code should go
            for (final NicTO nic : vmSpec.getNics()) {
                if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vswitch) {
                    final HashMap<String, String> args = citrixResourceBase.parseDefaultOvsRuleComamnd(BroadcastDomainType.getValue(nic.getBroadcastUri()));
                    final OvsSetTagAndFlowCommand flowCmd = new OvsSetTagAndFlowCommand(args.get("vmName"), args.get("tag"), args.get("vlans"), args.get("seqno"), Long.parseLong(args.get("vmId")));
                    final CitrixRequestWrapper citrixRequestWrapper = CitrixRequestWrapper.getInstance();
                    final OvsSetTagAndFlowAnswer r = (OvsSetTagAndFlowAnswer) citrixRequestWrapper.execute(flowCmd, citrixResourceBase);
                    if (!r.getResult()) {
                        s_logger.warn("Failed to set flow for VM " + r.getVmId());
                    } else {
                        s_logger.info("Success to set flow for VM " + r.getVmId());
                    }
                }
            }
        }
        if (citrixResourceBase.canBridgeFirewall()) {
            String result = null;
            if (vmSpec.getType() != VirtualMachine.Type.User) {
                final NicTO[] nics = vmSpec.getNics();
                boolean secGrpEnabled = false;
                for (final NicTO nic : nics) {
                    if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
                        secGrpEnabled = true;
                        break;
                    }
                }
                if (secGrpEnabled) {
                    result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules_systemvm", "vmName", vmName);
                    if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
                        s_logger.warn("Failed to program default network rules for " + vmName);
                    } else {
                        s_logger.info("Programmed default network rules for " + vmName);
                    }
                }
            } else {
                // For user vm, program the rules for each nic if the
                // isolation uri scheme is ec2
                final NicTO[] nics = vmSpec.getNics();
                for (final NicTO nic : nics) {
                    if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
                        final List<String> nicSecIps = nic.getNicSecIps();
                        String secIpsStr;
                        final StringBuilder sb = new StringBuilder();
                        if (nicSecIps != null) {
                            for (final String ip : nicSecIps) {
                                sb.append(ip).append(";");
                            }
                            secIpsStr = sb.toString();
                        } else {
                            secIpsStr = "0;";
                        }
                        result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(), "vmID", Long.toString(vmSpec.getId()), "secIps", secIpsStr);
                        if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
                            s_logger.warn("Failed to program default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
                        } else {
                            s_logger.info("Programmed default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
                        }
                    }
                }
            }
        }
        state = VmPowerState.RUNNING;
        final StartAnswer startAnswer = new StartAnswer(command);
        startAnswer.setIqnToData(iqnToData);
        return startAnswer;
    } catch (final Exception e) {
        s_logger.warn("Catch Exception: " + e.getClass().toString() + " due to " + e.toString(), e);
        final String msg = citrixResourceBase.handleVmStartFailure(conn, vmName, vm, "", e);
        final StartAnswer startAnswer = new StartAnswer(command, msg);
        startAnswer.setIqnToData(iqnToData);
        return startAnswer;
    } finally {
        if (state != VmPowerState.HALTED) {
            s_logger.debug("2. The VM " + vmName + " is in " + state + " state.");
        } else {
            s_logger.debug("The VM is in stopped state, detected problem during startup : " + vmName);
        }
    }
}
Also used : StartAnswer(com.cloud.agent.api.StartAnswer) HashMap(java.util.HashMap) Connection(com.xensource.xenapi.Connection) Host(com.xensource.xenapi.Host) OvsSetTagAndFlowAnswer(com.cloud.agent.api.OvsSetTagAndFlowAnswer) GPUDeviceTO(com.cloud.agent.api.to.GPUDeviceTO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) OvsSetTagAndFlowCommand(com.cloud.agent.api.OvsSetTagAndFlowCommand) VM(com.xensource.xenapi.VM) VmPowerState(com.xensource.xenapi.Types.VmPowerState) HashMap(java.util.HashMap) Map(java.util.Map) NicTO(com.cloud.agent.api.to.NicTO)

Example 10 with GPUDeviceTO

use of com.cloud.agent.api.to.GPUDeviceTO in project cloudstack by apache.

the class CitrixStopCommandWrapper method execute.

@Override
public Answer execute(final StopCommand command, final CitrixResourceBase citrixResourceBase) {
    final String vmName = command.getVmName();
    final Map<String, Boolean> vlanToPersistenceMap = command.getVlanToPersistenceMap();
    String platformstring = null;
    try {
        final Connection conn = citrixResourceBase.getConnection();
        final Set<VM> vms = VM.getByNameLabel(conn, vmName);
        // stop vm which is running on this host or is in halted state
        final Iterator<VM> iter = vms.iterator();
        while (iter.hasNext()) {
            final VM vm = iter.next();
            final VM.Record vmr = vm.getRecord(conn);
            if (vmr.powerState != VmPowerState.RUNNING) {
                continue;
            }
            if (citrixResourceBase.isRefNull(vmr.residentOn)) {
                continue;
            }
            if (vmr.residentOn.getUuid(conn).equals(citrixResourceBase.getHost().getUuid())) {
                continue;
            }
            iter.remove();
        }
        if (vms.size() == 0) {
            return new StopAnswer(command, "VM does not exist", true);
        }
        for (final VM vm : vms) {
            final VM.Record vmr = vm.getRecord(conn);
            platformstring = StringUtils.mapToString(vmr.platform);
            if (vmr.isControlDomain) {
                final String msg = "Tring to Shutdown control domain";
                s_logger.warn(msg);
                return new StopAnswer(command, msg, false);
            }
            if (vmr.powerState == VmPowerState.RUNNING && !citrixResourceBase.isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(citrixResourceBase.getHost().getUuid())) {
                final String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + citrixResourceBase.getHost().getUuid() + " but host:" + vmr.residentOn.getUuid(conn);
                s_logger.warn(msg);
                return new StopAnswer(command, msg, platformstring, false);
            }
            if (command.checkBeforeCleanup() && vmr.powerState == VmPowerState.RUNNING) {
                final String msg = "Vm " + vmName + " is running on host and checkBeforeCleanup flag is set, so bailing out";
                s_logger.debug(msg);
                return new StopAnswer(command, msg, false);
            }
            s_logger.debug("9. The VM " + vmName + " is in Stopping state");
            try {
                if (vmr.powerState == VmPowerState.RUNNING) {
                    /* when stop a vm, set affinity to current xenserver */
                    vm.setAffinity(conn, vm.getResidentOn(conn));
                    if (citrixResourceBase.canBridgeFirewall()) {
                        final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "destroy_network_rules_for_vm", "vmName", command.getVmName());
                        if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
                            s_logger.warn("Failed to remove  network rules for vm " + command.getVmName());
                        } else {
                            s_logger.info("Removed  network rules for vm " + command.getVmName());
                        }
                    }
                    citrixResourceBase.shutdownVM(conn, vm, vmName, command.isForceStop());
                }
            } catch (final Exception e) {
                final String msg = "Catch exception " + e.getClass().getName() + " when stop VM:" + command.getVmName() + " due to " + e.toString();
                s_logger.debug(msg);
                return new StopAnswer(command, msg, platformstring, false);
            } finally {
                try {
                    if (vm.getPowerState(conn) == VmPowerState.HALTED) {
                        Set<VGPU> vGPUs = null;
                        // Get updated GPU details
                        try {
                            vGPUs = vm.getVGPUs(conn);
                        } catch (final XenAPIException e2) {
                            s_logger.debug("VM " + vmName + " does not have GPU support.");
                        }
                        if (vGPUs != null && !vGPUs.isEmpty()) {
                            final HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = citrixResourceBase.getGPUGroupDetails(conn);
                            command.setGpuDevice(new GPUDeviceTO(null, null, groupDetails));
                        }
                        final Set<VIF> vifs = vm.getVIFs(conn);
                        final List<Network> networks = new ArrayList<Network>();
                        for (final VIF vif : vifs) {
                            networks.add(vif.getNetwork(conn));
                        }
                        vm.destroy(conn);
                        final SR sr = citrixResourceBase.getISOSRbyVmName(conn, command.getVmName());
                        citrixResourceBase.removeSR(conn, sr);
                        // anymore
                        for (final Network network : networks) {
                            try {
                                if (network.getNameLabel(conn).startsWith("VLAN")) {
                                    String networkLabel = network.getNameLabel(conn);
                                    citrixResourceBase.disableVlanNetwork(conn, network, shouldDeleteVlan(networkLabel, vlanToPersistenceMap));
                                }
                            } catch (final Exception e) {
                            // network might be destroyed by other host
                            }
                        }
                        return new StopAnswer(command, "Stop VM " + vmName + " Succeed", platformstring, true);
                    }
                } catch (final Exception e) {
                    final String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage();
                    s_logger.warn(msg, e);
                } finally {
                    s_logger.debug("10. The VM " + vmName + " is in Stopped state");
                }
            }
        }
    } catch (final Exception e) {
        final String msg = "Stop Vm " + vmName + " fail due to " + e.toString();
        s_logger.warn(msg, e);
        return new StopAnswer(command, msg, platformstring, false);
    }
    return new StopAnswer(command, "Stop VM failed", platformstring, false);
}
Also used : HashMap(java.util.HashMap) Connection(com.xensource.xenapi.Connection) ArrayList(java.util.ArrayList) XenAPIException(com.xensource.xenapi.Types.XenAPIException) GPUDeviceTO(com.cloud.agent.api.to.GPUDeviceTO) XenAPIException(com.xensource.xenapi.Types.XenAPIException) VIF(com.xensource.xenapi.VIF) VM(com.xensource.xenapi.VM) Network(com.xensource.xenapi.Network) StopAnswer(com.cloud.agent.api.StopAnswer) VGPU(com.xensource.xenapi.VGPU) SR(com.xensource.xenapi.SR)

Aggregations

GPUDeviceTO (com.cloud.agent.api.to.GPUDeviceTO)10 StartAnswer (com.cloud.agent.api.StartAnswer)8 StopAnswer (com.cloud.agent.api.StopAnswer)8 AgentControlAnswer (com.cloud.agent.api.AgentControlAnswer)6 Answer (com.cloud.agent.api.Answer)6 CheckVirtualMachineAnswer (com.cloud.agent.api.CheckVirtualMachineAnswer)6 ClusterVMMetaDataSyncAnswer (com.cloud.agent.api.ClusterVMMetaDataSyncAnswer)6 PlugNicAnswer (com.cloud.agent.api.PlugNicAnswer)6 RebootAnswer (com.cloud.agent.api.RebootAnswer)6 RestoreVMSnapshotAnswer (com.cloud.agent.api.RestoreVMSnapshotAnswer)6 StopCommand (com.cloud.agent.api.StopCommand)6 UnPlugNicAnswer (com.cloud.agent.api.UnPlugNicAnswer)6 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)6 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)6 HashMap (java.util.HashMap)6 VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)4 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)4 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)4 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)4 AffinityConflictException (com.cloud.exception.AffinityConflictException)3