Search in sources :

Example 56 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: " + 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)

Example 57 with Domain

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

the class LibvirtComputingResource method getDisks.

public List<DiskDef> getDisks(final Connect conn, final String vmName) {
    final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
    Domain dm = null;
    try {
        dm = conn.domainLookupByName(vmName);
        parser.parseDomainXML(dm.getXMLDesc(0));
        return parser.getDisks();
    } catch (final LibvirtException e) {
        s_logger.debug("Failed to get dom xml: " + e.toString());
        return new ArrayList<DiskDef>();
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (final LibvirtException e) {
            s_logger.trace("Ignoring libvirt error.", e);
        }
    }
}
Also used : DiskDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef) LibvirtException(org.libvirt.LibvirtException) Domain(org.libvirt.Domain)

Example 58 with Domain

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

the class LibvirtComputingResource method stopVM.

public String stopVM(final Connect conn, final String vmName) {
    DomainState state = null;
    Domain dm = null;
    // delete the metadata of vm snapshots before stopping
    try {
        dm = conn.domainLookupByName(vmName);
        cleanVMSnapshotMetadata(dm);
    } catch (LibvirtException e) {
        s_logger.debug("Failed to get vm :" + e.getMessage());
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (LibvirtException l) {
            s_logger.trace("Ignoring libvirt error.", l);
        }
    }
    s_logger.debug("Try to stop the vm at first");
    String ret = stopVM(conn, vmName, false);
    if (ret == Script.ERR_TIMEOUT) {
        ret = stopVM(conn, vmName, true);
    } else if (ret != null) {
        /* Retry 3 times, to make sure we can get the vm's status */
        for (int i = 0; i < 3; i++) {
            try {
                dm = conn.domainLookupByName(vmName);
                state = dm.getInfo().state;
                break;
            } catch (final LibvirtException e) {
                s_logger.debug("Failed to get vm status:" + e.getMessage());
            } finally {
                try {
                    if (dm != null) {
                        dm.free();
                    }
                } catch (final LibvirtException l) {
                    s_logger.trace("Ignoring libvirt error.", l);
                }
            }
        }
        if (state == null) {
            s_logger.debug("Can't get vm's status, assume it's dead already");
            return null;
        }
        if (state != DomainState.VIR_DOMAIN_SHUTOFF) {
            s_logger.debug("Try to destroy the vm");
            ret = stopVM(conn, vmName, true);
            if (ret != null) {
                return ret;
            }
        }
    }
    return null;
}
Also used : LibvirtException(org.libvirt.LibvirtException) DomainState(org.libvirt.DomainInfo.DomainState) Domain(org.libvirt.Domain)

Example 59 with Domain

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

the class LibvirtComputingResource method VifHotPlug.

private void VifHotPlug(final Connect conn, final String vmName, final String broadcastUri, final String macAddr) throws InternalErrorException, LibvirtException {
    final NicTO nicTO = new NicTO();
    nicTO.setMac(macAddr);
    nicTO.setType(TrafficType.Public);
    if (broadcastUri == null) {
        nicTO.setBroadcastType(BroadcastDomainType.Native);
    } else {
        final URI uri = BroadcastDomainType.fromString(broadcastUri);
        nicTO.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
        nicTO.setBroadcastUri(uri);
    }
    final Domain vm = getDomain(conn, vmName);
    vm.attachDevice(getVifDriver(nicTO.getType()).plug(nicTO, "Other PV", "").toString());
}
Also used : Domain(org.libvirt.Domain) URI(java.net.URI) NicTO(com.cloud.agent.api.to.NicTO)

Example 60 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)

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