Search in sources :

Example 61 with Domain

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

the class LibvirtComputingResource method getHostVmStateReport.

private HashMap<String, HostVmStateReportEntry> getHostVmStateReport(final Connect conn) {
    final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>();
    String[] vms = null;
    int[] ids = null;
    try {
        ids = conn.listDomains();
    } catch (final LibvirtException e) {
        s_logger.warn("Unable to listDomains", e);
        return null;
    }
    try {
        vms = conn.listDefinedDomains();
    } catch (final LibvirtException e) {
        s_logger.warn("Unable to listDomains", e);
        return null;
    }
    Domain dm = null;
    for (int i = 0; i < ids.length; i++) {
        try {
            dm = conn.domainLookupByID(ids[i]);
            final DomainState ps = dm.getInfo().state;
            final PowerState state = convertToPowerState(ps);
            s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps + "; vm state=" + state.toString());
            final String vmName = dm.getName();
            //
            if (state == PowerState.PowerOn) {
                vmStates.put(vmName, new HostVmStateReportEntry(state, conn.getHostName()));
            }
        } catch (final LibvirtException e) {
            s_logger.warn("Unable to get vms", e);
        } finally {
            try {
                if (dm != null) {
                    dm.free();
                }
            } catch (final LibvirtException e) {
                s_logger.trace("Ignoring libvirt error.", e);
            }
        }
    }
    for (int i = 0; i < vms.length; i++) {
        try {
            dm = conn.domainLookupByName(vms[i]);
            final DomainState ps = dm.getInfo().state;
            final PowerState state = convertToPowerState(ps);
            final String vmName = dm.getName();
            s_logger.trace("VM " + vmName + ": powerstate = " + ps + "; vm state=" + state.toString());
            //
            if (state == PowerState.PowerOn) {
                vmStates.put(vmName, new HostVmStateReportEntry(state, conn.getHostName()));
            }
        } catch (final LibvirtException e) {
            s_logger.warn("Unable to get vms", e);
        } finally {
            try {
                if (dm != null) {
                    dm.free();
                }
            } catch (final LibvirtException e) {
                s_logger.trace("Ignoring libvirt error.", e);
            }
        }
    }
    return vmStates;
}
Also used : LibvirtException(org.libvirt.LibvirtException) HostVmStateReportEntry(com.cloud.agent.api.HostVmStateReportEntry) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DomainState(org.libvirt.DomainInfo.DomainState) Domain(org.libvirt.Domain) PowerState(com.cloud.vm.VirtualMachine.PowerState)

Example 62 with Domain

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

the class LibvirtComputingResource method getVmStat.

public VmStatsEntry getVmStat(final Connect conn, final String vmName) throws LibvirtException {
    Domain dm = null;
    try {
        dm = getDomain(conn, vmName);
        if (dm == null) {
            return null;
        }
        DomainInfo info = dm.getInfo();
        final VmStatsEntry stats = new VmStatsEntry();
        stats.setNumCPUs(info.nrVirtCpu);
        stats.setEntityType("vm");
        stats.setMemoryKBs(info.maxMem);
        stats.setTargetMemoryKBs(info.memory);
        stats.setIntFreeMemoryKBs(getMemoryFreeInKBs(dm));
        /* get cpu utilization */
        VmStats oldStats = null;
        final Calendar now = Calendar.getInstance();
        oldStats = _vmStats.get(vmName);
        long elapsedTime = 0;
        if (oldStats != null) {
            elapsedTime = now.getTimeInMillis() - oldStats._timestamp.getTimeInMillis();
            double utilization = (info.cpuTime - oldStats._usedTime) / ((double) elapsedTime * 1000000);
            final NodeInfo node = conn.nodeInfo();
            utilization = utilization / node.cpus;
            if (utilization > 0) {
                stats.setCPUUtilization(utilization * 100);
            }
        }
        /* get network stats */
        final List<InterfaceDef> vifs = getInterfaces(conn, vmName);
        long rx = 0;
        long tx = 0;
        for (final InterfaceDef vif : vifs) {
            final DomainInterfaceStats ifStats = dm.interfaceStats(vif.getDevName());
            rx += ifStats.rx_bytes;
            tx += ifStats.tx_bytes;
        }
        if (oldStats != null) {
            final double deltarx = rx - oldStats._rx;
            if (deltarx > 0) {
                stats.setNetworkReadKBs(deltarx / 1024);
            }
            final double deltatx = tx - oldStats._tx;
            if (deltatx > 0) {
                stats.setNetworkWriteKBs(deltatx / 1024);
            }
        }
        /* get disk stats */
        final List<DiskDef> disks = getDisks(conn, vmName);
        long io_rd = 0;
        long io_wr = 0;
        long bytes_rd = 0;
        long bytes_wr = 0;
        for (final DiskDef disk : disks) {
            final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel());
            io_rd += blockStats.rd_req;
            io_wr += blockStats.wr_req;
            bytes_rd += blockStats.rd_bytes;
            bytes_wr += blockStats.wr_bytes;
        }
        if (oldStats != null) {
            final long deltaiord = io_rd - oldStats._ioRead;
            if (deltaiord > 0) {
                stats.setDiskReadIOs(deltaiord);
            }
            final long deltaiowr = io_wr - oldStats._ioWrote;
            if (deltaiowr > 0) {
                stats.setDiskWriteIOs(deltaiowr);
            }
            final double deltabytesrd = bytes_rd - oldStats._bytesRead;
            if (deltabytesrd > 0) {
                stats.setDiskReadKBs(deltabytesrd / 1024);
            }
            final double deltabyteswr = bytes_wr - oldStats._bytesWrote;
            if (deltabyteswr > 0) {
                stats.setDiskWriteKBs(deltabyteswr / 1024);
            }
        }
        /* save to Hashmap */
        final VmStats newStat = new VmStats();
        newStat._usedTime = info.cpuTime;
        newStat._rx = rx;
        newStat._tx = tx;
        newStat._ioRead = io_rd;
        newStat._ioWrote = io_wr;
        newStat._bytesRead = bytes_rd;
        newStat._bytesWrote = bytes_wr;
        newStat._timestamp = now;
        _vmStats.put(vmName, newStat);
        return stats;
    } finally {
        if (dm != null) {
            dm.free();
        }
    }
}
Also used : DomainInterfaceStats(org.libvirt.DomainInterfaceStats) Calendar(java.util.Calendar) VmStatsEntry(com.cloud.agent.api.VmStatsEntry) InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef) NodeInfo(org.libvirt.NodeInfo) DomainBlockStats(org.libvirt.DomainBlockStats) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain)

Example 63 with Domain

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

the class LibvirtComputingResource method rebootVM.

public String rebootVM(final Connect conn, final String vmName) {
    Domain dm = null;
    String msg = null;
    try {
        dm = conn.domainLookupByName(vmName);
        // Get XML Dump including the secure information such as VNC password
        // By passing 1, or VIR_DOMAIN_XML_SECURE flag
        // https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainXMLFlags
        String vmDef = dm.getXMLDesc(1);
        final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
        parser.parseDomainXML(vmDef);
        for (final InterfaceDef nic : parser.getInterfaces()) {
            if (nic.getNetType() == GuestNetType.BRIDGE && nic.getBrName().startsWith("cloudVirBr")) {
                try {
                    final int vnetId = Integer.parseInt(nic.getBrName().replaceFirst("cloudVirBr", ""));
                    final String pifName = getPif(_guestBridgeName);
                    final String newBrName = "br" + pifName + "-" + vnetId;
                    vmDef = vmDef.replaceAll("'" + nic.getBrName() + "'", "'" + newBrName + "'");
                    s_logger.debug("VM bridge name is changed from " + nic.getBrName() + " to " + newBrName);
                } catch (final NumberFormatException e) {
                    continue;
                }
            }
        }
        s_logger.debug(vmDef);
        msg = stopVM(conn, vmName);
        msg = startVM(conn, vmName, vmDef);
        return null;
    } catch (final LibvirtException e) {
        s_logger.warn("Failed to create vm", e);
        msg = e.getMessage();
    } catch (final InternalErrorException e) {
        s_logger.warn("Failed to create vm", e);
        msg = e.getMessage();
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (final LibvirtException e) {
            s_logger.trace("Ignoring libvirt error.", e);
        }
    }
    return msg;
}
Also used : InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef) LibvirtException(org.libvirt.LibvirtException) InternalErrorException(com.cloud.exception.InternalErrorException) Domain(org.libvirt.Domain)

Example 64 with Domain

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

the class KVMStorageProcessor method attachOrDetachDevice.

protected synchronized String attachOrDetachDevice(final Connect conn, final boolean attach, final String vmName, final String xml) throws LibvirtException, InternalErrorException {
    Domain dm = null;
    try {
        dm = conn.domainLookupByName(vmName);
        if (attach) {
            s_logger.debug("Attaching device: " + xml);
            dm.attachDevice(xml);
        } else {
            s_logger.debug("Detaching device: " + xml);
            dm.detachDevice(xml);
        }
    } catch (final LibvirtException e) {
        if (attach) {
            s_logger.warn("Failed to attach device to " + vmName + ": " + e.getMessage());
        } else {
            s_logger.warn("Failed to detach device from " + vmName + ": " + e.getMessage());
        }
        throw e;
    } finally {
        if (dm != null) {
            try {
                dm.free();
            } catch (final LibvirtException l) {
                s_logger.trace("Ignoring libvirt error.", l);
            }
        }
    }
    return null;
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 65 with Domain

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

the class KVMStorageProcessor method createSnapshot.

@Override
public Answer createSnapshot(final CreateObjectCommand cmd) {
    final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) cmd.getData();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) snapshotTO.getDataStore();
    final VolumeObjectTO volume = snapshotTO.getVolume();
    final String snapshotName = UUID.randomUUID().toString();
    final String vmName = volume.getVmName();
    try {
        final Connect conn = LibvirtConnection.getConnectionByVmName(vmName);
        DomainInfo.DomainState state = null;
        Domain vm = null;
        if (vmName != null) {
            try {
                vm = resource.getDomain(conn, vmName);
                state = vm.getInfo().state;
            } catch (final LibvirtException e) {
                s_logger.trace("Ignoring libvirt error.", e);
            }
        }
        final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid());
        final KVMPhysicalDisk disk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volume.getPath());
        if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING && !primaryPool.isExternalSnapshot()) {
            final String vmUuid = vm.getUUIDString();
            final Object[] args = new Object[] { snapshotName, vmUuid };
            final String snapshot = SnapshotXML.format(args);
            final long start = System.currentTimeMillis();
            vm.snapshotCreateXML(snapshot);
            final long total = (System.currentTimeMillis() - start) / 1000;
            s_logger.debug("snapshot takes " + total + " seconds to finish");
            /*
                 * libvirt on RHEL6 doesn't handle resume event emitted from
                 * qemu
                 */
            vm = resource.getDomain(conn, vmName);
            state = vm.getInfo().state;
            if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
                vm.resume();
            }
        } else {
            /**
                 * For RBD we can't use libvirt to do our snapshotting or any Bash scripts.
                 * libvirt also wants to store the memory contents of the Virtual Machine,
                 * but that's not possible with RBD since there is no way to store the memory
                 * contents in RBD.
                 *
                 * So we rely on the Java bindings for RBD to create our snapshot
                 *
                 * This snapshot might not be 100% consistent due to writes still being in the
                 * memory of the Virtual Machine, but if the VM runs a kernel which supports
                 * barriers properly (>2.6.32) this won't be any different then pulling the power
                 * cord out of a running machine.
                 */
            if (primaryPool.getType() == StoragePoolType.RBD) {
                try {
                    final Rados r = new Rados(primaryPool.getAuthUserName());
                    r.confSet("mon_host", primaryPool.getSourceHost() + ":" + primaryPool.getSourcePort());
                    r.confSet("key", primaryPool.getAuthSecret());
                    r.confSet("client_mount_timeout", "30");
                    r.connect();
                    s_logger.debug("Succesfully connected to Ceph cluster at " + r.confGet("mon_host"));
                    final IoCTX io = r.ioCtxCreate(primaryPool.getSourceDir());
                    final Rbd rbd = new Rbd(io);
                    final RbdImage image = rbd.open(disk.getName());
                    s_logger.debug("Attempting to create RBD snapshot " + disk.getName() + "@" + snapshotName);
                    image.snapCreate(snapshotName);
                    rbd.close(image);
                    r.ioCtxDestroy(io);
                } catch (final Exception e) {
                    s_logger.error("A RBD snapshot operation on " + disk.getName() + " failed. The error was: " + e.getMessage());
                }
            } else {
                /* VM is not running, create a snapshot by ourself */
                final Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger);
                command.add("-c", disk.getPath());
                command.add("-n", snapshotName);
                final String result = command.execute();
                if (result != null) {
                    s_logger.debug("Failed to manage snapshot: " + result);
                    return new CreateObjectAnswer("Failed to manage snapshot: " + result);
                }
            }
        }
        final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        // NOTE: sort of hack, we'd better just put snapshtoName
        newSnapshot.setPath(disk.getPath() + File.separator + snapshotName);
        return new CreateObjectAnswer(newSnapshot);
    } catch (final LibvirtException e) {
        s_logger.debug("Failed to manage snapshot: ", e);
        return new CreateObjectAnswer("Failed to manage snapshot: " + e.toString());
    }
}
Also used : SnapshotObjectTO(org.apache.cloudstack.storage.to.SnapshotObjectTO) Script(com.cloud.utils.script.Script) LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) Rados(com.ceph.rados.Rados) CreateObjectAnswer(org.apache.cloudstack.storage.command.CreateObjectAnswer) URISyntaxException(java.net.URISyntaxException) LibvirtException(org.libvirt.LibvirtException) RbdException(com.ceph.rbd.RbdException) QemuImgException(org.apache.cloudstack.utils.qemu.QemuImgException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RadosException(com.ceph.rados.exceptions.RadosException) IOException(java.io.IOException) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) Rbd(com.ceph.rbd.Rbd) RbdImage(com.ceph.rbd.RbdImage) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) IoCTX(com.ceph.rados.IoCTX) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain)

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