Search in sources :

Example 1 with StartAnswer

use of com.cloud.legacymodel.communication.answer.StartAnswer in project cosmic by MissionCriticalCloud.

the class LibvirtStartCommandWrapper method execute.

@Override
public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final String vmName = vmSpec.getName();
    LibvirtVmDef vm = null;
    DomainState state = DomainState.VIR_DOMAIN_SHUTOFF;
    final KvmStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
    Connect conn = null;
    try {
        vm = libvirtComputingResource.createVmFromSpec(vmSpec);
        conn = libvirtUtilitiesHelper.getConnectionByType(vm.getHvsType());
        final Long remainingMem = getFreeMemory(conn, libvirtComputingResource);
        if (remainingMem == null) {
            return new StartAnswer(command, "Failed to get free memory");
        } else if (remainingMem < vmSpec.getMinRam()) {
            return new StartAnswer(command, "Not enough memory on the host, remaining: " + remainingMem + ", asking: " + vmSpec.getMinRam());
        }
        final NicTO[] nics = vmSpec.getNics();
        libvirtComputingResource.createVbd(conn, vmSpec, vmName, vm);
        if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)) {
            return new StartAnswer(command, "Failed to connect physical disks to host");
        }
        libvirtComputingResource.createVifs(vmSpec, vm);
        s_logger.debug("starting " + vmName + ": " + vm.toString());
        libvirtComputingResource.startVm(conn, vmName, vm.toString());
        // system vms
        if (vmSpec.getType() != VirtualMachineType.User) {
            // pass cmdline with config for the systemvm to configure itself
            if (libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())) {
                s_logger.debug("Passing cmdline succeeded");
            } else {
                final String errorMessage = "Passing cmdline failed, aborting.";
                s_logger.debug(errorMessage);
                return new StartAnswer(command, errorMessage);
            }
            String controlIp = null;
            for (final NicTO nic : nics) {
                if (nic.getType() == TrafficType.Control) {
                    controlIp = nic.getIp();
                    break;
                }
            }
            // connect to the router by using its linklocal address (that should now be configured)
            s_logger.debug("Starting ssh attempts to " + controlIp);
            final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
            if (!virtRouterResource.connect(controlIp, 30, 5000)) {
                final String errorMessage = "Unable to login to router via linklocal address " + controlIp + " after 30 tries, aborting.";
                s_logger.debug(errorMessage);
                return new StartAnswer(command, errorMessage);
            }
            s_logger.debug("Successfully completed ssh attempts to " + controlIp);
        }
        state = DomainState.VIR_DOMAIN_RUNNING;
        return new StartAnswer(command);
    } catch (final LibvirtException | InternalErrorException | URISyntaxException e) {
        s_logger.warn("Exception while starting VM: " + ExceptionUtils.getRootCauseMessage(e));
        if (conn != null) {
            libvirtComputingResource.handleVmStartFailure(vm);
        }
        return new StartAnswer(command, e.getMessage());
    } finally {
        if (state != DomainState.VIR_DOMAIN_RUNNING) {
            storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec);
        }
    }
}
Also used : LibvirtVmDef(com.cloud.agent.resource.kvm.xml.LibvirtVmDef) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) VirtualRoutingResource(com.cloud.common.virtualnetwork.VirtualRoutingResource) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) URISyntaxException(java.net.URISyntaxException) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) DomainState(org.libvirt.DomainInfo.DomainState) KvmStoragePoolManager(com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager) NicTO(com.cloud.legacymodel.to.NicTO)

Example 2 with StartAnswer

use of com.cloud.legacymodel.communication.answer.StartAnswer in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateStart.

@Override
public void orchestrateStart(final String vmUuid, final Map<VirtualMachineProfile.Param, Object> params, final DeploymentPlan planToDeploy, final DeploymentPlanner planner) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
    final CallContext cctxt = CallContext.current();
    final Account account = cctxt.getCallingAccount();
    final User caller = cctxt.getCallingUser();
    VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final Ternary<VMInstanceVO, ReservationContext, ItWorkVO> start = changeToStartState(vm, caller, account);
    if (start == null) {
        return;
    }
    vm = start.first();
    final ReservationContext ctx = start.second();
    ItWorkVO work = start.third();
    VMInstanceVO startedVm = null;
    final ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
    final VirtualMachineTemplate template = _entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, vm.getTemplateId());
    s_logger.debug("Trying to deploy VM, vm has dcId: " + vm.getDataCenterId() + " and podId: " + vm.getPodIdToDeployIn());
    DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null, ctx);
    if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
        s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:" + planToDeploy.getDataCenterId() + ", podId: " + planToDeploy.getPodId() + ", clusterId: " + planToDeploy.getClusterId() + ", hostId: " + planToDeploy.getHostId() + ", poolId: " + planToDeploy.getPoolId());
        plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), planToDeploy.getPoolId(), planToDeploy.getPhysicalNetworkId(), ctx);
    }
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    boolean canRetry = true;
    ExcludeList avoids = null;
    try {
        final Journal journal = start.second().getJournal();
        if (planToDeploy != null) {
            avoids = planToDeploy.getAvoids();
        }
        if (avoids == null) {
            avoids = new ExcludeList();
        }
        s_logger.debug("VM start orchestration will {}", avoids.toString());
        boolean planChangedByVolume = false;
        boolean reuseVolume = true;
        final DataCenterDeployment originalPlan = plan;
        int retry = StartRetry.value();
        while (retry-- != 0) {
            if (reuseVolume) {
                // edit plan if this vm's ROOT volume is in READY state already
                final List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
                for (final VolumeVO vol : vols) {
                    // make sure if the templateId is unchanged. If it is changed,
                    // let planner
                    // reassign pool for the volume even if it ready.
                    final Long volTemplateId = vol.getTemplateId();
                    if (volTemplateId != null && volTemplateId != template.getId()) {
                        s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool");
                        continue;
                    }
                    final StoragePool pool = (StoragePool) dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
                    if (!pool.isInMaintenance()) {
                        s_logger.debug("Root volume is ready, need to place VM in volume's cluster");
                        final long rootVolDcId = pool.getDataCenterId();
                        final Long rootVolPodId = pool.getPodId();
                        final Long rootVolClusterId = pool.getClusterId();
                        if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
                            final Long clusterIdSpecified = planToDeploy.getClusterId();
                            if (clusterIdSpecified != null && rootVolClusterId != null) {
                                checkIfPlanIsDeployable(vm, rootVolClusterId, clusterIdSpecified);
                            }
                            plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId(), null, ctx);
                        } else {
                            plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId(), null, ctx);
                            s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId + " , and clusterId: " + rootVolClusterId);
                            planChangedByVolume = true;
                        }
                    }
                }
            }
            final Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
            final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params);
            final DeployDestination dest = _dpMgr.planDeployment(vmProfile, plan, avoids, planner);
            if (dest == null) {
                if (planChangedByVolume) {
                    plan = originalPlan;
                    planChangedByVolume = false;
                    // do not enter volume reuse for next retry, since we want to look for resources outside the volume's cluster
                    reuseVolume = false;
                    continue;
                }
                throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId(), areAffinityGroupsAssociated(vmProfile));
            }
            if (dest != null) {
                avoids.addHost(dest.getHost().getId());
                journal.record("Deployment found ", vmProfile, dest);
            }
            long destHostId = dest.getHost().getId();
            vm.setPodIdToDeployIn(dest.getPod().getId());
            final Long cluster_id = dest.getCluster().getId();
            final ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
            final ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
            // storing the value of overcommit in the vm_details table for doing a capacity check in case the cluster overcommit ratio is changed.
            if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") == null && (Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f)) {
                _uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue(), true);
                _uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue(), true);
            } else if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") != null) {
                _uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue(), true);
                _uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue(), true);
            }
            vmProfile.setCpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
            vmProfile.setMemoryOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
            StartAnswer startAnswer = null;
            try {
                if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
                    throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine " + vm.getUuid() + " oldstate: " + vm.getState() + "Event :" + Event.OperationRetry);
                }
            } catch (final NoTransitionException e1) {
                throw new ConcurrentOperationException(e1.getMessage());
            }
            try {
                s_logger.debug("VM is being created in podId: " + vm.getPodIdToDeployIn());
                _networkMgr.prepare(vmProfile, dest, ctx);
                volumeMgr.prepare(vmProfile, dest);
                // since StorageMgr succeeded in volume creation, reuse Volume for further tries until current cluster has capacity
                if (!reuseVolume) {
                    reuseVolume = true;
                }
                vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx);
                final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
                handlePath(vmTO.getDisks(), vm.getHypervisorType());
                final Commands cmds = new Commands(Command.OnError.Stop);
                cmds.addCommand(new StartCommand(vmTO, dest.getHost(), getExecuteInSequence(vm.getHypervisorType())));
                vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx);
                work = _workDao.findById(work.getId());
                if (work == null || work.getStep() != Step.Prepare) {
                    throw new ConcurrentOperationException("Work steps have been changed: " + work);
                }
                _workDao.updateStep(work, Step.Starting);
                _agentMgr.send(destHostId, cmds);
                _workDao.updateStep(work, Step.Started);
                startAnswer = cmds.getAnswer(StartAnswer.class);
                // Set date and version we start this VM
                vm.setLastStartDateTime(getCurrentLocalDateTimeStamp());
                vm.setLastStartVersion(VirtualMachineManagerImpl.class.getPackage().getImplementationVersion());
                // Reset VM compliance state
                if (vm.getComplianceStatus() == ComplianceStatus.VMNeedsRestart) {
                    vm.setComplianceStatus(ComplianceStatus.Compliant);
                }
                _vmDao.persist(vm);
                if (startAnswer != null && startAnswer.getResult()) {
                    handlePath(vmTO.getDisks(), startAnswer.getIqnToPath());
                    final String host_guid = startAnswer.getHost_guid();
                    if (host_guid != null) {
                        final HostVO finalHost = _resourceMgr.findHostByGuid(host_guid);
                        if (finalHost == null) {
                            throw new CloudRuntimeException("Host Guid " + host_guid + " doesn't exist in DB, something went wrong while processing start answer: " + startAnswer);
                        }
                        destHostId = finalHost.getId();
                    }
                    if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) {
                        syncDiskChainChange(startAnswer);
                        if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) {
                            s_logger.error("Unable to transition to a new state. VM uuid: " + vm.getUuid() + "VM oldstate:" + vm.getState() + "Event:" + Event.OperationSucceeded);
                            throw new ConcurrentOperationException("Failed to deploy VM" + vm.getUuid());
                        }
                        // Update GPU device capacity
                        final GPUDeviceTO gpuDevice = startAnswer.getVirtualMachine().getGpuDevice();
                        if (gpuDevice != null) {
                            _resourceMgr.updateGPUDetails(destHostId, gpuDevice.getGroupDetails());
                        }
                        startedVm = vm;
                        s_logger.debug("Start completed for VM " + vm);
                        return;
                    } else {
                        s_logger.info("The guru did not like the answers so stopping " + vm);
                        final StopCommand cmd = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false);
                        final Answer answer = _agentMgr.easySend(destHostId, cmd);
                        if (answer != null && answer instanceof StopAnswer) {
                            final StopAnswer stopAns = (StopAnswer) answer;
                            if (vm.getType() == VirtualMachineType.User) {
                                final String platform = stopAns.getPlatform();
                                if (platform != null) {
                                    final Map<String, String> vmmetadata = new HashMap<>();
                                    vmmetadata.put(vm.getInstanceName(), platform);
                                    syncVMMetaData(vmmetadata);
                                }
                            }
                        }
                        if (answer == null || !answer.getResult()) {
                            s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
                            _haMgr.scheduleStop(vm, destHostId, HaWork.HaWorkType.ForceStop);
                            throw new ExecutionException("Unable to stop this VM, " + vm.getUuid() + " so we are unable to retry the start operation");
                        }
                        throw new ExecutionException("Unable to start  VM:" + vm.getUuid() + " due to error in finalizeStart, not retrying");
                    }
                }
                s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails()));
                if (startAnswer != null && startAnswer.getContextParam("stopRetry") != null) {
                    break;
                }
            } catch (final OperationTimedoutException e) {
                s_logger.debug("Unable to send the start command to host " + dest.getHost() + " failed to start VM: " + vm.getUuid());
                if (e.isActive()) {
                    _haMgr.scheduleStop(vm, destHostId, HaWork.HaWorkType.CheckStop);
                }
                canRetry = false;
                throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e);
            } catch (final ResourceUnavailableException e) {
                s_logger.info("Unable to contact resource.", e);
                if (!avoids.add(e)) {
                    if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
                        throw e;
                    } else {
                        s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e);
                        throw e;
                    }
                }
            } catch (final InsufficientCapacityException e) {
                s_logger.info("Insufficient capacity ", e);
                if (!avoids.add(e)) {
                    if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
                        throw e;
                    } else {
                        s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e);
                    }
                }
            } catch (final ExecutionException | NoTransitionException e) {
                s_logger.error("Failed to start instance " + vm, e);
                throw new AgentUnavailableException("Unable to start instance due to " + e.getMessage(), destHostId, e);
            } finally {
                if (startedVm == null && canRetry) {
                    final Step prevStep = work.getStep();
                    _workDao.updateStep(work, Step.Release);
                    // If previous step was started/ing && we got a valid answer
                    if ((prevStep == Step.Started || prevStep == Step.Starting) && startAnswer != null && startAnswer.getResult()) {
                        // TODO check the response of cleanup
                        // and record it in DB for retry
                        cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false);
                    } else {
                        // if step is not starting/started, send cleanup command with force=true
                        cleanup(vmGuru, vmProfile, work, Event.OperationFailed, true);
                    }
                }
            }
        }
    } finally {
        if (startedVm == null) {
            if (canRetry) {
                try {
                    changeState(vm, Event.OperationFailed, null, work, Step.Done);
                } catch (final NoTransitionException e) {
                    throw new ConcurrentOperationException(e.getMessage());
                }
            }
        }
        if (planToDeploy != null) {
            planToDeploy.setAvoids(avoids);
        }
    }
    if (startedVm == null) {
        throw new CloudRuntimeException("Unable to start instance '" + vm.getHostName() + "' (" + vm.getUuid() + "), see management server log for details");
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) User(com.cloud.legacymodel.user.User) StoragePool(com.cloud.legacymodel.storage.StoragePool) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) StartCommand(com.cloud.legacymodel.communication.command.StartCommand) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Journal(com.cloud.utils.Journal) Step(com.cloud.vm.ItWorkVO.Step) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) VolumeVO(com.cloud.storage.VolumeVO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) Commands(com.cloud.agent.manager.Commands) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) StopAnswer(com.cloud.legacymodel.communication.answer.StopAnswer) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) VirtualMachineTemplate(com.cloud.legacymodel.storage.VirtualMachineTemplate) InsufficientServerCapacityException(com.cloud.legacymodel.exceptions.InsufficientServerCapacityException) GPUDeviceTO(com.cloud.legacymodel.to.GPUDeviceTO) CallContext(com.cloud.context.CallContext) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) HostVO(com.cloud.host.HostVO) 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) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ClusterDetailsVO(com.cloud.dc.ClusterDetailsVO)

Example 3 with StartAnswer

use of com.cloud.legacymodel.communication.answer.StartAnswer in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImplTest method testOrchestrateStart.

@Test
public void testOrchestrateStart() throws Exception {
    final DeployDestination deployDestination = new DeployDestination(null, _pod, _cluster, _host);
    final VirtualMachineGuru guru = mock(VirtualMachineGuru.class);
    final DiskTO[] disks = {};
    when(guru.finalizeStart(any(VirtualMachineProfile.class), anyLong(), any(Commands.class), any(ReservationContext.class))).thenReturn(true);
    _vmMgr._vmGurus = new HashMap<>();
    _vmMgr._vmGurus.put(VirtualMachineType.User, guru);
    final HypervisorGuru guruMock = mock(HypervisorGuru.class);
    final VirtualMachineTO vmTO = mock(VirtualMachineTO.class);
    when(vmTO.getDisks()).thenReturn(disks);
    when(guruMock.implement(any(VirtualMachineProfile.class))).thenReturn(vmTO);
    when(_hvGuruMgr.getGuru(any(HypervisorType.class))).thenReturn(guruMock);
    when(_dpMgr.planDeployment(any(VirtualMachineProfile.class), any(DeploymentPlan.class), any(DeploymentPlanner.ExcludeList.class), any(DeploymentPlanner.class))).thenReturn(deployDestination);
    doReturn(true).when(this._vmMgr).stateTransitTo(eq(_vmMock), eq(Event.StartRequested), eq(null), any(String.class));
    doReturn(true).when(this._vmMgr).changeState(eq(_vmMock), eq(Event.OperationRetry), anyLong(), any(ItWorkVO.class), eq(ItWorkVO.Step.Prepare));
    doReturn(true).when(this._vmMgr).changeState(eq(_vmMock), eq(Event.OperationSucceeded), anyLong(), any(ItWorkVO.class), eq(ItWorkVO.Step.Done));
    when(_work.getStep()).thenReturn(ItWorkVO.Step.Prepare);
    when(_agentMgr.send(anyLong(), any(Commands.class))).thenAnswer(invocation -> {
        Commands cmds = ((Commands) invocation.getArguments()[1]);
        StartAnswer startAnswer = new StartAnswer(cmds.getCommand(StartCommand.class));
        com.cloud.legacymodel.communication.answer.Answer[] answers = { startAnswer };
        cmds.setAnswers(answers);
        return answers;
    });
    _vmMgr.orchestrateStart("uuid", null, null, null);
}
Also used : StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) StartCommand(com.cloud.legacymodel.communication.command.StartCommand) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorType(com.cloud.model.enumeration.HypervisorType) MigrateWithStorageReceiveAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageReceiveAnswer) MigrateWithStorageAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageAnswer) MigrateWithStorageSendAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageSendAnswer) StopAnswer(com.cloud.legacymodel.communication.answer.StopAnswer) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) PrepareForMigrationAnswer(com.cloud.legacymodel.communication.answer.PrepareForMigrationAnswer) MigrateWithStorageCompleteAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageCompleteAnswer) ScaleVmAnswer(com.cloud.legacymodel.communication.answer.ScaleVmAnswer) CheckVirtualMachineAnswer(com.cloud.legacymodel.communication.answer.CheckVirtualMachineAnswer) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) DeployDestination(com.cloud.deploy.DeployDestination) Commands(com.cloud.agent.manager.Commands) DeploymentPlanner(com.cloud.deploy.DeploymentPlanner) DeploymentPlan(com.cloud.deploy.DeploymentPlan) DiskTO(com.cloud.legacymodel.to.DiskTO) Test(org.junit.Test)

Example 4 with StartAnswer

use of com.cloud.legacymodel.communication.answer.StartAnswer in project cosmic by MissionCriticalCloud.

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 to send back to the CS MS
    final Map<String, String> iqnToPath = 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() != VirtualMachineType.User) {
            citrixResourceBase.createPatchVbd(conn, vmName, vm);
        }
        // put cdrom at the first place in the list
        final List<DiskTO> disks = new ArrayList<>(vmSpec.getDisks().length);
        int index = 0;
        for (final DiskTO disk : vmSpec.getDisks()) {
            if (VolumeType.ISO.equals(disk.getType())) {
                disks.add(0, disk);
            } else {
                disks.add(index, disk);
            }
            index++;
        }
        for (final DiskTO disk : disks) {
            final VDI newVdi = citrixResourceBase.prepareManagedDisk(conn, disk, vmName);
            if (newVdi != null) {
                final String path = newVdi.getUuid(conn);
                iqnToPath.put(disk.getDetails().get(DiskTO.IQN), path);
            }
            citrixResourceBase.createVbd(conn, disk, vmName, vm, vmSpec.getBootloader(), newVdi);
        }
        for (final NicTO nic : vmSpec.getNics()) {
            citrixResourceBase.createVif(conn, vmName, vm, vmSpec, nic);
        }
        citrixResourceBase.startVM(conn, host, vm, vmName);
        state = VmPowerState.RUNNING;
        final StartAnswer startAnswer = new StartAnswer(command);
        startAnswer.setIqnToPath(iqnToPath);
        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.setIqnToPath(iqnToPath);
        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.legacymodel.communication.answer.StartAnswer) HashMap(java.util.HashMap) Connection(com.xensource.xenapi.Connection) ArrayList(java.util.ArrayList) Host(com.xensource.xenapi.Host) GPUDeviceTO(com.cloud.legacymodel.to.GPUDeviceTO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) VM(com.xensource.xenapi.VM) VDI(com.xensource.xenapi.VDI) VmPowerState(com.xensource.xenapi.Types.VmPowerState) DiskTO(com.cloud.legacymodel.to.DiskTO) NicTO(com.cloud.legacymodel.to.NicTO)

Example 5 with StartAnswer

use of com.cloud.legacymodel.communication.answer.StartAnswer in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method finalizeStart.

@Override
public boolean finalizeStart(final VirtualMachineProfile profile, final long hostId, final Commands cmds, final ReservationContext context) {
    final UserVmVO vm = _vmDao.findById(profile.getId());
    final Answer[] answersToCmds = cmds.getAnswers();
    if (answersToCmds == null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Returning from finalizeStart() since there are no answers to read");
        }
        return true;
    }
    final Answer startAnswer = cmds.getAnswer(StartAnswer.class);
    String returnedIp = null;
    String originalIp = null;
    if (startAnswer != null) {
        final StartAnswer startAns = (StartAnswer) startAnswer;
        final VirtualMachineTO vmTO = startAns.getVirtualMachine();
        for (final NicTO nicTO : vmTO.getNics()) {
            if (nicTO.getType() == TrafficType.Guest) {
                returnedIp = nicTO.getIp();
            }
        }
    }
    final List<NicVO> nics = _nicDao.listByVmId(vm.getId());
    NicVO guestNic = null;
    NetworkVO guestNetwork = null;
    for (final NicVO nic : nics) {
        final NetworkVO network = _networkDao.findById(nic.getNetworkId());
        final long isDefault = nic.isDefaultNic() ? 1 : 0;
        if (network.getTrafficType() == TrafficType.Guest) {
            originalIp = nic.getIPv4Address();
            guestNic = nic;
            guestNetwork = network;
            if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
                final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, "pvlan-nic");
                if (!setupVmForPvlan(true, hostId, nicProfile)) {
                    return false;
                }
            }
        }
    }
    boolean ipChanged = false;
    if (originalIp != null && !originalIp.equalsIgnoreCase(returnedIp)) {
        if (returnedIp != null && guestNic != null) {
            guestNic.setIPv4Address(returnedIp);
            ipChanged = true;
        }
    }
    if (returnedIp != null && !returnedIp.equalsIgnoreCase(originalIp)) {
        if (guestNic != null) {
            guestNic.setIPv4Address(returnedIp);
            ipChanged = true;
        }
    }
    // get system ip and create static nat rule for the vm
    try {
        _rulesMgr.getSystemIpAndEnableStaticNatForVm(profile.getVirtualMachine(), false);
    } catch (final Exception ex) {
        s_logger.warn("Failed to get system ip and enable static nat for the vm " + profile.getVirtualMachine() + " due to exception ", ex);
        return false;
    }
    final Answer answer = cmds.getAnswer("restoreVMSnapshot");
    if (answer != null && answer instanceof RestoreVMSnapshotAnswer) {
        final RestoreVMSnapshotAnswer restoreVMSnapshotAnswer = (RestoreVMSnapshotAnswer) answer;
        if (!restoreVMSnapshotAnswer.getResult()) {
            s_logger.warn("Unable to restore the vm snapshot from image file to the VM: " + restoreVMSnapshotAnswer.getDetails());
        }
    }
    return true;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) RestoreVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RestoreVMSnapshotAnswer) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) 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) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) CloudException(com.cloud.legacymodel.exceptions.CloudException) 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) ManagementServerException(com.cloud.legacymodel.exceptions.ManagementServerException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) GetVmDiskStatsAnswer(com.cloud.legacymodel.communication.answer.GetVmDiskStatsAnswer) GetVmStatsAnswer(com.cloud.legacymodel.communication.answer.GetVmStatsAnswer) RestoreVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RestoreVMSnapshotAnswer) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) Answer(com.cloud.legacymodel.communication.answer.Answer) NicTO(com.cloud.legacymodel.to.NicTO)

Aggregations

StartAnswer (com.cloud.legacymodel.communication.answer.StartAnswer)5 VirtualMachineTO (com.cloud.legacymodel.to.VirtualMachineTO)5 NicTO (com.cloud.legacymodel.to.NicTO)3 Commands (com.cloud.agent.manager.Commands)2 DeployDestination (com.cloud.deploy.DeployDestination)2 HypervisorGuru (com.cloud.hypervisor.HypervisorGuru)2 Answer (com.cloud.legacymodel.communication.answer.Answer)2 CheckVirtualMachineAnswer (com.cloud.legacymodel.communication.answer.CheckVirtualMachineAnswer)2 RestoreVMSnapshotAnswer (com.cloud.legacymodel.communication.answer.RestoreVMSnapshotAnswer)2 StopAnswer (com.cloud.legacymodel.communication.answer.StopAnswer)2 StartCommand (com.cloud.legacymodel.communication.command.StartCommand)2 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)2 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)2 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)2 ExecutionException (com.cloud.legacymodel.exceptions.ExecutionException)2 DiskTO (com.cloud.legacymodel.to.DiskTO)2 GPUDeviceTO (com.cloud.legacymodel.to.GPUDeviceTO)2 HashMap (java.util.HashMap)2 KvmStoragePoolManager (com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager)1 LibvirtVmDef (com.cloud.agent.resource.kvm.xml.LibvirtVmDef)1