Search in sources :

Example 96 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 97 with Domain

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

the class LibvirtComputingResource method getVncPort.

public Integer getVncPort(final Connect conn, final String vmName) throws LibvirtException {
    final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
    Domain dm = null;
    try {
        dm = conn.domainLookupByName(vmName);
        final String xmlDesc = dm.getXMLDesc(0);
        parser.parseDomainXML(xmlDesc);
        return parser.getVncPort();
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (final LibvirtException l) {
            s_logger.trace("Ignoring libvirt error.", l);
        }
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 98 with Domain

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

the class LibvirtComputingResource method stopVMInternal.

protected String stopVMInternal(final Connect conn, final String vmName, final boolean force) {
    Domain dm = null;
    try {
        dm = conn.domainLookupByName(vmName);
        final int persist = dm.isPersistent();
        if (force) {
            if (dm.isActive() == 1) {
                dm.destroy();
                if (persist == 1) {
                    dm.undefine();
                }
            }
        } else {
            if (dm.isActive() == 0) {
                return null;
            }
            dm.shutdown();
            int retry = _stopTimeout / 2000;
            /* Wait for the domain gets into shutoff state. When it does
                   the dm object will no longer work, so we need to catch it. */
            try {
                while (dm.isActive() == 1 && retry >= 0) {
                    Thread.sleep(2000);
                    retry--;
                }
            } catch (final LibvirtException e) {
                final String error = e.toString();
                if (error.contains("Domain not found")) {
                    s_logger.debug("successfully shut down vm " + vmName);
                } else {
                    s_logger.debug("Error in waiting for vm shutdown:" + error);
                }
            }
            if (retry < 0) {
                s_logger.warn("Timed out waiting for domain " + vmName + " to shutdown gracefully");
                return Script.ERR_TIMEOUT;
            } else {
                if (persist == 1) {
                    dm.undefine();
                }
            }
        }
    } catch (final LibvirtException e) {
        if (e.getMessage().contains("Domain not found")) {
            s_logger.debug("VM " + vmName + " doesn't exist, no need to stop it");
            return null;
        }
        s_logger.debug("Failed to stop VM :" + vmName + " :", e);
        return e.getMessage();
    } catch (final InterruptedException ie) {
        s_logger.debug("Interrupted sleep");
        return ie.getMessage();
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (final LibvirtException e) {
            s_logger.trace("Ignoring libvirt error.", e);
        }
    }
    return null;
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 99 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);
            utilization = utilization / info.nrVirtCpu;
            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) {
            if (disk.getDeviceType() == DeviceType.CDROM || disk.getDeviceType() == DeviceType.FLOPPY) {
                continue;
            }
            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) DomainBlockStats(org.libvirt.DomainBlockStats) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain)

Example 100 with Domain

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

the class LibvirtBackupSnapshotCommandWrapper method execute.

@Override
public Answer execute(final BackupSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final Long dcId = command.getDataCenterId();
    final Long accountId = command.getAccountId();
    final Long volumeId = command.getVolumeId();
    final String secondaryStoragePoolUrl = command.getSecondaryStorageUrl();
    final String snapshotName = command.getSnapshotName();
    String snapshotDestPath = null;
    String snapshotRelPath = null;
    final String vmName = command.getVmName();
    KVMStoragePool secondaryStoragePool = null;
    final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
        secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolUrl);
        final String ssPmountPath = secondaryStoragePool.getLocalPath();
        snapshotRelPath = File.separator + "snapshots" + File.separator + dcId + File.separator + accountId + File.separator + volumeId;
        snapshotDestPath = ssPmountPath + File.separator + "snapshots" + File.separator + dcId + File.separator + accountId + File.separator + volumeId;
        final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel());
        final KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(command.getVolumePath());
        final String manageSnapshotPath = libvirtComputingResource.manageSnapshotPath();
        final int cmdsTimeout = libvirtComputingResource.getCmdsTimeout();
        /**
         * RBD snapshots can't be copied using qemu-img, so we have to use
         * the Java bindings for librbd here.
         *
         * These bindings will read the snapshot and write the contents to
         * the secondary storage directly
         *
         * It will stop doing so if the amount of time spend is longer then
         * cmds.timeout
         */
        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(snapshotDisk.getName(), snapshotName);
                final File fh = new File(snapshotDestPath);
                try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fh))) {
                    final int chunkSize = 4194304;
                    long offset = 0;
                    s_logger.debug("Backuping up RBD snapshot " + snapshotName + " to  " + snapshotDestPath);
                    while (true) {
                        final byte[] buf = new byte[chunkSize];
                        final int bytes = image.read(offset, buf, chunkSize);
                        if (bytes <= 0) {
                            break;
                        }
                        bos.write(buf, 0, bytes);
                        offset += bytes;
                    }
                    s_logger.debug("Completed backing up RBD snapshot " + snapshotName + " to  " + snapshotDestPath + ". Bytes written: " + toHumanReadableSize(offset));
                } catch (final IOException ex) {
                    s_logger.error("BackupSnapshotAnswer:Exception:" + ex.getMessage());
                }
                r.ioCtxDestroy(io);
            } catch (final RadosException e) {
                s_logger.error("A RADOS operation failed. The error was: " + e.getMessage());
                return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
            } catch (final RbdException e) {
                s_logger.error("A RBD operation on " + snapshotDisk.getName() + " failed. The error was: " + e.getMessage());
                return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
            }
        } else {
            final Script scriptCommand = new Script(manageSnapshotPath, cmdsTimeout, s_logger);
            scriptCommand.add("-b", snapshotDisk.getPath());
            scriptCommand.add("-n", snapshotName);
            scriptCommand.add("-p", snapshotDestPath);
            scriptCommand.add("-t", snapshotName);
            final String result = scriptCommand.execute();
            if (result != null) {
                s_logger.debug("Failed to backup snaptshot: " + result);
                return new BackupSnapshotAnswer(command, false, result, null, true);
            }
        }
        /* Delete the snapshot on primary */
        DomainState state = null;
        Domain vm = null;
        if (vmName != null) {
            try {
                vm = libvirtComputingResource.getDomain(conn, command.getVmName());
                state = vm.getInfo().state;
            } catch (final LibvirtException e) {
                s_logger.trace("Ignoring libvirt error.", e);
            }
        }
        final KVMStoragePool primaryStorage = storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPool().getUuid());
        if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) {
            final MessageFormat snapshotXML = new MessageFormat("   <domainsnapshot>" + "       <name>{0}</name>" + "          <domain>" + "            <uuid>{1}</uuid>" + "        </domain>" + "    </domainsnapshot>");
            final String vmUuid = vm.getUUIDString();
            final Object[] args = new Object[] { snapshotName, vmUuid };
            final String snapshot = snapshotXML.format(args);
            s_logger.debug(snapshot);
            final DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
            if (snap != null) {
                snap.delete(0);
            } else {
                throw new CloudRuntimeException("Unable to find vm snapshot with name -" + snapshotName);
            }
            /*
                 * libvirt on RHEL6 doesn't handle resume event emitted from
                 * qemu
                 */
            vm = libvirtComputingResource.getDomain(conn, command.getVmName());
            state = vm.getInfo().state;
            if (state == DomainState.VIR_DOMAIN_PAUSED) {
                vm.resume();
            }
        } else {
            final Script scriptCommand = new Script(manageSnapshotPath, cmdsTimeout, s_logger);
            scriptCommand.add("-d", snapshotDisk.getPath());
            scriptCommand.add("-n", snapshotName);
            final String result = scriptCommand.execute();
            if (result != null) {
                s_logger.debug("Failed to backup snapshot: " + result);
                return new BackupSnapshotAnswer(command, false, "Failed to backup snapshot: " + result, null, true);
            }
        }
    } catch (final LibvirtException e) {
        return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
    } catch (final CloudRuntimeException e) {
        return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
    } finally {
        if (secondaryStoragePool != null) {
            storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
        }
    }
    return new BackupSnapshotAnswer(command, true, null, snapshotRelPath + File.separator + snapshotName, true);
}
Also used : LibvirtException(org.libvirt.LibvirtException) RadosException(com.ceph.rados.exceptions.RadosException) KVMStoragePool(com.cloud.hypervisor.kvm.storage.KVMStoragePool) Rbd(com.ceph.rbd.Rbd) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) BufferedOutputStream(java.io.BufferedOutputStream) Script(com.cloud.utils.script.Script) KVMStoragePoolManager(com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager) MessageFormat(java.text.MessageFormat) KVMPhysicalDisk(com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk) Connect(org.libvirt.Connect) Rados(com.ceph.rados.Rados) DomainSnapshot(org.libvirt.DomainSnapshot) IOException(java.io.IOException) DomainState(org.libvirt.DomainInfo.DomainState) FileOutputStream(java.io.FileOutputStream) RbdImage(com.ceph.rbd.RbdImage) IoCTX(com.ceph.rados.IoCTX) BackupSnapshotAnswer(com.cloud.agent.api.BackupSnapshotAnswer) Domain(org.libvirt.Domain) File(java.io.File) RbdException(com.ceph.rbd.RbdException)

Aggregations

Domain (org.libvirt.Domain)112 LibvirtException (org.libvirt.LibvirtException)92 Connect (org.libvirt.Connect)58 InternalErrorException (com.cloud.exception.InternalErrorException)35 Test (org.junit.Test)26 URISyntaxException (java.net.URISyntaxException)23 DomainState (org.libvirt.DomainInfo.DomainState)23 Answer (com.cloud.agent.api.Answer)22 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)22 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)22 LibvirtUtilitiesHelper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper)22 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)22 IOException (java.io.IOException)21 DomainInfo (org.libvirt.DomainInfo)21 NicTO (com.cloud.agent.api.to.NicTO)20 ArrayList (java.util.ArrayList)19 ConfigurationException (javax.naming.ConfigurationException)19 InterfaceDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef)16 FileNotFoundException (java.io.FileNotFoundException)16 ExecutionException (java.util.concurrent.ExecutionException)14