Search in sources :

Example 6 with DiskDef

use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef in project cloudstack by apache.

the class LibvirtComputingResourceTest method testMigrateCommand.

@Test
public void testMigrateCommand() {
    final Connect conn = Mockito.mock(Connect.class);
    final Connect dconn = Mockito.mock(Connect.class);
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final String vmName = "Test";
    final String destIp = "127.0.0.100";
    final boolean isWindows = false;
    final VirtualMachineTO vmTO = Mockito.mock(VirtualMachineTO.class);
    final boolean executeInSequence = false;
    final MigrateCommand command = new MigrateCommand(vmName, destIp, isWindows, vmTO, executeInSequence);
    when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    try {
        when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
        when(libvirtUtilitiesHelper.retrieveQemuConnection("qemu+tcp://" + command.getDestinationIp() + "/system")).thenReturn(dconn);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
    final List<InterfaceDef> ifaces = new ArrayList<InterfaceDef>();
    ifaces.add(interfaceDef);
    when(libvirtComputingResource.getInterfaces(conn, vmName)).thenReturn(ifaces);
    final DiskDef diskDef = Mockito.mock(DiskDef.class);
    final List<DiskDef> disks = new ArrayList<DiskDef>();
    disks.add(diskDef);
    when(libvirtComputingResource.getDisks(conn, vmName)).thenReturn(disks);
    final Domain dm = Mockito.mock(Domain.class);
    try {
        when(conn.domainLookupByName(vmName)).thenReturn(dm);
        when(libvirtComputingResource.getPrivateIp()).thenReturn("127.0.0.1");
        when(dm.getXMLDesc(8)).thenReturn("<domain type='kvm' id='3'>" + "  <devices>" + "    <graphics type='vnc' port='5900' autoport='yes' listen='10.10.10.1'>" + "      <listen type='address' address='10.10.10.1'/>" + "    </graphics>" + "  </devices>" + "</domain>");
        when(dm.getXMLDesc(1)).thenReturn("<domain type='kvm' id='3'>" + "  <devices>" + "    <graphics type='vnc' port='5900' autoport='yes' listen='10.10.10.1'>" + "      <listen type='address' address='10.10.10.1'/>" + "    </graphics>" + "  </devices>" + "</domain>");
        when(dm.isPersistent()).thenReturn(1);
        doNothing().when(dm).undefine();
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, libvirtComputingResource);
    assertTrue(answer.getResult());
    verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
    try {
        verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
        verify(libvirtUtilitiesHelper, times(1)).retrieveQemuConnection("qemu+tcp://" + command.getDestinationIp() + "/system");
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    verify(libvirtComputingResource, times(1)).getInterfaces(conn, vmName);
    verify(libvirtComputingResource, times(1)).getDisks(conn, vmName);
    try {
        verify(conn, times(1)).domainLookupByName(vmName);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    try {
        verify(dm, times(1)).getXMLDesc(8);
    } catch (final Throwable t) {
        try {
            verify(dm, times(1)).getXMLDesc(1);
        } catch (final LibvirtException e) {
            fail(e.getMessage());
        }
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) ArrayList(java.util.ArrayList) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) LibvirtException(org.libvirt.LibvirtException) SAXException(org.xml.sax.SAXException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LibvirtUtilitiesHelper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper) MigrateCommand(com.cloud.agent.api.MigrateCommand) InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) Answer(com.cloud.agent.api.Answer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef) LibvirtRequestWrapper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper) Domain(org.libvirt.Domain) Test(org.junit.Test)

Example 7 with DiskDef

use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef in project cloudstack by apache.

the class LibvirtComputingResourceTest method testGetVmStat.

@Test
public void testGetVmStat() throws LibvirtException {
    final Connect connect = Mockito.mock(Connect.class);
    final Domain domain = Mockito.mock(Domain.class);
    final DomainInfo domainInfo = new DomainInfo();
    final MemoryStatistic[] domainMem = new MemoryStatistic[2];
    domainMem[0] = Mockito.mock(MemoryStatistic.class);
    Mockito.when(domain.getInfo()).thenReturn(domainInfo);
    Mockito.when(domain.memoryStats(2)).thenReturn(domainMem);
    Mockito.when(connect.domainLookupByName(VMNAME)).thenReturn(domain);
    final NodeInfo nodeInfo = new NodeInfo();
    nodeInfo.cpus = 8;
    nodeInfo.memory = 8 * 1024 * 1024;
    nodeInfo.sockets = 2;
    nodeInfo.threads = 2;
    nodeInfo.model = "Foo processor";
    Mockito.when(connect.nodeInfo()).thenReturn(nodeInfo);
    // this is testing the interface stats, returns an increasing number of sent and received bytes
    Mockito.when(domain.interfaceStats(Matchers.anyString())).thenAnswer(new org.mockito.stubbing.Answer<DomainInterfaceStats>() {

        // increment with less than a KB, so this should be less than 1 KB
        static final int increment = 1000;

        int rxBytes = 1000;

        int txBytes = 1000;

        @Override
        public DomainInterfaceStats answer(final InvocationOnMock invocation) throws Throwable {
            final DomainInterfaceStats domainInterfaceStats = new DomainInterfaceStats();
            domainInterfaceStats.rx_bytes = rxBytes += increment;
            domainInterfaceStats.tx_bytes = txBytes += increment;
            return domainInterfaceStats;
        }
    });
    Mockito.when(domain.blockStats(Matchers.anyString())).thenAnswer(new org.mockito.stubbing.Answer<DomainBlockStats>() {

        // a little less than a KB
        static final int increment = 1000;

        int rdBytes = 0;

        int wrBytes = 1024;

        @Override
        public DomainBlockStats answer(final InvocationOnMock invocation) throws Throwable {
            final DomainBlockStats domainBlockStats = new DomainBlockStats();
            domainBlockStats.rd_bytes = rdBytes += increment;
            domainBlockStats.wr_bytes = wrBytes += increment;
            return domainBlockStats;
        }
    });
    final LibvirtComputingResource libvirtComputingResource = new LibvirtComputingResource() {

        @Override
        public List<InterfaceDef> getInterfaces(final Connect conn, final String vmName) {
            final InterfaceDef interfaceDef = new InterfaceDef();
            return Arrays.asList(interfaceDef);
        }

        @Override
        public List<DiskDef> getDisks(final Connect conn, final String vmName) {
            final DiskDef diskDef = new DiskDef();
            return Arrays.asList(diskDef);
        }
    };
    libvirtComputingResource.getVmStat(connect, VMNAME);
    final VmStatsEntry vmStat = libvirtComputingResource.getVmStat(connect, VMNAME);
    // network traffic as generated by the logic above, must be greater than zero
    Assert.assertTrue(vmStat.getNetworkReadKBs() > 0);
    Assert.assertTrue(vmStat.getNetworkWriteKBs() > 0);
    // IO traffic as generated by the logic above, must be greater than zero
    Assert.assertTrue(vmStat.getDiskReadKBs() > 0);
    Assert.assertTrue(vmStat.getDiskWriteKBs() > 0);
    // Memory limit of VM must be greater than zero
    Assert.assertTrue(vmStat.getIntFreeMemoryKBs() >= 0);
    Assert.assertTrue(vmStat.getMemoryKBs() >= 0);
    Assert.assertTrue(vmStat.getTargetMemoryKBs() >= vmStat.getMemoryKBs());
}
Also used : DomainInterfaceStats(org.libvirt.DomainInterfaceStats) Connect(org.libvirt.Connect) VmStatsEntry(com.cloud.agent.api.VmStatsEntry) MemoryStatistic(org.libvirt.MemoryStatistic) InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef) NodeInfo(org.libvirt.NodeInfo) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DomainBlockStats(org.libvirt.DomainBlockStats) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain) Test(org.junit.Test)

Example 8 with DiskDef

use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef in project cloudstack by apache.

the class KVMStorageProcessor method attachOrDetachDisk.

protected synchronized String attachOrDetachDisk(final Connect conn, final boolean attach, final String vmName, final KVMPhysicalDisk attachingDisk, final int devId, final String serial, final Long bytesReadRate, final Long bytesWriteRate, final Long iopsReadRate, final Long iopsWriteRate) throws LibvirtException, InternalErrorException {
    List<DiskDef> disks = null;
    Domain dm = null;
    DiskDef diskdef = null;
    final KVMStoragePool attachingPool = attachingDisk.getPool();
    try {
        dm = conn.domainLookupByName(vmName);
        final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
        final String domXml = dm.getXMLDesc(0);
        parser.parseDomainXML(domXml);
        disks = parser.getDisks();
        if (!attach) {
            if (attachingPool.getType() == StoragePoolType.RBD) {
                if (resource.getHypervisorType() == Hypervisor.HypervisorType.LXC) {
                    final String device = resource.mapRbdDevice(attachingDisk);
                    if (device != null) {
                        s_logger.debug("RBD device on host is: " + device);
                        attachingDisk.setPath(device);
                    }
                }
            }
            for (final DiskDef disk : disks) {
                final String file = disk.getDiskPath();
                if (file != null && file.equalsIgnoreCase(attachingDisk.getPath())) {
                    diskdef = disk;
                    break;
                }
            }
            if (diskdef == null) {
                throw new InternalErrorException("disk: " + attachingDisk.getPath() + " is not attached before");
            }
        } else {
            DiskDef.DiskBus busT = DiskDef.DiskBus.VIRTIO;
            for (final DiskDef disk : disks) {
                if (disk.getDeviceType() == DeviceType.DISK) {
                    if (disk.getBusType() == DiskDef.DiskBus.SCSI) {
                        busT = DiskDef.DiskBus.SCSI;
                    }
                    break;
                }
            }
            diskdef = new DiskDef();
            if (busT == DiskDef.DiskBus.SCSI) {
                diskdef.setQemuDriver(true);
                diskdef.setDiscard(DiscardType.UNMAP);
            }
            diskdef.setSerial(serial);
            if (attachingPool.getType() == StoragePoolType.RBD) {
                if (resource.getHypervisorType() == Hypervisor.HypervisorType.LXC) {
                    // For LXC, map image to host and then attach to Vm
                    final String device = resource.mapRbdDevice(attachingDisk);
                    if (device != null) {
                        s_logger.debug("RBD device on host is: " + device);
                        diskdef.defBlockBasedDisk(device, devId, busT);
                    } else {
                        throw new InternalErrorException("Error while mapping disk " + attachingDisk.getPath() + " on host");
                    }
                } else {
                    diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), attachingPool.getAuthUserName(), attachingPool.getUuid(), devId, busT, DiskProtocol.RBD, DiskDef.DiskFmtType.RAW);
                }
            } else if (attachingPool.getType() == StoragePoolType.Gluster) {
                final String mountpoint = attachingPool.getLocalPath();
                final String path = attachingDisk.getPath();
                final String glusterVolume = attachingPool.getSourceDir().replace("/", "");
                diskdef.defNetworkBasedDisk(glusterVolume + path.replace(mountpoint, ""), attachingPool.getSourceHost(), attachingPool.getSourcePort(), null, null, devId, busT, DiskProtocol.GLUSTER, DiskDef.DiskFmtType.QCOW2);
            } else if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
                diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, busT, DiskDef.DiskFmtType.QCOW2);
            } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
                diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, busT);
            }
            if ((bytesReadRate != null) && (bytesReadRate > 0)) {
                diskdef.setBytesReadRate(bytesReadRate);
            }
            if ((bytesWriteRate != null) && (bytesWriteRate > 0)) {
                diskdef.setBytesWriteRate(bytesWriteRate);
            }
            if ((iopsReadRate != null) && (iopsReadRate > 0)) {
                diskdef.setIopsReadRate(iopsReadRate);
            }
            if ((iopsWriteRate != null) && (iopsWriteRate > 0)) {
                diskdef.setIopsWriteRate(iopsWriteRate);
            }
        }
        final String xml = diskdef.toString();
        return attachOrDetachDevice(conn, attach, vmName, xml);
    } finally {
        if (dm != null) {
            dm.free();
        }
    }
}
Also used : DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef) LibvirtDomainXMLParser(com.cloud.hypervisor.kvm.resource.LibvirtDomainXMLParser) InternalErrorException(com.cloud.exception.InternalErrorException) Domain(org.libvirt.Domain)

Example 9 with DiskDef

use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef in project cloudstack by apache.

the class KVMStorageProcessor method attachOrDetachISO.

protected synchronized String attachOrDetachISO(final Connect conn, final String vmName, String isoPath, final boolean isAttach) throws LibvirtException, URISyntaxException, InternalErrorException {
    String isoXml = null;
    if (isoPath != null && isAttach) {
        final int index = isoPath.lastIndexOf("/");
        final String path = isoPath.substring(0, index);
        final String name = isoPath.substring(index + 1);
        final KVMStoragePool secondaryPool = storagePoolMgr.getStoragePoolByURI(path);
        final KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
        isoPath = isoVol.getPath();
        final DiskDef iso = new DiskDef();
        iso.defISODisk(isoPath);
        isoXml = iso.toString();
    } else {
        final DiskDef iso = new DiskDef();
        iso.defISODisk(null);
        isoXml = iso.toString();
    }
    final List<DiskDef> disks = resource.getDisks(conn, vmName);
    final String result = attachOrDetachDevice(conn, true, vmName, isoXml);
    if (result == null && !isAttach) {
        for (final DiskDef disk : disks) {
            if (disk.getDeviceType() == DiskDef.DeviceType.CDROM) {
                resource.cleanupDisk(disk);
            }
        }
    }
    return result;
}
Also used : DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef)

Example 10 with DiskDef

use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef in project cloudstack by apache.

the class LibvirtStopCommandWrapper method execute.

@Override
public Answer execute(final StopCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final String vmName = command.getVmName();
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
    if (command.checkBeforeCleanup()) {
        try {
            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
            final Domain vm = conn.domainLookupByName(command.getVmName());
            if (vm != null && vm.getInfo().state == DomainState.VIR_DOMAIN_RUNNING) {
                return new StopAnswer(command, "vm is still running on host", false);
            }
        } catch (final Exception e) {
            s_logger.debug("Failed to get vm status in case of checkboforecleanup is true", e);
        }
    }
    File pemFile = new File(LibvirtComputingResource.SSHPRVKEYPATH);
    try {
        if (vmName.startsWith("s-") || vmName.startsWith("v-")) {
            //move the command line file to backup.
            s_logger.debug("backing up the cmdline");
            try {
                Pair<Boolean, String> ret = SshHelper.sshExecute(command.getControlIp(), 3922, "root", pemFile, null, "mv -f " + CMDLINE_PATH + " " + CMDLINE_BACKUP_PATH);
                if (!ret.first()) {
                    s_logger.debug("Failed to backup cmdline file due to " + ret.second());
                }
            } catch (Exception e) {
                s_logger.debug("Failed to backup cmdline file due to " + e.getMessage());
            }
        }
        final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
        final List<DiskDef> disks = libvirtComputingResource.getDisks(conn, vmName);
        final List<InterfaceDef> ifaces = libvirtComputingResource.getInterfaces(conn, vmName);
        libvirtComputingResource.destroyNetworkRulesForVM(conn, vmName);
        final String result = libvirtComputingResource.stopVM(conn, vmName);
        if (result == null) {
            for (final DiskDef disk : disks) {
                libvirtComputingResource.cleanupDisk(disk);
            }
            for (final InterfaceDef iface : ifaces) {
                // each interface at this point, so inform all vif drivers
                for (final VifDriver vifDriver : libvirtComputingResource.getAllVifDrivers()) {
                    vifDriver.unplug(iface);
                }
            }
        }
        return new StopAnswer(command, result, true);
    } catch (final LibvirtException e) {
        s_logger.debug("unable to stop VM:" + vmName + " due to" + e.getMessage());
        try {
            if (vmName.startsWith("s-") || vmName.startsWith("v-"))
                s_logger.debug("restoring cmdline file from backup");
            Pair<Boolean, String> ret = SshHelper.sshExecute(command.getControlIp(), 3922, "root", pemFile, null, "mv " + CMDLINE_BACKUP_PATH + " " + CMDLINE_PATH);
            if (!ret.first()) {
                s_logger.debug("unable to restore cmdline due to " + ret.second());
            }
        } catch (final Exception ex) {
            s_logger.debug("unable to restore cmdline due to:" + ex.getMessage());
        }
        return new StopAnswer(command, e.getMessage(), false);
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) LibvirtException(org.libvirt.LibvirtException) VifDriver(com.cloud.hypervisor.kvm.resource.VifDriver) InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef) Domain(org.libvirt.Domain) StopAnswer(com.cloud.agent.api.StopAnswer) File(java.io.File) Pair(com.cloud.utils.Pair)

Aggregations

DiskDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef)15 Domain (org.libvirt.Domain)9 InterfaceDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef)7 InternalErrorException (com.cloud.exception.InternalErrorException)4 Connect (org.libvirt.Connect)4 LibvirtException (org.libvirt.LibvirtException)4 KVMStoragePool (com.cloud.hypervisor.kvm.storage.KVMStoragePool)3 File (java.io.File)3 IOException (java.io.IOException)3 DomainBlockStats (org.libvirt.DomainBlockStats)3 VmStatsEntry (com.cloud.agent.api.VmStatsEntry)2 ChannelDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ChannelDef)2 RngDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.RngDef)2 VifDriver (com.cloud.hypervisor.kvm.resource.VifDriver)2 KVMPhysicalDisk (com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 ArrayList (java.util.ArrayList)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 Test (org.junit.Test)2 DomainInfo (org.libvirt.DomainInfo)2