Search in sources :

Example 71 with Domain

use of org.libvirt.Domain in project CloudStack-archive by CloudStack-extras.

the class LibvirtComputingResource method execute.

protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) {
    Long dcId = cmd.getDataCenterId();
    Long accountId = cmd.getAccountId();
    Long volumeId = cmd.getVolumeId();
    String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl();
    String snapshotName = cmd.getSnapshotName();
    String snapshotPath = cmd.getVolumePath();
    String snapshotDestPath = null;
    String snapshotRelPath = null;
    String vmName = cmd.getVmName();
    KVMStoragePool secondaryStoragePool = null;
    try {
        Connect conn = LibvirtConnection.getConnection();
        secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolUrl);
        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;
        KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd.getPrimaryStoragePoolNameLabel());
        KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd.getVolumePath());
        Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger);
        command.add("-b", snapshotDisk.getPath());
        command.add("-n", snapshotName);
        command.add("-p", snapshotDestPath);
        command.add("-t", snapshotName);
        String result = command.execute();
        if (result != null) {
            s_logger.debug("Failed to backup snaptshot: " + result);
            return new BackupSnapshotAnswer(cmd, false, result, null, true);
        }
        /* Delete the snapshot on primary */
        DomainInfo.DomainState state = null;
        Domain vm = null;
        if (vmName != null) {
            try {
                vm = getDomain(conn, cmd.getVmName());
                state = vm.getInfo().state;
            } catch (LibvirtException e) {
            }
        }
        KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd.getPool().getUuid());
        if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) {
            String vmUuid = vm.getUUIDString();
            Object[] args = new Object[] { snapshotName, vmUuid };
            String snapshot = SnapshotXML.format(args);
            s_logger.debug(snapshot);
            DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
            snap.delete(0);
            /*
				 * libvirt on RHEL6 doesn't handle resume event emitted from
				 * qemu
				 */
            vm = getDomain(conn, cmd.getVmName());
            state = vm.getInfo().state;
            if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
                vm.resume();
            }
        } else {
            command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger);
            command.add("-d", snapshotDisk.getPath());
            command.add("-n", snapshotName);
            result = command.execute();
            if (result != null) {
                s_logger.debug("Failed to backup snapshot: " + result);
                return new BackupSnapshotAnswer(cmd, false, "Failed to backup snapshot: " + result, null, true);
            }
        }
    } catch (LibvirtException e) {
        return new BackupSnapshotAnswer(cmd, false, e.toString(), null, true);
    } catch (CloudRuntimeException e) {
        return new BackupSnapshotAnswer(cmd, false, e.toString(), null, true);
    } finally {
        if (secondaryStoragePool != null) {
            secondaryStoragePool.delete();
        }
    }
    return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath + File.separator + snapshotName, true);
}
Also used : Script(com.cloud.utils.script.Script) LibvirtException(org.libvirt.LibvirtException) KVMPhysicalDisk(com.cloud.agent.storage.KVMPhysicalDisk) Connect(org.libvirt.Connect) DomainSnapshot(org.libvirt.DomainSnapshot) KVMStoragePool(com.cloud.agent.storage.KVMStoragePool) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) BackupSnapshotAnswer(com.cloud.agent.api.BackupSnapshotAnswer) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain)

Example 72 with Domain

use of org.libvirt.Domain in project CloudStack-archive by CloudStack-extras.

the class LibvirtComputingResource method getVmState.

protected State getVmState(Connect conn, final String vmName) {
    int retry = 3;
    Domain vms = null;
    while (retry-- > 0) {
        try {
            vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes()));
            State s = convertToState(vms.getInfo().state);
            return s;
        } catch (final LibvirtException e) {
            s_logger.warn("Can't get vm state " + vmName + e.getMessage() + "retry:" + retry);
        } catch (Exception e) {
            s_logger.warn("Can't get vm state " + vmName + e.getMessage() + "retry:" + retry);
        } finally {
            try {
                if (vms != null) {
                    vms.free();
                }
            } catch (final LibvirtException e) {
            }
        }
    }
    return State.Stopped;
}
Also used : LibvirtException(org.libvirt.LibvirtException) State(com.cloud.vm.VirtualMachine.State) Domain(org.libvirt.Domain) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) LibvirtException(org.libvirt.LibvirtException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException)

Example 73 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 74 with Domain

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

the class KvmStorageProcessor method backupSnapshot.

@Override
public Answer backupSnapshot(final CopyCommand cmd) {
    final DataTO srcData = cmd.getSrcTO();
    final DataTO destData = cmd.getDestTO();
    final SnapshotObjectTO snapshot = (SnapshotObjectTO) srcData;
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) snapshot.getDataStore();
    final SnapshotObjectTO destSnapshot = (SnapshotObjectTO) destData;
    final DataStoreTO imageStore = destData.getDataStore();
    final NfsTO nfsImageStore = (NfsTO) imageStore;
    final String secondaryStoragePoolUrl = nfsImageStore.getUrl();
    // NOTE: snapshot name is encoded in snapshot path
    final int index = snapshot.getPath().lastIndexOf("/");
    // -1 means the snapshot is created from existing vm snapshot
    final boolean isCreatedFromVmSnapshot = index == -1;
    final String snapshotName = snapshot.getPath().substring(index + 1);
    String descName = snapshotName;
    final String volumePath = snapshot.getVolume().getPath();
    String snapshotDestPath;
    String snapshotRelPath;
    final String vmName = snapshot.getVmName();
    KvmStoragePool secondaryStoragePool = null;
    Connect conn = null;
    KvmPhysicalDisk snapshotDisk = null;
    KvmStoragePool primaryPool = null;
    try {
        conn = LibvirtConnection.getConnectionByVmName(vmName);
        secondaryStoragePool = storagePoolMgr.getStoragePoolByUri(secondaryStoragePoolUrl);
        final String ssPmountPath = secondaryStoragePool.getLocalPath();
        snapshotRelPath = destSnapshot.getPath();
        snapshotDestPath = ssPmountPath + File.separator + snapshotRelPath;
        snapshotDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volumePath);
        primaryPool = snapshotDisk.getPool();
        long size = 0;
        if (primaryPool.getType() == StoragePoolType.RBD) {
            final String rbdSnapshot = snapshotDisk.getPath() + "@" + snapshotName;
            final String snapshotFile = snapshotDestPath + "/" + snapshotName;
            try {
                logger.debug("Attempting to backup RBD snapshot " + rbdSnapshot);
                final File snapDir = new File(snapshotDestPath);
                logger.debug("Attempting to create " + snapDir.getAbsolutePath() + " recursively for snapshot storage");
                FileUtils.forceMkdir(snapDir);
                final QemuImgFile srcFile = new QemuImgFile(KvmPhysicalDisk.rbdStringBuilder(primaryPool.getSourceHost(), primaryPool.getSourcePort(), primaryPool.getAuthUserName(), primaryPool.getAuthSecret(), rbdSnapshot));
                srcFile.setFormat(snapshotDisk.getFormat());
                final QemuImgFile destFile = new QemuImgFile(snapshotFile);
                destFile.setFormat(PhysicalDiskFormat.QCOW2);
                logger.debug("Backing up RBD snapshot " + rbdSnapshot + " to " + snapshotFile);
                final QemuImg q = new QemuImg(cmd.getWaitInMillSeconds());
                q.convert(srcFile, destFile);
                final File snapFile = new File(snapshotFile);
                if (snapFile.exists()) {
                    size = snapFile.length();
                }
                logger.debug("Finished backing up RBD snapshot " + rbdSnapshot + " to " + snapshotFile + " Snapshot size: " + size);
            } catch (final FileNotFoundException e) {
                logger.error("Failed to open " + snapshotDestPath + ". The error was: " + e.getMessage());
                return new CopyCmdAnswer(e.toString());
            } catch (final IOException e) {
                logger.error("Failed to create " + snapshotDestPath + ". The error was: " + e.getMessage());
                return new CopyCmdAnswer(e.toString());
            } catch (final QemuImgException e) {
                logger.error("Failed to backup the RBD snapshot from " + rbdSnapshot + " to " + snapshotFile + " the error was: " + e.getMessage());
                return new CopyCmdAnswer(e.toString());
            }
        } else {
            final Script command = new Script(manageSnapshotPath, cmd.getWaitInMillSeconds(), logger);
            command.add("-b", snapshotDisk.getPath());
            command.add("-n", snapshotName);
            command.add("-p", snapshotDestPath);
            if (isCreatedFromVmSnapshot) {
                descName = UUID.randomUUID().toString();
            }
            command.add("-t", descName);
            final String result = command.execute();
            if (result != null) {
                logger.debug("Failed to backup snaptshot: " + result);
                return new CopyCmdAnswer(result);
            }
            final File snapFile = new File(snapshotDestPath + "/" + descName);
            if (snapFile.exists()) {
                size = snapFile.length();
            }
        }
        final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(snapshotRelPath + File.separator + descName);
        newSnapshot.setPhysicalSize(size);
        return new CopyCmdAnswer(newSnapshot);
    } catch (final LibvirtException | CloudRuntimeException e) {
        logger.debug("Failed to backup snapshot: ", e);
        return new CopyCmdAnswer(e.toString());
    } finally {
        if (isCreatedFromVmSnapshot) {
            logger.debug("Ignoring removal of vm snapshot on primary as this snapshot is created from vm snapshot");
        } else {
            try {
                /* Delete the snapshot on primary */
                DomainState state = null;
                Domain vm = null;
                if (vmName != null) {
                    try {
                        vm = resource.getDomain(conn, vmName);
                        state = vm.getInfo().state;
                    } catch (final LibvirtException e) {
                        logger.trace("Ignoring libvirt error.", e);
                    }
                }
                final KvmStoragePool primaryStorage = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid());
                if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) {
                    final DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
                    snap.delete(0);
                    /*
                         * 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 {
                    if (primaryPool.getType() != StoragePoolType.RBD) {
                        final Script command = new Script(manageSnapshotPath, cmdsTimeout, logger);
                        command.add("-d", snapshotDisk.getPath());
                        command.add("-n", snapshotName);
                        final String result = command.execute();
                        if (result != null) {
                            logger.debug("Failed to delete snapshot on primary: " + result);
                        // return new CopyCmdAnswer("Failed to backup snapshot: " + result);
                        }
                    }
                }
            } catch (final Exception ex) {
                logger.debug("Failed to delete snapshots on primary", ex);
            }
        }
        try {
            if (secondaryStoragePool != null) {
                secondaryStoragePool.delete();
            }
        } catch (final Exception ex) {
            logger.debug("Failed to delete secondary storage", ex);
        }
    }
}
Also used : SnapshotObjectTO(com.cloud.storage.to.SnapshotObjectTO) LibvirtException(org.libvirt.LibvirtException) FileNotFoundException(java.io.FileNotFoundException) DataTO(com.cloud.agent.api.to.DataTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) QemuImgException(com.cloud.utils.qemu.QemuImgException) Script(com.cloud.utils.script.Script) PrimaryDataStoreTO(com.cloud.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) Connect(org.libvirt.Connect) DomainSnapshot(org.libvirt.DomainSnapshot) IOException(java.io.IOException) NfsTO(com.cloud.agent.api.to.NfsTO) URISyntaxException(java.net.URISyntaxException) LibvirtException(org.libvirt.LibvirtException) QemuImgException(com.cloud.utils.qemu.QemuImgException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) QemuImg(com.cloud.utils.qemu.QemuImg) PrimaryDataStoreTO(com.cloud.storage.to.PrimaryDataStoreTO) QemuImgFile(com.cloud.utils.qemu.QemuImgFile) DomainState(org.libvirt.DomainInfo.DomainState) Domain(org.libvirt.Domain) QemuImgFile(com.cloud.utils.qemu.QemuImgFile) File(java.io.File) CopyCmdAnswer(com.cloud.storage.command.CopyCmdAnswer)

Example 75 with Domain

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

the class KvmStorageProcessor method attachOrDetachDisk.

protected synchronized String attachOrDetachDisk(final Connect conn, final boolean attach, final String vmName, final KvmPhysicalDisk attachingDisk, final int devId, final String serial) throws LibvirtException, InternalErrorException {
    List<LibvirtDiskDef> disks = null;
    Domain dm = null;
    LibvirtDiskDef diskdef = null;
    final KvmStoragePool attachingPool = attachingDisk.getPool();
    try {
        dm = conn.domainLookupByName(vmName);
        final LibvirtDomainXmlParser parser = new LibvirtDomainXmlParser();
        final String domXml = dm.getXMLDesc(0);
        parser.parseDomainXml(domXml);
        disks = parser.getDisks();
        if (!attach) {
            for (final LibvirtDiskDef disk : disks) {
                final String file = disk.getDiskPath();
                if (file != null && file.equalsIgnoreCase(attachingDisk.getPath())) {
                    diskdef = disk;
                    break;
                }
            }
            if (diskdef == null) {
                throw new InternalErrorException("disk: " + attachingDisk.getPath() + " is not attached before");
            }
        } else {
            LibvirtDiskDef.DiskBus diskBusType = LibvirtDiskDef.DiskBus.VIRTIO;
            for (final LibvirtDiskDef disk : disks) {
                logger.debug("disk is type : " + disk.toString());
                if (disk.getDeviceType() == LibvirtDiskDef.DeviceType.DISK) {
                    if (disk.getBusType() == LibvirtDiskDef.DiskBus.SCSI) {
                        diskBusType = LibvirtDiskDef.DiskBus.SCSI;
                    }
                    logger.debug("Disk bus type: " + disk.getDeviceType().toString() + ", diskBusType: " + diskBusType.toString());
                    break;
                }
            }
            diskdef = new LibvirtDiskDef();
            if (diskBusType == LibvirtDiskDef.DiskBus.SCSI) {
                diskdef.setQemuDriver(true);
                diskdef.setDiscard(LibvirtDiskDef.DiscardType.UNMAP);
            }
            diskdef.setSerial(serial);
            if (attachingPool.getType() == StoragePoolType.RBD) {
                diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), attachingPool.getAuthUserName(), attachingPool.getUuid(), devId, diskBusType, LibvirtDiskDef.DiskProtocol.RBD, LibvirtDiskDef.DiskFmtType.RAW);
            } else if (attachingPool.getType() == StoragePoolType.Gluster) {
                final String mountpoint = attachingPool.getLocalPath();
                final String path = attachingDisk.getPath();
                final String glusterVolume = attachingPool.getSourceDir().replace("/", "");
                diskdef.defNetworkBasedDisk(glusterVolume + path.replace(mountpoint, ""), attachingPool.getSourceHost(), attachingPool.getSourcePort(), null, null, devId, diskBusType, LibvirtDiskDef.DiskProtocol.GLUSTER, LibvirtDiskDef.DiskFmtType.QCOW2);
            } else if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
                diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, diskBusType, LibvirtDiskDef.DiskFmtType.QCOW2);
            } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
                diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, diskBusType);
            }
        }
        final String xml = diskdef.toString();
        return attachOrDetachDevice(conn, attach, vmName, xml);
    } finally {
        if (dm != null) {
            dm.free();
        }
    }
}
Also used : LibvirtDiskDef(com.cloud.hypervisor.kvm.resource.xml.LibvirtDiskDef) LibvirtDomainXmlParser(com.cloud.hypervisor.kvm.resource.LibvirtDomainXmlParser) InternalErrorException(com.cloud.exception.InternalErrorException) Domain(org.libvirt.Domain)

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