Search in sources :

Example 11 with DomainState

use of org.libvirt.DomainInfo.DomainState in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testStopCommandCheckVmRunning.

@Test
public void testStopCommandCheckVmRunning() {
    final Connect conn = Mockito.mock(Connect.class);
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final Domain vm = Mockito.mock(Domain.class);
    final DomainInfo info = Mockito.mock(DomainInfo.class);
    final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING;
    info.state = state;
    final String vmName = "Test";
    final StopCommand command = new StopCommand(vmName, false, true);
    when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    try {
        when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
        when(conn.domainLookupByName(command.getVmName())).thenReturn(vm);
        when(vm.getInfo()).thenReturn(info);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
    try {
        verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
}
Also used : Answer(com.cloud.agent.api.Answer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) AttachAnswer(com.cloud.storage.command.AttachAnswer) StopCommand(com.cloud.agent.api.StopCommand) LibvirtRequestWrapper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper) LibvirtException(org.libvirt.LibvirtException) DomainState(org.libvirt.DomainInfo.DomainState) Connect(org.libvirt.Connect) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain) LibvirtUtilitiesHelper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper) Test(org.junit.Test)

Example 12 with DomainState

use of org.libvirt.DomainInfo.DomainState in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testStopCommandCheckException1.

@Test
public void testStopCommandCheckException1() {
    final Connect conn = Mockito.mock(Connect.class);
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final Domain vm = Mockito.mock(Domain.class);
    final DomainInfo info = Mockito.mock(DomainInfo.class);
    final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING;
    info.state = state;
    final String vmName = "Test";
    final StopCommand command = new StopCommand(vmName, false, true);
    when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    try {
        when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
        when(conn.domainLookupByName(command.getVmName())).thenReturn(vm);
        when(vm.getInfo()).thenReturn(info);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
    try {
        verify(libvirtUtilitiesHelper, times(2)).getConnectionByVmName(vmName);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    }
}
Also used : Answer(com.cloud.agent.api.Answer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) AttachAnswer(com.cloud.storage.command.AttachAnswer) StopCommand(com.cloud.agent.api.StopCommand) LibvirtRequestWrapper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper) LibvirtException(org.libvirt.LibvirtException) DomainState(org.libvirt.DomainInfo.DomainState) Connect(org.libvirt.Connect) DomainInfo(org.libvirt.DomainInfo) Domain(org.libvirt.Domain) LibvirtUtilitiesHelper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper) Test(org.junit.Test)

Example 13 with DomainState

use of org.libvirt.DomainInfo.DomainState in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResource method getHostVmStateReport.

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

Example 14 with DomainState

use of org.libvirt.DomainInfo.DomainState in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResource method stopVm.

public String stopVm(final Connect conn, final String vmName, final boolean forceStop) {
    DomainState state = null;
    Domain dm = null;
    // delete the metadata of vm snapshots before stopping
    try {
        dm = conn.domainLookupByName(vmName);
        cleanVMSnapshotMetadata(dm);
    } catch (final LibvirtException e) {
        logger.debug("Failed to get vm :" + e.getMessage());
    } finally {
        try {
            if (dm != null) {
                dm.free();
            }
        } catch (final LibvirtException l) {
            logger.trace("Ignoring libvirt error.", l);
        }
    }
    logger.debug("Try to stop the vm at first");
    String ret = stopVmInternal(conn, vmName, forceStop);
    if (ret == Script.ERR_TIMEOUT) {
        ret = stopVmInternal(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) {
                logger.debug("Failed to get vm status:" + e.getMessage());
            } finally {
                try {
                    if (dm != null) {
                        dm.free();
                    }
                } catch (final LibvirtException l) {
                    logger.trace("Ignoring libvirt error.", l);
                }
            }
        }
        if (state == null) {
            logger.debug("Can't get vm's status, assume it's dead already");
            return null;
        }
        if (state != DomainState.VIR_DOMAIN_SHUTOFF) {
            logger.debug("Try to destroy the vm");
            ret = stopVmInternal(conn, vmName, forceStop);
            if (ret != null) {
                return ret;
            }
        }
    }
    return null;
}
Also used : LibvirtException(org.libvirt.LibvirtException) DomainState(org.libvirt.DomainInfo.DomainState) Domain(org.libvirt.Domain)

Example 15 with DomainState

use of org.libvirt.DomainInfo.DomainState in project cosmic by MissionCriticalCloud.

the class LibvirtManageSnapshotCommandWrapper method execute.

@Override
public Answer execute(final ManageSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final String snapshotName = command.getSnapshotName();
    final String snapshotPath = command.getSnapshotPath();
    final String vmName = command.getVmName();
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
        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 KvmStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
        final StorageFilerTO pool = command.getPool();
        final KvmStoragePool primaryPool = storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
        final KvmPhysicalDisk disk = primaryPool.getPhysicalDisk(command.getVolumePath());
        if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryPool.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);
            if (command.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
                vm.snapshotCreateXML(snapshot);
            } else {
                final DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
                snap.delete(0);
            }
            /*
                 * 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 {
            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());
                    if (command.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
                        s_logger.debug("Attempting to create RBD snapshot " + disk.getName() + "@" + snapshotName);
                        image.snapCreate(snapshotName);
                    } else {
                        s_logger.debug("Attempting to remove RBD snapshot " + disk.getName() + "@" + snapshotName);
                        image.snapRemove(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 int cmdsTimeout = libvirtComputingResource.getCmdsTimeout();
                final String manageSnapshotPath = libvirtComputingResource.manageSnapshotPath();
                final Script scriptCommand = new Script(manageSnapshotPath, cmdsTimeout, s_logger);
                if (command.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
                    scriptCommand.add("-c", disk.getPath());
                } else {
                    scriptCommand.add("-d", snapshotPath);
                }
                scriptCommand.add("-n", snapshotName);
                final String result = scriptCommand.execute();
                if (result != null) {
                    s_logger.debug("Failed to manage snapshot: " + result);
                    return new ManageSnapshotAnswer(command, false, "Failed to manage snapshot: " + result);
                }
            }
        }
        return new ManageSnapshotAnswer(command, command.getSnapshotId(), disk.getPath() + File.separator + snapshotName, true, null);
    } catch (final LibvirtException e) {
        s_logger.debug("Failed to manage snapshot: " + e.toString());
        return new ManageSnapshotAnswer(command, false, "Failed to manage snapshot: " + e.toString());
    }
}
Also used : Script(com.cloud.utils.script.Script) LibvirtException(org.libvirt.LibvirtException) KvmStoragePool(com.cloud.agent.resource.kvm.storage.KvmStoragePool) MessageFormat(java.text.MessageFormat) Connect(org.libvirt.Connect) DomainSnapshot(org.libvirt.DomainSnapshot) Rados(com.ceph.rados.Rados) ManageSnapshotAnswer(com.cloud.legacymodel.communication.answer.ManageSnapshotAnswer) StorageFilerTO(com.cloud.legacymodel.to.StorageFilerTO) LibvirtException(org.libvirt.LibvirtException) DomainState(org.libvirt.DomainInfo.DomainState) Rbd(com.ceph.rbd.Rbd) RbdImage(com.ceph.rbd.RbdImage) KvmStoragePoolManager(com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager) IoCTX(com.ceph.rados.IoCTX) Domain(org.libvirt.Domain) KvmPhysicalDisk(com.cloud.agent.resource.kvm.storage.KvmPhysicalDisk)

Aggregations

DomainState (org.libvirt.DomainInfo.DomainState)38 LibvirtException (org.libvirt.LibvirtException)38 Domain (org.libvirt.Domain)35 Connect (org.libvirt.Connect)31 Test (org.junit.Test)12 DomainInfo (org.libvirt.DomainInfo)12 Script (com.cloud.utils.script.Script)10 IoCTX (com.ceph.rados.IoCTX)8 Rados (com.ceph.rados.Rados)8 Rbd (com.ceph.rbd.Rbd)8 RbdImage (com.ceph.rbd.RbdImage)8 Answer (com.cloud.agent.api.Answer)8 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)8 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)8 IOException (java.io.IOException)8 DomainSnapshot (org.libvirt.DomainSnapshot)8 StopCommand (com.cloud.agent.api.StopCommand)6 LibvirtUtilitiesHelper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper)6 URISyntaxException (java.net.URISyntaxException)6 MessageFormat (java.text.MessageFormat)6