Search in sources :

Example 31 with Domain

use of org.libvirt.Domain in project cloudstack by apache.

the class LibvirtStartCommandWrapper method getFreeMemory.

private Long getFreeMemory(final Connect conn, final LibvirtComputingResource libvirtComputingResource) {
    try {
        long allocatedMem = 0;
        int[] ids = conn.listDomains();
        for (int id : ids) {
            Domain dm = conn.domainLookupByID(id);
            allocatedMem += dm.getMaxMemory() * 1024L;
            s_logger.debug("vm: " + dm.getName() + " mem: " + dm.getMaxMemory() * 1024L);
        }
        Long remainingMem = libvirtComputingResource.getTotalMemory() - allocatedMem;
        s_logger.debug("remaining mem" + remainingMem);
        return remainingMem;
    } catch (Exception e) {
        s_logger.debug("failed to get free memory", e);
        return null;
    }
}
Also used : Domain(org.libvirt.Domain) URISyntaxException(java.net.URISyntaxException) InternalErrorException(com.cloud.exception.InternalErrorException) LibvirtException(org.libvirt.LibvirtException)

Example 32 with Domain

use of org.libvirt.Domain 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)

Example 33 with Domain

use of org.libvirt.Domain in project cloudstack by apache.

the class LibvirtUnPlugNicCommandWrapper method execute.

@Override
public Answer execute(final UnPlugNicCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final NicTO nic = command.getNic();
    final String vmName = command.getVmName();
    Domain vm = null;
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
        vm = libvirtComputingResource.getDomain(conn, vmName);
        final List<InterfaceDef> pluggedNics = libvirtComputingResource.getInterfaces(conn, vmName);
        for (final InterfaceDef pluggedNic : pluggedNics) {
            if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) {
                vm.detachDevice(pluggedNic.toString());
                // each interface at this point, so inform all vif drivers
                for (final VifDriver vifDriver : libvirtComputingResource.getAllVifDrivers()) {
                    vifDriver.unplug(pluggedNic);
                }
                return new UnPlugNicAnswer(command, true, "success");
            }
        }
        return new UnPlugNicAnswer(command, true, "success");
    } catch (final LibvirtException e) {
        final String msg = " Unplug Nic failed due to " + e.toString();
        s_logger.warn(msg, e);
        return new UnPlugNicAnswer(command, false, msg);
    } finally {
        if (vm != null) {
            try {
                vm.free();
            } catch (final LibvirtException l) {
                s_logger.trace("Ignoring libvirt error.", l);
            }
        }
    }
}
Also used : InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) LibvirtException(org.libvirt.LibvirtException) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) Connect(org.libvirt.Connect) Domain(org.libvirt.Domain) VifDriver(com.cloud.hypervisor.kvm.resource.VifDriver) NicTO(com.cloud.agent.api.to.NicTO)

Example 34 with Domain

use of org.libvirt.Domain in project cloudstack by apache.

the class LibvirtPlugNicCommandWrapper method execute.

@Override
public Answer execute(final PlugNicCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final NicTO nic = command.getNic();
    final String vmName = command.getVmName();
    Domain vm = null;
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
        vm = libvirtComputingResource.getDomain(conn, vmName);
        final List<InterfaceDef> pluggedNics = libvirtComputingResource.getInterfaces(conn, vmName);
        Integer nicnum = 0;
        for (final InterfaceDef pluggedNic : pluggedNics) {
            if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) {
                s_logger.debug("found existing nic for mac " + pluggedNic.getMacAddress() + " at index " + nicnum);
                return new PlugNicAnswer(command, true, "success");
            }
            nicnum++;
        }
        final VifDriver vifDriver = libvirtComputingResource.getVifDriver(nic.getType());
        final InterfaceDef interfaceDef = vifDriver.plug(nic, "Other PV", "");
        vm.attachDevice(interfaceDef.toString());
        return new PlugNicAnswer(command, true, "success");
    } catch (final LibvirtException e) {
        final String msg = " Plug Nic failed due to " + e.toString();
        s_logger.warn(msg, e);
        return new PlugNicAnswer(command, false, msg);
    } catch (final InternalErrorException e) {
        final String msg = " Plug Nic failed due to " + e.toString();
        s_logger.warn(msg, e);
        return new PlugNicAnswer(command, false, msg);
    } finally {
        if (vm != null) {
            try {
                vm.free();
            } catch (final LibvirtException l) {
                s_logger.trace("Ignoring libvirt error.", l);
            }
        }
    }
}
Also used : InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) InternalErrorException(com.cloud.exception.InternalErrorException) Domain(org.libvirt.Domain) VifDriver(com.cloud.hypervisor.kvm.resource.VifDriver) NicTO(com.cloud.agent.api.to.NicTO)

Example 35 with Domain

use of org.libvirt.Domain 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)

Aggregations

Domain (org.libvirt.Domain)67 LibvirtException (org.libvirt.LibvirtException)54 Connect (org.libvirt.Connect)30 InternalErrorException (com.cloud.exception.InternalErrorException)24 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)17 URISyntaxException (java.net.URISyntaxException)17 IOException (java.io.IOException)16 ConfigurationException (javax.naming.ConfigurationException)16 InterfaceDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef)15 FileNotFoundException (java.io.FileNotFoundException)14 Test (org.junit.Test)14 DomainInfo (org.libvirt.DomainInfo)14 ExecutionException (java.util.concurrent.ExecutionException)13 Answer (com.cloud.agent.api.Answer)11 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)11 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)11 LibvirtUtilitiesHelper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper)11 AttachAnswer (org.apache.cloudstack.storage.command.AttachAnswer)11 NicTO (com.cloud.agent.api.to.NicTO)10 ArrayList (java.util.ArrayList)10