Search in sources :

Example 76 with Domain

use of org.libvirt.Domain in project cosmic by MissionCriticalCloud.

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 = getStopScriptTimeout() / 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")) {
                    logger.debug("successfully shut down vm " + vmName);
                } else {
                    logger.debug("Error in waiting for vm shutdown:" + error);
                }
            }
            if (retry < 0) {
                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")) {
            logger.debug("VM " + vmName + " doesn't exist, no need to stop it");
            return null;
        }
        logger.debug("Failed to stop VM :" + vmName + " :", e);
        return e.getMessage();
    } catch (final InterruptedException ie) {
        logger.debug("Interrupted sleep");
        return ie.getMessage();
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (final LibvirtException e) {
            logger.trace("Ignoring libvirt error.", e);
        }
    }
    return null;
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 77 with Domain

use of org.libvirt.Domain in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResource method startVm.

public String startVm(final Connect conn, final String vmName, final String domainXml) throws LibvirtException, InternalErrorException {
    try {
        /*
             * We create a transient domain here. When this method gets called we receive a full XML specification of the
             * guest, so no need to define it persistent.
             *
             * This also makes sure we never have any old "garbage" defined in libvirt which might haunt us.
             */
        // check for existing inactive vm definition and remove it
        // this can sometimes happen during crashes, etc
        Domain dm = null;
        try {
            dm = conn.domainLookupByName(vmName);
            if (dm != null && dm.isPersistent() == 1) {
                // this is safe because it doesn't stop running VMs
                dm.undefine();
            }
        } catch (final LibvirtException e) {
        // this is what we want, no domain found
        } finally {
            if (dm != null) {
                dm.free();
            }
        }
        conn.domainCreateXML(domainXml, 0);
    } catch (final LibvirtException e) {
        throw e;
    }
    return null;
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 78 with Domain

use of org.libvirt.Domain in project cosmic by MissionCriticalCloud.

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) {
            logger.trace("Ignoring libvirt error.", l);
        }
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 79 with Domain

use of org.libvirt.Domain in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResource method getVmState.

public PowerState getVmState(final Connect conn, final String vmName) {
    int retry = 3;
    Domain vms = null;
    while (retry-- > 0) {
        try {
            vms = conn.domainLookupByName(vmName);
            final PowerState s = convertToPowerState(vms.getInfo().state);
            return s;
        } catch (final LibvirtException e) {
            logger.warn("Can't get vm state " + vmName + e.getMessage() + "retry:" + retry);
        } finally {
            try {
                if (vms != null) {
                    vms.free();
                }
            } catch (final LibvirtException l) {
                logger.trace("Ignoring libvirt error.", l);
            }
        }
    }
    return PowerState.PowerOff;
}
Also used : LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain) PowerState(com.cloud.vm.VirtualMachine.PowerState)

Example 80 with Domain

use of org.libvirt.Domain in project cosmic by MissionCriticalCloud.

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();
        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: " + 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 : KvmStoragePool(com.cloud.hypervisor.kvm.storage.KvmStoragePool) LibvirtException(org.libvirt.LibvirtException) RadosException(com.ceph.rados.exceptions.RadosException) Rbd(com.ceph.rbd.Rbd) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) KvmStoragePoolManager(com.cloud.hypervisor.kvm.storage.KvmStoragePoolManager) KvmPhysicalDisk(com.cloud.hypervisor.kvm.storage.KvmPhysicalDisk) BufferedOutputStream(java.io.BufferedOutputStream) Script(com.cloud.utils.script.Script) MessageFormat(java.text.MessageFormat) 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