Search in sources :

Example 36 with VBD

use of com.xensource.xenapi.VBD in project cloudstack by apache.

the class CitrixRevertToVMSnapshotCommandWrapper method execute.

@Override
public Answer execute(final RevertToVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
    final String vmName = command.getVmName();
    final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
    final VMSnapshot.Type vmSnapshotType = command.getTarget().getType();
    final Boolean snapshotMemory = vmSnapshotType == VMSnapshot.Type.DiskAndMemory;
    final Connection conn = citrixResourceBase.getConnection();
    PowerState vmState = null;
    VM vm = null;
    try {
        final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
        if (vmSnapshots == null || vmSnapshots.size() == 0) {
            return new RevertToVMSnapshotAnswer(command, false, "Cannot find vmSnapshot with name: " + command.getTarget().getSnapshotName());
        }
        final VM vmSnapshot = vmSnapshots.iterator().next();
        // find target VM or creating a work VM
        try {
            vm = citrixResourceBase.getVM(conn, vmName);
        } catch (final Exception e) {
            vm = citrixResourceBase.createWorkingVM(conn, vmName, command.getGuestOSType(), command.getPlatformEmulator(), listVolumeTo);
        }
        if (vm == null) {
            return new RevertToVMSnapshotAnswer(command, false, "Revert to VM Snapshot Failed due to can not find vm: " + vmName);
        }
        // call plugin to execute revert
        citrixResourceBase.revertToSnapshot(conn, vmSnapshot, vmName, vm.getUuid(conn), snapshotMemory, citrixResourceBase.getHost().getUuid());
        vm = citrixResourceBase.getVM(conn, vmName);
        final Set<VBD> vbds = vm.getVBDs(conn);
        final Map<String, VDI> vdiMap = new HashMap<String, VDI>();
        // get vdi:vbdr to a map
        for (final VBD vbd : vbds) {
            final VBD.Record vbdr = vbd.getRecord(conn);
            if (vbdr.type == Types.VbdType.DISK) {
                final VDI vdi = vbdr.VDI;
                vdiMap.put(vbdr.userdevice, vdi);
            }
        }
        if (!snapshotMemory) {
            vm.destroy(conn);
            vmState = PowerState.PowerOff;
        } else {
            vmState = PowerState.PowerOn;
        }
        // after revert, VM's volumes path have been changed, need to report to manager
        for (final VolumeObjectTO volumeTo : listVolumeTo) {
            final Long deviceId = volumeTo.getDeviceId();
            final VDI vdi = vdiMap.get(deviceId.toString());
            volumeTo.setPath(vdi.getUuid(conn));
        }
        return new RevertToVMSnapshotAnswer(command, listVolumeTo, vmState);
    } catch (final Exception e) {
        s_logger.error("revert vm " + vmName + " to snapshot " + command.getTarget().getSnapshotName() + " failed due to " + e.getMessage());
        return new RevertToVMSnapshotAnswer(command, false, e.getMessage());
    }
}
Also used : RevertToVMSnapshotAnswer(com.cloud.agent.api.RevertToVMSnapshotAnswer) HashMap(java.util.HashMap) Connection(com.xensource.xenapi.Connection) VMSnapshot(com.cloud.vm.snapshot.VMSnapshot) VM(com.xensource.xenapi.VM) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) VBD(com.xensource.xenapi.VBD) VDI(com.xensource.xenapi.VDI) PowerState(com.cloud.vm.VirtualMachine.PowerState)

Example 37 with VBD

use of com.xensource.xenapi.VBD in project cloudstack by apache.

the class CitrixResourceBase method attachConfigDriveIsoToVm.

public boolean attachConfigDriveIsoToVm(final Connection conn, final VM vm) throws XenAPIException, XmlRpcException {
    final String vmName = vm.getNameLabel(conn);
    final String isoURL = _configDriveIsopath + vmName + ".iso";
    VDI srVdi;
    try {
        final Set<VDI> vdis = VDI.getByNameLabel(conn, vmName + ".iso");
        if (vdis.isEmpty()) {
            throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL);
        }
        srVdi = vdis.iterator().next();
    } catch (final XenAPIException e) {
        s_logger.debug("Unable to get config drive iso: " + isoURL + " due to " + e.toString());
        return false;
    } catch (final Exception e) {
        s_logger.debug("Unable to get config drive iso: " + isoURL + " due to " + e.toString());
        return false;
    }
    VBD isoVBD = null;
    // Find the VM's CD-ROM VBD
    final Set<VBD> vbds = vm.getVBDs(conn);
    for (final VBD vbd : vbds) {
        final Types.VbdType type = vbd.getType(conn);
        final VBD.Record vbdr = vbd.getRecord(conn);
        // if the device exists then attach it
        if (!vbdr.userdevice.equals(_attachIsoDeviceNum) && type == Types.VbdType.CD) {
            isoVBD = vbd;
            break;
        }
    }
    if (isoVBD == null) {
        // create vbd
        final VBD.Record cfgDriveVbdr = new VBD.Record();
        cfgDriveVbdr.VM = vm;
        cfgDriveVbdr.empty = true;
        cfgDriveVbdr.bootable = false;
        cfgDriveVbdr.userdevice = "autodetect";
        cfgDriveVbdr.mode = Types.VbdMode.RO;
        cfgDriveVbdr.type = Types.VbdType.CD;
        final VBD cfgDriveVBD = VBD.create(conn, cfgDriveVbdr);
        isoVBD = cfgDriveVBD;
        s_logger.debug("Created CD-ROM VBD for VM: " + vm);
    }
    if (isoVBD != null) {
        // If an ISO is already inserted, eject it
        if (isoVBD.getEmpty(conn) == false) {
            isoVBD.eject(conn);
        }
        try {
            // Insert the new ISO
            isoVBD.insert(conn, srVdi);
            s_logger.debug("Attached config drive iso to vm " + vmName);
        } catch (final XmlRpcException ex) {
            s_logger.debug("Failed to attach config drive iso to vm " + vmName);
            return false;
        }
    }
    return true;
}
Also used : Types(com.xensource.xenapi.Types) XenAPIException(com.xensource.xenapi.Types.XenAPIException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) SAXException(org.xml.sax.SAXException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) MalformedURLException(java.net.MalformedURLException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VBD(com.xensource.xenapi.VBD) VDI(com.xensource.xenapi.VDI) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 38 with VBD

use of com.xensource.xenapi.VBD in project cloudstack by apache.

the class CitrixResourceBase method createPatchVbd.

public VBD createPatchVbd(final Connection conn, final String vmName, final VM vm) throws XmlRpcException, XenAPIException {
    if (_host.getSystemvmisouuid() == null) {
        final SR sr = findPatchIsoSR(conn);
        if (_host.getSystemvmisouuid() == null) {
            final VDI vdi = findPatchIsoVDI(conn, sr);
            if (vdi != null) {
                _host.setSystemvmisouuid(vdi.getRecord(conn).uuid);
            }
        }
        if (_host.getSystemvmisouuid() == null) {
            throw new CloudRuntimeException("can not find systemvmiso");
        }
    }
    final VBD.Record cdromVBDR = new VBD.Record();
    cdromVBDR.VM = vm;
    cdromVBDR.empty = true;
    cdromVBDR.bootable = false;
    cdromVBDR.userdevice = "3";
    cdromVBDR.mode = Types.VbdMode.RO;
    cdromVBDR.type = Types.VbdType.CD;
    final VBD cdromVBD = VBD.create(conn, cdromVBDR);
    cdromVBD.insert(conn, VDI.getByUuid(conn, _host.getSystemvmisouuid()));
    return cdromVBD;
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VBD(com.xensource.xenapi.VBD) VDI(com.xensource.xenapi.VDI) SR(com.xensource.xenapi.SR)

Example 39 with VBD

use of com.xensource.xenapi.VBD in project cloudstack by apache.

the class XenServerStorageProcessor method attachIso.

@Override
public AttachAnswer attachIso(final AttachCommand cmd) {
    final DiskTO disk = cmd.getDisk();
    final DataTO data = disk.getData();
    final DataStoreTO store = data.getDataStore();
    String isoURL = null;
    if (store == null) {
        final TemplateObjectTO iso = (TemplateObjectTO) disk.getData();
        isoURL = iso.getName();
    } else {
        if (!(store instanceof NfsTO)) {
            s_logger.debug("Can't attach a iso which is not created on nfs: ");
            return new AttachAnswer("Can't attach a iso which is not created on nfs: ");
        }
        final NfsTO nfsStore = (NfsTO) store;
        isoURL = nfsStore.getUrl() + nfsStore.getPathSeparator() + data.getPath();
    }
    final String vmName = cmd.getVmName();
    try {
        final Connection conn = hypervisorResource.getConnection();
        VBD isoVBD = null;
        // Find the VM
        final VM vm = hypervisorResource.getVM(conn, vmName);
        // Find the ISO VDI
        final VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, vmName, isoURL);
        // Find the VM's CD-ROM VBD
        final Set<VBD> vbds = vm.getVBDs(conn);
        for (final VBD vbd : vbds) {
            final String userDevice = vbd.getUserdevice(conn);
            final Types.VbdType type = vbd.getType(conn);
            if (userDevice.equals("3") && type == Types.VbdType.CD) {
                isoVBD = vbd;
                break;
            }
        }
        if (isoVBD == null) {
            throw new CloudRuntimeException("Unable to find CD-ROM VBD for VM: " + vmName);
        } else {
            // If an ISO is already inserted, eject it
            if (!isoVBD.getEmpty(conn)) {
                isoVBD.eject(conn);
            }
            // Insert the new ISO
            isoVBD.insert(conn, isoVDI);
        }
        return new AttachAnswer(disk);
    } catch (final XenAPIException e) {
        s_logger.warn("Failed to attach iso" + ": " + e.toString(), e);
        return new AttachAnswer(e.toString());
    } catch (final Exception e) {
        s_logger.warn("Failed to attach iso" + ": " + e.toString(), e);
        return new AttachAnswer(e.toString());
    }
}
Also used : Types(com.xensource.xenapi.Types) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) NfsTO(com.cloud.agent.api.to.NfsTO) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.exception.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataTO(com.cloud.agent.api.to.DataTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VM(com.xensource.xenapi.VM) VBD(com.xensource.xenapi.VBD) VDI(com.xensource.xenapi.VDI) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) DiskTO(com.cloud.agent.api.to.DiskTO) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer)

Example 40 with VBD

use of com.xensource.xenapi.VBD in project cloudstack by apache.

the class CitrixCreateVMSnapshotCommandWrapper method execute.

@Override
public Answer execute(final CreateVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
    final String vmName = command.getVmName();
    final String vmSnapshotName = command.getTarget().getSnapshotName();
    final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
    VmPowerState vmState = VmPowerState.HALTED;
    final String guestOSType = command.getGuestOSType();
    final String platformEmulator = command.getPlatformEmulator();
    final boolean snapshotMemory = command.getTarget().getType() == VMSnapshot.Type.DiskAndMemory;
    final long timeout = command.getWait();
    final Connection conn = citrixResourceBase.getConnection();
    VM vm = null;
    VM vmSnapshot = null;
    boolean success = false;
    try {
        // check if VM snapshot already exists
        final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
        if (vmSnapshots == null || vmSnapshots.size() > 0) {
            return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
        }
        // check if there is already a task for this VM snapshot
        Task task = null;
        Set<Task> tasks = Task.getByNameLabel(conn, "Async.VM.snapshot");
        if (tasks == null) {
            tasks = new LinkedHashSet<>();
        }
        final Set<Task> tasksByName = Task.getByNameLabel(conn, "Async.VM.checkpoint");
        if (tasksByName != null) {
            tasks.addAll(tasksByName);
        }
        for (final Task taskItem : tasks) {
            if (taskItem.getOtherConfig(conn).containsKey("CS_VM_SNAPSHOT_KEY")) {
                final String vmSnapshotTaskName = taskItem.getOtherConfig(conn).get("CS_VM_SNAPSHOT_KEY");
                if (vmSnapshotTaskName != null && vmSnapshotTaskName.equals(command.getTarget().getSnapshotName())) {
                    task = taskItem;
                }
            }
        }
        // create a new task if there is no existing task for this VM snapshot
        if (task == null) {
            try {
                vm = citrixResourceBase.getVM(conn, vmName);
                vmState = vm.getPowerState(conn);
            } catch (final Exception e) {
                if (!snapshotMemory) {
                    vm = citrixResourceBase.createWorkingVM(conn, vmName, guestOSType, platformEmulator, listVolumeTo);
                }
            }
            if (vm == null) {
                return new CreateVMSnapshotAnswer(command, false, "Creating VM Snapshot Failed due to can not find vm: " + vmName);
            }
            // call Xenserver API
            if (!snapshotMemory) {
                task = vm.snapshotAsync(conn, vmSnapshotName);
            } else {
                final Set<VBD> vbds = vm.getVBDs(conn);
                final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
                for (final VBD vbd : vbds) {
                    final VBD.Record vbdr = vbd.getRecord(conn);
                    if (vbdr.userdevice.equals("0")) {
                        final VDI vdi = vbdr.VDI;
                        final SR sr = vdi.getSR(conn);
                        // store memory image on the same SR with ROOT volume
                        pool.setSuspendImageSR(conn, sr);
                    }
                }
                task = vm.checkpointAsync(conn, vmSnapshotName);
            }
            task.addToOtherConfig(conn, "CS_VM_SNAPSHOT_KEY", vmSnapshotName);
        }
        citrixResourceBase.waitForTask(conn, task, 1000, timeout * 1000);
        citrixResourceBase.checkForSuccess(conn, task);
        final String result = task.getResult(conn);
        // extract VM snapshot ref from result
        final String ref = result.substring("<value>".length(), result.length() - "</value>".length());
        vmSnapshot = Types.toVM(ref);
        try {
            Thread.sleep(5000);
        } catch (final InterruptedException ex) {
        }
        // calculate used capacity for this VM snapshot
        for (final VolumeObjectTO volumeTo : command.getVolumeTOs()) {
            try {
                final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName(), vmSnapshotName);
                volumeTo.setSize(size);
            } catch (final CloudRuntimeException cre) {
            }
        }
        success = true;
        return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
    } catch (final Exception e) {
        String msg = "";
        if (e instanceof Types.BadAsyncResult) {
            final String licenseKeyWord = "LICENCE_RESTRICTION";
            final Types.BadAsyncResult errorResult = (Types.BadAsyncResult) e;
            if (errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)) {
                msg = licenseKeyWord;
            }
        } else {
            msg = e.toString();
        }
        s_logger.warn("Creating VM Snapshot " + command.getTarget().getSnapshotName() + " failed due to: " + msg, e);
        return new CreateVMSnapshotAnswer(command, false, msg);
    } finally {
        try {
            if (!success) {
                if (vmSnapshot != null) {
                    s_logger.debug("Delete exsisting VM Snapshot " + vmSnapshotName + " after making VolumeTO failed");
                    final Set<VBD> vbds = vmSnapshot.getVBDs(conn);
                    for (final VBD vbd : vbds) {
                        final VBD.Record vbdr = vbd.getRecord(conn);
                        if (vbdr.type == Types.VbdType.DISK) {
                            final VDI vdi = vbdr.VDI;
                            vdi.destroy(conn);
                        }
                    }
                    vmSnapshot.destroy(conn);
                }
            }
            if (vmState == VmPowerState.HALTED) {
                if (vm != null) {
                    vm.destroy(conn);
                }
            }
        } catch (final Exception e2) {
            s_logger.error("delete snapshot error due to " + e2.getMessage());
        }
    }
}
Also used : Types(com.xensource.xenapi.Types) Task(com.xensource.xenapi.Task) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) VBD(com.xensource.xenapi.VBD) Pool(com.xensource.xenapi.Pool) VDI(com.xensource.xenapi.VDI) SR(com.xensource.xenapi.SR) Connection(com.xensource.xenapi.Connection) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) VM(com.xensource.xenapi.VM) VmPowerState(com.xensource.xenapi.Types.VmPowerState)

Aggregations

VBD (com.xensource.xenapi.VBD)45 VDI (com.xensource.xenapi.VDI)34 VM (com.xensource.xenapi.VM)33 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 Connection (com.xensource.xenapi.Connection)26 XenAPIException (com.xensource.xenapi.Types.XenAPIException)25 XmlRpcException (org.apache.xmlrpc.XmlRpcException)25 SR (com.xensource.xenapi.SR)14 InternalErrorException (com.cloud.exception.InternalErrorException)13 DiskTO (com.cloud.agent.api.to.DiskTO)10 Types (com.xensource.xenapi.Types)10 DataTO (com.cloud.agent.api.to.DataTO)8 IOException (java.io.IOException)8 MalformedURLException (java.net.MalformedURLException)8 URISyntaxException (java.net.URISyntaxException)8 TimeoutException (java.util.concurrent.TimeoutException)8 ConfigurationException (javax.naming.ConfigurationException)8 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)8 SAXException (org.xml.sax.SAXException)8 Answer (com.cloud.agent.api.Answer)6