Search in sources :

Example 1 with VirtualMachineTO

use of com.cloud.legacymodel.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testcreateVmFromSpecWithTopology6.

/**
 * This test verifies that CPU topology is properly set for hex-core
 */
@Test
public void testcreateVmFromSpecWithTopology6() {
    final int id = this._random.nextInt(65534);
    final String name = "test-instance-1";
    final int cpus = 12;
    final int minRam = 256 * 1024;
    final int maxRam = 512 * 1024;
    final String os = "Ubuntu";
    final String vncPassword = "mySuperSecretPassword";
    final LibvirtComputingResource lcr = new LibvirtComputingResource();
    final VirtualMachineTO to = new VirtualMachineTO(id, name, VirtualMachineType.User, cpus, minRam, maxRam, BootloaderType.HVM, os, false, false, vncPassword);
    to.setUuid("b0f0a72d-7efb-3cad-a8ff-70ebf30b3af9");
    final LibvirtVmDef vm = lcr.createVmFromSpec(to);
    vm.setHvsType(this._hyperVisorType);
    verifyVm(to, vm);
}
Also used : LibvirtVmDef(com.cloud.agent.resource.kvm.xml.LibvirtVmDef) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) Test(org.junit.Test)

Example 2 with VirtualMachineTO

use of com.cloud.legacymodel.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testPrepareForMigrationCommandInternalErrorException.

@Test
public void testPrepareForMigrationCommandInternalErrorException() {
    final Connect conn = Mockito.mock(Connect.class);
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
    final KvmStoragePoolManager storagePoolManager = Mockito.mock(KvmStoragePoolManager.class);
    final NicTO nicTO = Mockito.mock(NicTO.class);
    final DiskTO volume = Mockito.mock(DiskTO.class);
    final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
    when(this.libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    try {
        when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    when(vm.getNics()).thenReturn(new NicTO[] { nicTO });
    when(nicTO.getType()).thenReturn(TrafficType.Guest);
    when(this.libvirtComputingResource.getVifDriver(nicTO.getType())).thenThrow(InternalErrorException.class);
    when(this.libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
    try {
        when(this.libvirtComputingResource.getVolumePath(conn, volume)).thenReturn("/path");
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    } catch (final URISyntaxException e) {
        fail(e.getMessage());
    }
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(this.libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
    try {
        verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    verify(this.libvirtComputingResource, times(1)).getStoragePoolMgr();
    verify(vm, times(1)).getNics();
}
Also used : Answer(com.cloud.legacymodel.communication.answer.Answer) CheckRouterAnswer(com.cloud.legacymodel.communication.answer.CheckRouterAnswer) AttachAnswer(com.cloud.legacymodel.communication.answer.AttachAnswer) LibvirtRequestWrapper(com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper) LibvirtException(org.libvirt.LibvirtException) PrepareForMigrationCommand(com.cloud.legacymodel.communication.command.PrepareForMigrationCommand) Connect(org.libvirt.Connect) KvmStoragePoolManager(com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager) URISyntaxException(java.net.URISyntaxException) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) LibvirtUtilitiesHelper(com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper) NicTO(com.cloud.legacymodel.to.NicTO) DiskTO(com.cloud.legacymodel.to.DiskTO) Test(org.junit.Test)

Example 3 with VirtualMachineTO

use of com.cloud.legacymodel.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testPrepareForMigrationCommandLibvirtException.

@Test
public void testPrepareForMigrationCommandLibvirtException() {
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
    final KvmStoragePoolManager storagePoolManager = Mockito.mock(KvmStoragePoolManager.class);
    final NicTO nicTO = Mockito.mock(NicTO.class);
    final VifDriver vifDriver = Mockito.mock(VifDriver.class);
    final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
    when(this.libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    try {
        when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenThrow(LibvirtException.class);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    when(vm.getNics()).thenReturn(new NicTO[] { nicTO });
    when(nicTO.getType()).thenReturn(TrafficType.Guest);
    when(this.libvirtComputingResource.getVifDriver(nicTO.getType())).thenReturn(vifDriver);
    when(this.libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(this.libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
    try {
        verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    verify(this.libvirtComputingResource, times(1)).getStoragePoolMgr();
    verify(vm, times(1)).getNics();
}
Also used : Answer(com.cloud.legacymodel.communication.answer.Answer) CheckRouterAnswer(com.cloud.legacymodel.communication.answer.CheckRouterAnswer) AttachAnswer(com.cloud.legacymodel.communication.answer.AttachAnswer) LibvirtRequestWrapper(com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper) LibvirtException(org.libvirt.LibvirtException) PrepareForMigrationCommand(com.cloud.legacymodel.communication.command.PrepareForMigrationCommand) KvmStoragePoolManager(com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) VifDriver(com.cloud.agent.resource.kvm.vif.VifDriver) LibvirtUtilitiesHelper(com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper) NicTO(com.cloud.legacymodel.to.NicTO) Test(org.junit.Test)

Example 4 with VirtualMachineTO

use of com.cloud.legacymodel.to.VirtualMachineTO 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 5 with VirtualMachineTO

use of com.cloud.legacymodel.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateMigrateWithStorage.

private void orchestrateMigrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map<Long, Long> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final HostVO srcHost = _hostDao.findById(srcHostId);
    final HostVO destHost = _hostDao.findById(destHostId);
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    final Zone zone = _zoneRepository.findById(destHost.getDataCenterId()).orElse(null);
    final HostPodVO pod = _podDao.findById(destHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
    final DeployDestination destination = new DeployDestination(zone, pod, cluster, destHost);
    // Create a map of which volume should go in which storage pool.
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    final Map<Volume, StoragePool> volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
    // a vm and not migrating a vm with storage.
    if (volumeToPoolMap == null || volumeToPoolMap.isEmpty()) {
        throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost + " doesn't involve migrating the volumes.");
    }
    AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
    if (VirtualMachineType.DomainRouter.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
    } else if (VirtualMachineType.ConsoleProxy.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
    }
    _networkMgr.prepareNicForMigration(profile, destination);
    volumeMgr.prepareForMigration(profile, destination);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
    final VirtualMachineTO to = hvGuru.implement(profile);
    ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
    work.setStep(Step.Prepare);
    work.setResourceType(ItWorkVO.ResourceType.Host);
    work.setResourceId(destHostId);
    work = _workDao.persist(work);
    // Put the vm in migrating state.
    vm.setLastHostId(srcHostId);
    moveVmToMigratingState(vm, destHostId, work);
    boolean migrated = false;
    try {
        // config drive: Detach the config drive at source host
        // After migration successful attach the config drive in destination host
        // On migration failure VM will be stopped, So configIso will be deleted
        final Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
        List<String[]> vmData = null;
        if (defaultNic != null) {
            final UserVmVO userVm = _userVmDao.findById(vm.getId());
            final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
            vm.setDetails(details);
            final Network network = _networkModel.getNetwork(defaultNic.getNetworkId());
            if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
                final String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
                final String zoneName = _dcDao.findById(vm.getDataCenterId()).getName();
                final boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
                vmData = _networkModel.generateVmData(userVm.getUserData(), serviceOffering, zoneName, vm.getInstanceName(), vm.getId(), (String) profile.getParameter(VirtualMachineProfile.Param.VmSshPubKey), (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows, network);
                final String vmName = vm.getInstanceName();
                final String configDriveIsoRootFolder = "/tmp";
                final String isoFile = configDriveIsoRootFolder + "/" + vmName + "/configDrive/" + vmName + ".iso";
                profile.setVmData(vmData);
                profile.setConfigDriveLabel(VmConfigDriveLabel.value());
                profile.setConfigDriveIsoRootFolder(configDriveIsoRootFolder);
                profile.setConfigDriveIsoFile(isoFile);
                // At source host detach the config drive iso.
                final AttachOrDettachConfigDriveCommand dettachCommand = new AttachOrDettachConfigDriveCommand(vm.getInstanceName(), vmData, VmConfigDriveLabel.value(), false);
                try {
                    _agentMgr.send(srcHost.getId(), dettachCommand);
                    s_logger.debug("Deleted config drive ISO for  vm " + vm.getInstanceName() + " In host " + srcHost);
                } catch (final OperationTimedoutException e) {
                    s_logger.debug("TIme out occured while exeuting command AttachOrDettachConfigDrive " + e.getMessage());
                }
            }
        }
        // Migrate the vm and its volume.
        volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPoolMap);
        // Put the vm back to running state.
        moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
        try {
            if (!checkVmOnHost(vm, destHostId)) {
                s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
                try {
                    _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
                } catch (final AgentUnavailableException e) {
                    s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
                }
                cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
                throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm);
            }
        } catch (final OperationTimedoutException e) {
            s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
        }
        migrated = true;
    } finally {
        if (!migrated) {
            s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm);
            _alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + zone.getName() + " and pod " + zone.getName(), "Migrate Command failed.  Please check logs.");
            try {
                _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
                stateTransitTo(vm, Event.OperationFailed, srcHostId);
            } catch (final AgentUnavailableException e) {
                s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
            } catch (final NoTransitionException e) {
                s_logger.error("Error while transitioning vm from migrating to running state.", e);
            }
        }
        work.setStep(Step.Done);
        _workDao.update(work.getId(), work);
    }
}
Also used : AlertManager(com.cloud.alert.AlertManager) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) StoragePool(com.cloud.legacymodel.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) Commands(com.cloud.agent.manager.Commands) TimeZone(java.util.TimeZone) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.legacymodel.dc.Cluster) Nic(com.cloud.legacymodel.network.Nic) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.legacymodel.communication.command.AttachOrDettachConfigDriveCommand) Volume(com.cloud.legacymodel.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException)

Aggregations

VirtualMachineTO (com.cloud.legacymodel.to.VirtualMachineTO)51 NicTO (com.cloud.legacymodel.to.NicTO)28 Test (org.junit.Test)28 Answer (com.cloud.legacymodel.communication.answer.Answer)27 AttachAnswer (com.cloud.legacymodel.communication.answer.AttachAnswer)17 LibvirtException (org.libvirt.LibvirtException)16 KvmStoragePoolManager (com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager)14 Connection (com.xensource.xenapi.Connection)14 Connect (org.libvirt.Connect)14 LibvirtRequestWrapper (com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper)13 LibvirtUtilitiesHelper (com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper)13 CheckRouterAnswer (com.cloud.legacymodel.communication.answer.CheckRouterAnswer)13 LibvirtVmDef (com.cloud.agent.resource.kvm.xml.LibvirtVmDef)12 Host (com.cloud.legacymodel.dc.Host)12 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)12 URISyntaxException (java.net.URISyntaxException)11 StartCommand (com.cloud.legacymodel.communication.command.StartCommand)10 HashMap (java.util.HashMap)10 InternalErrorException (com.cloud.legacymodel.exceptions.InternalErrorException)9 DiskTO (com.cloud.legacymodel.to.DiskTO)9