Search in sources :

Example 16 with Connect

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

the class LibvirtCreateVMSnapshotCommandWrapper method execute.

@Override
public Answer execute(final CreateVMSnapshotCommand cmd, final LibvirtComputingResource libvirtComputingResource) {
    String vmName = cmd.getVmName();
    String vmSnapshotName = cmd.getTarget().getSnapshotName();
    Domain dm = null;
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        Connect conn = libvirtUtilitiesHelper.getConnection();
        dm = libvirtComputingResource.getDomain(conn, vmName);
        if (dm == null) {
            return new CreateVMSnapshotAnswer(cmd, false, "Create VM Snapshot Failed due to can not find vm: " + vmName);
        }
        DomainState domainState = dm.getInfo().state;
        if (domainState != DomainState.VIR_DOMAIN_RUNNING) {
            return new CreateVMSnapshotAnswer(cmd, false, "Create VM Snapshot Failed due to  vm is not running: " + vmName + " with domainState = " + domainState);
        }
        String vmSnapshotXML = "<domainsnapshot>" + "  <name>" + vmSnapshotName + "</name>" + "  <memory snapshot='internal' />" + "</domainsnapshot>";
        dm.snapshotCreateXML(vmSnapshotXML);
        return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
    } catch (LibvirtException e) {
        String msg = " Create VM snapshot failed due to " + e.toString();
        s_logger.warn(msg, e);
        return new CreateVMSnapshotAnswer(cmd, false, msg);
    } finally {
        if (dm != null) {
            try {
                dm.free();
            } catch (LibvirtException l) {
                s_logger.trace("Ignoring libvirt error.", l);
            }
            ;
        }
    }
}
Also used : CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) LibvirtException(org.libvirt.LibvirtException) DomainState(org.libvirt.DomainInfo.DomainState) Connect(org.libvirt.Connect) Domain(org.libvirt.Domain)

Example 17 with Connect

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

the class LibvirtDeleteVMSnapshotCommandWrapper method execute.

@Override
public Answer execute(final DeleteVMSnapshotCommand cmd, final LibvirtComputingResource libvirtComputingResource) {
    String vmName = cmd.getVmName();
    final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
    Domain dm = null;
    DomainSnapshot snapshot = null;
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        Connect conn = libvirtUtilitiesHelper.getConnection();
        dm = libvirtComputingResource.getDomain(conn, vmName);
        snapshot = dm.snapshotLookupByName(cmd.getTarget().getSnapshotName());
        // only remove this snapshot, not children
        snapshot.delete(0);
        return new DeleteVMSnapshotAnswer(cmd, cmd.getVolumeTOs());
    } catch (LibvirtException e) {
        String msg = " Delete VM snapshot failed due to " + e.toString();
        if (dm == null) {
            s_logger.debug("Can not find running vm: " + vmName + ", now we are trying to delete the vm snapshot using qemu-img if the format of root volume is QCOW2");
            VolumeObjectTO rootVolume = null;
            for (VolumeObjectTO volume : cmd.getVolumeTOs()) {
                if (volume.getVolumeType() == Volume.Type.ROOT) {
                    rootVolume = volume;
                    break;
                }
            }
            if (rootVolume != null && ImageFormat.QCOW2.equals(rootVolume.getFormat())) {
                PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) rootVolume.getDataStore();
                KVMPhysicalDisk rootDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), rootVolume.getPath());
                String qemu_img_snapshot = Script.runSimpleBashScript("qemu-img snapshot -l " + rootDisk.getPath() + " | tail -n +3 | awk -F ' ' '{print $2}' | grep ^" + cmd.getTarget().getSnapshotName() + "$");
                if (qemu_img_snapshot == null) {
                    s_logger.info("Cannot find snapshot " + cmd.getTarget().getSnapshotName() + " in file " + rootDisk.getPath() + ", return true");
                    return new DeleteVMSnapshotAnswer(cmd, cmd.getVolumeTOs());
                }
                int result = Script.runSimpleBashScriptForExitValue("qemu-img snapshot -d " + cmd.getTarget().getSnapshotName() + " " + rootDisk.getPath());
                if (result != 0) {
                    return new DeleteVMSnapshotAnswer(cmd, false, "Delete VM Snapshot Failed due to can not remove snapshot from image file " + rootDisk.getPath() + " : " + result);
                } else {
                    return new DeleteVMSnapshotAnswer(cmd, cmd.getVolumeTOs());
                }
            }
        } else if (snapshot == null) {
            s_logger.debug("Can not find vm snapshot " + cmd.getTarget().getSnapshotName() + " on vm: " + vmName + ", return true");
            return new DeleteVMSnapshotAnswer(cmd, cmd.getVolumeTOs());
        }
        s_logger.warn(msg, e);
        return new DeleteVMSnapshotAnswer(cmd, false, msg);
    } finally {
        if (dm != null) {
            try {
                dm.free();
            } catch (LibvirtException l) {
                s_logger.trace("Ignoring libvirt error.", l);
            }
            ;
        }
    }
}
Also used : KVMStoragePoolManager(com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager) LibvirtException(org.libvirt.LibvirtException) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) KVMPhysicalDisk(com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk) Connect(org.libvirt.Connect) DomainSnapshot(org.libvirt.DomainSnapshot) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) DeleteVMSnapshotAnswer(com.cloud.agent.api.DeleteVMSnapshotAnswer) Domain(org.libvirt.Domain)

Example 18 with Connect

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

the class LibvirtCheckVirtualMachineCommandWrapper method execute.

@Override
public Answer execute(final CheckVirtualMachineCommand command, final LibvirtComputingResource libvirtComputingResource) {
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
        final PowerState state = libvirtComputingResource.getVmState(conn, command.getVmName());
        Integer vncPort = null;
        if (state == PowerState.PowerOn) {
            vncPort = libvirtComputingResource.getVncPort(conn, command.getVmName());
        }
        return new CheckVirtualMachineAnswer(command, state, vncPort);
    } catch (final LibvirtException e) {
        return new CheckVirtualMachineAnswer(command, e.getMessage());
    }
}
Also used : CheckVirtualMachineAnswer(com.cloud.agent.api.CheckVirtualMachineAnswer) LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) PowerState(com.cloud.vm.VirtualMachine.PowerState)

Example 19 with Connect

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

the class LibvirtGetVmDiskStatsCommandWrapper method execute.

@Override
public Answer execute(final GetVmDiskStatsCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final List<String> vmNames = command.getVmNames();
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
    try {
        final HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsNameMap = new HashMap<String, List<VmDiskStatsEntry>>();
        final Connect conn = libvirtUtilitiesHelper.getConnection();
        for (final String vmName : vmNames) {
            try {
                final List<VmDiskStatsEntry> statEntry = libvirtComputingResource.getVmDiskStat(conn, vmName);
                if (statEntry == null) {
                    continue;
                }
                vmDiskStatsNameMap.put(vmName, statEntry);
            } catch (LibvirtException e) {
                s_logger.warn("Can't get vm disk stats: " + e.toString() + ", continue");
            }
        }
        return new GetVmDiskStatsAnswer(command, "", command.getHostName(), vmDiskStatsNameMap);
    } catch (final LibvirtException e) {
        s_logger.debug("Can't get vm disk stats: " + e.toString());
        return new GetVmDiskStatsAnswer(command, null, null, null);
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) HashMap(java.util.HashMap) Connect(org.libvirt.Connect) List(java.util.List) VmDiskStatsEntry(com.cloud.agent.api.VmDiskStatsEntry) GetVmDiskStatsAnswer(com.cloud.agent.api.GetVmDiskStatsAnswer)

Example 20 with Connect

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

the class LibvirtComputingResource method cleanupNetworkElementCommand.

protected ExecutionResult cleanupNetworkElementCommand(final IpAssocCommand cmd) {
    final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
    final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
    final String lastIp = cmd.getAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP);
    Connect conn;
    try {
        conn = LibvirtConnection.getConnectionByVmName(routerName);
        final List<InterfaceDef> nics = getInterfaces(conn, routerName);
        final Map<String, Integer> broadcastUriAllocatedToVM = new HashMap<String, Integer>();
        Integer nicPos = 0;
        for (final InterfaceDef nic : nics) {
            if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) {
                broadcastUriAllocatedToVM.put("LinkLocal", nicPos);
            } else {
                if (nic.getBrName().equalsIgnoreCase(_publicBridgeName) || nic.getBrName().equalsIgnoreCase(_privBridgeName) || nic.getBrName().equalsIgnoreCase(_guestBridgeName)) {
                    broadcastUriAllocatedToVM.put(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED).toString(), nicPos);
                } else {
                    final String broadcastUri = getBroadcastUriFromBridge(nic.getBrName());
                    broadcastUriAllocatedToVM.put(broadcastUri, nicPos);
                }
            }
            nicPos++;
        }
        final IpAddressTO[] ips = cmd.getIpAddresses();
        final int numOfIps = ips.length;
        int nicNum = 0;
        for (final IpAddressTO ip : ips) {
            if (!broadcastUriAllocatedToVM.containsKey(ip.getBroadcastUri())) {
                /* plug a vif into router */
                VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress());
                broadcastUriAllocatedToVM.put(ip.getBroadcastUri(), nicPos++);
            }
            nicNum = broadcastUriAllocatedToVM.get(ip.getBroadcastUri());
            if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(lastIp, "true") && !ip.isAdd()) {
                // in isolated network eth2 is the default public interface. We don't want to delete it.
                if (nicNum != 2) {
                    vifHotUnPlug(conn, routerName, ip.getVifMacAddress());
                    networkUsage(routerIp, "deleteVif", "eth" + nicNum);
                }
            }
        }
    } catch (final LibvirtException e) {
        s_logger.error("ipassoccmd failed", e);
        return new ExecutionResult(false, e.getMessage());
    } catch (final InternalErrorException e) {
        s_logger.error("ipassoccmd failed", e);
        return new ExecutionResult(false, e.getMessage());
    }
    return new ExecutionResult(true, null);
}
Also used : IpAddressTO(com.cloud.agent.api.to.IpAddressTO) LibvirtException(org.libvirt.LibvirtException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Connect(org.libvirt.Connect) ExecutionResult(com.cloud.utils.ExecutionResult) InternalErrorException(com.cloud.exception.InternalErrorException) InterfaceDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef)

Aggregations

Connect (org.libvirt.Connect)113 LibvirtException (org.libvirt.LibvirtException)112 Answer (com.cloud.agent.api.Answer)47 AttachAnswer (org.apache.cloudstack.storage.command.AttachAnswer)42 Test (org.junit.Test)40 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)39 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)39 LibvirtUtilitiesHelper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper)39 InternalErrorException (com.cloud.exception.InternalErrorException)33 Domain (org.libvirt.Domain)30 URISyntaxException (java.net.URISyntaxException)25 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)24 NicTO (com.cloud.agent.api.to.NicTO)23 InterfaceDef (com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef)22 KVMStoragePoolManager (com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager)19 VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)16 ConfigurationException (javax.naming.ConfigurationException)15 ArrayList (java.util.ArrayList)14 IOException (java.io.IOException)13 HashMap (java.util.HashMap)11