Search in sources :

Example 16 with Task

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

the class Xenserver625StorageProcessor method createTemplateFromSnapshot.

@Override
public Answer createTemplateFromSnapshot(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final DataTO srcData = cmd.getSrcTO();
    final DataTO destData = cmd.getDestTO();
    if (srcData.getDataStore() instanceof PrimaryDataStoreTO && destData.getDataStore() instanceof NfsTO) {
        return createTemplateFromSnapshot2(cmd);
    }
    final int wait = cmd.getWait();
    final SnapshotObjectTO srcObj = (SnapshotObjectTO) srcData;
    final TemplateObjectTO destObj = (TemplateObjectTO) destData;
    final NfsTO srcStore = (NfsTO) srcObj.getDataStore();
    final NfsTO destStore = (NfsTO) destObj.getDataStore();
    URI srcUri = null;
    URI destUri = null;
    try {
        srcUri = new URI(srcStore.getUrl());
        destUri = new URI(destStore.getUrl());
    } catch (final Exception e) {
        s_logger.debug("incorrect url", e);
        return new CopyCmdAnswer("incorrect url" + e.toString());
    }
    final String srcPath = srcObj.getPath();
    final int index = srcPath.lastIndexOf("/");
    final String srcDir = srcPath.substring(0, index);
    final String destDir = destObj.getPath();
    SR srcSr = null;
    SR destSr = null;
    VDI destVdi = null;
    boolean result = false;
    try {
        srcSr = createFileSr(conn, srcUri.getHost() + ":" + srcUri.getPath(), srcDir);
        final String destNfsPath = destUri.getHost() + ":" + destUri.getPath();
        final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(destNfsPath.getBytes());
        mountNfs(conn, destUri.getHost() + ":" + destUri.getPath(), localDir);
        makeDirectory(conn, localDir + "/" + destDir);
        destSr = createFileSR(conn, localDir + "/" + destDir);
        final String nameLabel = "cloud-" + UUID.randomUUID().toString();
        final String[] parents = srcObj.getParents();
        final List<VDI> snapshotChains = new ArrayList<VDI>();
        if (parents != null) {
            for (int i = 0; i < parents.length; i++) {
                final String snChainPath = parents[i];
                final String uuid = getSnapshotUuid(snChainPath);
                final VDI chain = VDI.getByUuid(conn, uuid);
                snapshotChains.add(chain);
            }
        }
        final String snapshotUuid = getSnapshotUuid(srcPath);
        final VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid);
        snapshotChains.add(snapshotVdi);
        final long templateVirtualSize = snapshotChains.get(0).getVirtualSize(conn);
        destVdi = createVdi(conn, nameLabel, destSr, templateVirtualSize);
        final String destVdiUuid = destVdi.getUuid(conn);
        for (final VDI snapChain : snapshotChains) {
            final Task task = snapChain.copyAsync(conn, null, null, destVdi);
            // poll every 1 seconds ,
            hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
            hypervisorResource.checkForSuccess(conn, task);
            task.destroy(conn);
        }
        destVdi = VDI.getByUuid(conn, destVdiUuid);
        // scan makes XenServer pick up VDI physicalSize
        destSr.scan(conn);
        final String templateUuid = destVdi.getUuid(conn);
        final String templateFilename = templateUuid + ".vhd";
        final long virtualSize = destVdi.getVirtualSize(conn);
        final long physicalSize = destVdi.getPhysicalUtilisation(conn);
        String templatePath = destNfsPath + "/" + destDir;
        templatePath = templatePath.replaceAll("//", "/");
        result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, templateFilename, templateUuid, nameLabel, null, physicalSize, virtualSize, destObj.getId());
        if (!result) {
            throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir");
        }
        final TemplateObjectTO newTemplate = new TemplateObjectTO();
        newTemplate.setPath(destDir + "/" + templateFilename);
        newTemplate.setFormat(Storage.ImageFormat.VHD);
        newTemplate.setSize(destVdi.getVirtualSize(conn));
        newTemplate.setPhysicalSize(destVdi.getPhysicalUtilisation(conn));
        newTemplate.setName(destVdiUuid);
        result = true;
        return new CopyCmdAnswer(newTemplate);
    } catch (final Exception e) {
        s_logger.error("Failed create template from snapshot", e);
        return new CopyCmdAnswer("Failed create template from snapshot " + e.toString());
    } finally {
        if (!result) {
            if (destVdi != null) {
                try {
                    destVdi.destroy(conn);
                } catch (final Exception e) {
                    s_logger.debug("Clean up left over on dest storage failed: ", e);
                }
            }
        }
        if (srcSr != null) {
            hypervisorResource.removeSR(conn, srcSr);
        }
        if (destSr != null) {
            hypervisorResource.removeSR(conn, destSr);
        }
    }
}
Also used : SnapshotObjectTO(org.apache.cloudstack.storage.to.SnapshotObjectTO) Task(com.xensource.xenapi.Task) Connection(com.xensource.xenapi.Connection) ArrayList(java.util.ArrayList) NfsTO(com.cloud.agent.api.to.NfsTO) URI(java.net.URI) InternalErrorException(com.cloud.exception.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VDI(com.xensource.xenapi.VDI) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) SR(com.xensource.xenapi.SR)

Example 17 with Task

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

the class XenServer610MigrateWithStorageCommandWrapper method execute.

@Override
public Answer execute(final MigrateWithStorageCommand command, final XenServer610Resource xenServer610Resource) {
    final Connection connection = xenServer610Resource.getConnection();
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final List<Pair<VolumeTO, StorageFilerTO>> volumeToFiler = command.getVolumeToFilerAsList();
    final String vmName = vmSpec.getName();
    Task task = null;
    final XsHost xsHost = xenServer610Resource.getHost();
    final String uuid = xsHost.getUuid();
    try {
        xenServer610Resource.prepareISO(connection, vmName, null, null);
        // Get the list of networks and recreate VLAN, if required.
        for (final NicTO nicTo : vmSpec.getNics()) {
            xenServer610Resource.getNetwork(connection, nicTo);
        }
        final Map<String, String> other = new HashMap<String, String>();
        other.put("live", "true");
        final XsLocalNetwork nativeNetworkForTraffic = xenServer610Resource.getNativeNetworkForTraffic(connection, TrafficType.Storage, null);
        final Network networkForSm = nativeNetworkForTraffic.getNetwork();
        // Create the vif map. The  vm stays in the same cluster so we have to pass an empty vif map.
        final Map<VIF, Network> vifMap = new HashMap<VIF, Network>();
        final Map<VDI, SR> vdiMap = new HashMap<VDI, SR>();
        for (final Pair<VolumeTO, StorageFilerTO> entry : volumeToFiler) {
            final StorageFilerTO storageFiler = entry.second();
            final VolumeTO volume = entry.first();
            vdiMap.put(xenServer610Resource.getVDIbyUuid(connection, volume.getPath()), xenServer610Resource.getStorageRepository(connection, storageFiler.getUuid()));
        }
        // Get the vm to migrate.
        final Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
        final VM vmToMigrate = vms.iterator().next();
        // Check migration with storage is possible.
        final Host host = Host.getByUuid(connection, uuid);
        final Map<String, String> token = host.migrateReceive(connection, networkForSm, other);
        task = vmToMigrate.assertCanMigrateAsync(connection, token, true, vdiMap, vifMap, other);
        try {
            // poll every 1 seconds
            final long timeout = xenServer610Resource.getMigrateWait() * 1000L;
            xenServer610Resource.waitForTask(connection, task, 1000, timeout);
            xenServer610Resource.checkForSuccess(connection, task);
        } catch (final Types.HandleInvalid e) {
            s_logger.error("Error while checking if vm " + vmName + " can be migrated to the destination host " + host, e);
            throw new CloudRuntimeException("Error while checking if vm " + vmName + " can be migrated to the " + "destination host " + host, e);
        }
        // Migrate now.
        task = vmToMigrate.migrateSendAsync(connection, token, true, vdiMap, vifMap, other);
        try {
            // poll every 1 seconds.
            final long timeout = xenServer610Resource.getMigrateWait() * 1000L;
            xenServer610Resource.waitForTask(connection, task, 1000, timeout);
            xenServer610Resource.checkForSuccess(connection, task);
        } catch (final Types.HandleInvalid e) {
            s_logger.error("Error while migrating vm " + vmName + " to the destination host " + host, e);
            throw new CloudRuntimeException("Error while migrating vm " + vmName + " to the destination host " + host, e);
        }
        // Volume paths would have changed. Return that information.
        final List<VolumeObjectTO> volumeToList = xenServer610Resource.getUpdatedVolumePathsOfMigratedVm(connection, vmToMigrate, vmSpec.getDisks());
        vmToMigrate.setAffinity(connection, host);
        return new MigrateWithStorageAnswer(command, volumeToList);
    } catch (final Exception e) {
        s_logger.warn("Catch Exception " + e.getClass().getName() + ". Storage motion failed due to " + e.toString(), e);
        return new MigrateWithStorageAnswer(command, e);
    } finally {
        if (task != null) {
            try {
                task.destroy(connection);
            } catch (final Exception e) {
                s_logger.debug("Unable to destroy task " + task.toString() + " on host " + uuid + " due to " + e.toString());
            }
        }
    }
}
Also used : Types(com.xensource.xenapi.Types) Task(com.xensource.xenapi.Task) XsHost(com.cloud.hypervisor.xenserver.resource.XsHost) HashMap(java.util.HashMap) StorageFilerTO(com.cloud.agent.api.to.StorageFilerTO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) VolumeTO(com.cloud.agent.api.to.VolumeTO) XsLocalNetwork(com.cloud.hypervisor.xenserver.resource.XsLocalNetwork) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.xensource.xenapi.Network) XsLocalNetwork(com.cloud.hypervisor.xenserver.resource.XsLocalNetwork) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) VDI(com.xensource.xenapi.VDI) Pair(com.cloud.utils.Pair) NicTO(com.cloud.agent.api.to.NicTO) SR(com.xensource.xenapi.SR) MigrateWithStorageAnswer(com.cloud.agent.api.MigrateWithStorageAnswer) Connection(com.xensource.xenapi.Connection) Host(com.xensource.xenapi.Host) XsHost(com.cloud.hypervisor.xenserver.resource.XsHost) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VIF(com.xensource.xenapi.VIF) VM(com.xensource.xenapi.VM)

Example 18 with Task

use of com.xensource.xenapi.Task 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()) {
            final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName());
            volumeTo.setSize(size);
        }
        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) Connection(com.xensource.xenapi.Connection) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) VM(com.xensource.xenapi.VM) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) VBD(com.xensource.xenapi.VBD) Pool(com.xensource.xenapi.Pool) VDI(com.xensource.xenapi.VDI) VmPowerState(com.xensource.xenapi.Types.VmPowerState) SR(com.xensource.xenapi.SR)

Example 19 with Task

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

the class Xenserver625StorageProcessor method backupSnapshot.

@Override
public Answer backupSnapshot(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final DataTO srcData = cmd.getSrcTO();
    final DataTO cacheData = cmd.getCacheTO();
    final DataTO destData = cmd.getDestTO();
    final int wait = cmd.getWait();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore();
    final String primaryStorageNameLabel = primaryStore.getUuid();
    String secondaryStorageUrl = null;
    NfsTO cacheStore = null;
    String destPath = null;
    if (cacheData != null) {
        cacheStore = (NfsTO) cacheData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = cacheData.getPath();
    } else {
        cacheStore = (NfsTO) destData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = destData.getPath();
    }
    final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData;
    final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData;
    String snapshotUuid = snapshotTO.getPath();
    final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
    final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
    final Map<String, String> options = cmd.getOptions();
    // By default assume failure
    String details = null;
    String snapshotBackupUuid = null;
    boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
    Long physicalSize = null;
    try {
        SR primaryStorageSR = null;
        if (primaryStore.isManaged()) {
            // currently, managed storage only supports full backup
            fullbackup = true;
            final Map<String, String> srcDetails = cmd.getOptions();
            final String iScsiName = srcDetails.get(DiskTO.IQN);
            final String storageHost = srcDetails.get(DiskTO.STORAGE_HOST);
            final String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME);
            final String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET);
            final String srType = CitrixResourceBase.SRType.LVMOISCSI.toString();
            primaryStorageSR = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, false, srType, true);
            final VDI srcVdi = primaryStorageSR.getVDIs(conn).iterator().next();
            if (srcVdi == null) {
                throw new InternalErrorException("Could not Find a VDI on the SR: " + primaryStorageSR.getNameLabel(conn));
            }
            snapshotUuid = srcVdi.getUuid(conn);
        } else {
            primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
        }
        if (primaryStorageSR == null) {
            throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel);
        }
        // String psUuid = primaryStorageSR.getUuid(conn);
        final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));
        final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
        final String snapshotPaUuid = snapshotVdi.getUuid(conn);
        final URI uri = new URI(secondaryStorageUrl);
        final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
        final DataStoreTO destStore = destData.getDataStore();
        final String folder = destPath;
        String finalPath = null;
        final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
        if (fullbackup) {
            SR snapshotSr = null;
            Task task = null;
            try {
                final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes());
                mountNfs(conn, secondaryStorageMountPath, localDir);
                final boolean result = makeDirectory(conn, localDir + "/" + folder);
                if (!result) {
                    details = " Filed to create folder " + folder + " in secondary storage";
                    s_logger.warn(details);
                    return new CopyCmdAnswer(details);
                }
                snapshotSr = createFileSr(conn, secondaryStorageMountPath, folder);
                task = snapshotVdi.copyAsync(conn, snapshotSr, null, null);
                // poll every 1 seconds ,
                hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
                hypervisorResource.checkForSuccess(conn, task);
                final VDI backedVdi = Types.toVDI(task, conn);
                snapshotBackupUuid = backedVdi.getUuid(conn);
                physicalSize = backedVdi.getPhysicalUtilisation(conn);
                if (destStore instanceof SwiftTO) {
                    try {
                        final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                        final String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait);
                        final String swiftPath = container + File.separator + destSnapshotName;
                        finalPath = swiftPath;
                    } finally {
                        try {
                            deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid);
                        } catch (final Exception e) {
                            s_logger.debug("Failed to delete snapshot on cache storages", e);
                        }
                    }
                } else if (destStore instanceof S3TO) {
                    try {
                        finalPath = backupSnapshotToS3(conn, (S3TO) destStore, snapshotSr.getUuid(conn), folder, snapshotBackupUuid, isISCSI, wait);
                        if (finalPath == null) {
                            throw new CloudRuntimeException("S3 upload of snapshots " + snapshotBackupUuid + " failed");
                        }
                    } finally {
                        try {
                            deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid);
                        } catch (final Exception e) {
                            s_logger.debug("Failed to delete snapshot on cache storages", e);
                        }
                    }
                // finalPath = folder + File.separator +
                // snapshotBackupUuid;
                } else {
                    finalPath = folder + File.separator + snapshotBackupUuid + ".vhd";
                }
            } finally {
                if (task != null) {
                    try {
                        task.destroy(conn);
                    } catch (final Exception e) {
                        s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString());
                    }
                }
                if (snapshotSr != null) {
                    hypervisorResource.removeSR(conn, snapshotSr);
                }
                if (primaryStore.isManaged()) {
                    hypervisorResource.removeSR(conn, primaryStorageSR);
                }
            }
        } else {
            final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
            if (destStore instanceof SwiftTO) {
                final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait);
                finalPath = container + File.separator + snapshotBackupUuid;
            } else if (destStore instanceof S3TO) {
                finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder, snapshotPaUuid, isISCSI, wait);
                if (finalPath == null) {
                    throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed");
                }
            } else {
                final String result = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI, wait);
                final String[] tmp = result.split("#");
                snapshotBackupUuid = tmp[0];
                physicalSize = Long.parseLong(tmp[1]);
                finalPath = folder + File.separator + snapshotBackupUuid + ".vhd";
            }
            final String volumeUuid = snapshotTO.getVolume().getPath();
            destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);
        }
        final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(finalPath);
        newSnapshot.setPhysicalSize(physicalSize);
        if (fullbackup) {
            newSnapshot.setParentSnapshotPath(null);
        } else {
            newSnapshot.setParentSnapshotPath(prevBackupUuid);
        }
        return new CopyCmdAnswer(newSnapshot);
    } catch (final Types.XenAPIException e) {
        details = "BackupSnapshot Failed due to " + e.toString();
        s_logger.warn(details, e);
    } catch (final Exception e) {
        details = "BackupSnapshot Failed due to " + e.getMessage();
        s_logger.warn(details, e);
    }
    return new CopyCmdAnswer(details);
}
Also used : SnapshotObjectTO(org.apache.cloudstack.storage.to.SnapshotObjectTO) Types(com.xensource.xenapi.Types) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) Task(com.xensource.xenapi.Task) SwiftTO(com.cloud.agent.api.to.SwiftTO) Connection(com.xensource.xenapi.Connection) InternalErrorException(com.cloud.exception.InternalErrorException) NfsTO(com.cloud.agent.api.to.NfsTO) URI(java.net.URI) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.exception.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VDI(com.xensource.xenapi.VDI) S3TO(com.cloud.agent.api.to.S3TO) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) SR(com.xensource.xenapi.SR)

Example 20 with Task

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

the class Xenserver625StorageProcessor method copyVolumeFromImageCacheToPrimary.

@Override
public Answer copyVolumeFromImageCacheToPrimary(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final DataTO srcData = cmd.getSrcTO();
    final DataTO destData = cmd.getDestTO();
    final int wait = cmd.getWait();
    final VolumeObjectTO srcVolume = (VolumeObjectTO) srcData;
    final VolumeObjectTO destVolume = (VolumeObjectTO) destData;
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) destVolume.getDataStore();
    final DataStoreTO srcStore = srcVolume.getDataStore();
    if (srcStore instanceof NfsTO) {
        final NfsTO nfsStore = (NfsTO) srcStore;
        final String volumePath = srcVolume.getPath();
        int index = volumePath.lastIndexOf("/");
        final String volumeDirectory = volumePath.substring(0, index);
        String volumeUuid = volumePath.substring(index + 1);
        index = volumeUuid.indexOf(".");
        if (index != -1) {
            volumeUuid = volumeUuid.substring(0, index);
        }
        URI uri = null;
        try {
            uri = new URI(nfsStore.getUrl());
        } catch (final Exception e) {
            return new CopyCmdAnswer(e.toString());
        }
        final SR srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), volumeDirectory);
        Task task = null;
        try {
            final SR primaryStoragePool = hypervisorResource.getStorageRepository(conn, primaryStore.getUuid());
            final VDI srcVdi = VDI.getByUuid(conn, volumeUuid);
            task = srcVdi.copyAsync(conn, primaryStoragePool, null, null);
            // poll every 1 seconds ,
            hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
            hypervisorResource.checkForSuccess(conn, task);
            final VDI destVdi = Types.toVDI(task, conn);
            final VolumeObjectTO newVol = new VolumeObjectTO();
            destVdi.setNameLabel(conn, srcVolume.getName());
            newVol.setPath(destVdi.getUuid(conn));
            newVol.setSize(srcVolume.getSize());
            return new CopyCmdAnswer(newVol);
        } catch (final Exception e) {
            final String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString();
            s_logger.warn(msg, e);
            return new CopyCmdAnswer(e.toString());
        } finally {
            if (task != null) {
                try {
                    task.destroy(conn);
                } catch (final Exception e) {
                    s_logger.warn("unable to destroy task(" + task.toString() + ") due to " + e.toString());
                }
            }
            if (srcSr != null) {
                hypervisorResource.removeSR(conn, srcSr);
            }
        }
    }
    s_logger.debug("unsupported protocol");
    return new CopyCmdAnswer("unsupported protocol");
}
Also used : DataStoreTO(com.cloud.agent.api.to.DataStoreTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) Task(com.xensource.xenapi.Task) Connection(com.xensource.xenapi.Connection) NfsTO(com.cloud.agent.api.to.NfsTO) URI(java.net.URI) InternalErrorException(com.cloud.exception.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) VDI(com.xensource.xenapi.VDI) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) SR(com.xensource.xenapi.SR)

Aggregations

Task (com.xensource.xenapi.Task)21 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)17 XenAPIException (com.xensource.xenapi.Types.XenAPIException)16 XmlRpcException (org.apache.xmlrpc.XmlRpcException)16 InternalErrorException (com.cloud.exception.InternalErrorException)15 VDI (com.xensource.xenapi.VDI)14 SR (com.xensource.xenapi.SR)13 Connection (com.xensource.xenapi.Connection)12 Types (com.xensource.xenapi.Types)10 TimeoutException (java.util.concurrent.TimeoutException)8 NfsTO (com.cloud.agent.api.to.NfsTO)7 IOException (java.io.IOException)7 MalformedURLException (java.net.MalformedURLException)7 URI (java.net.URI)7 URISyntaxException (java.net.URISyntaxException)7 HashMap (java.util.HashMap)7 ConfigurationException (javax.naming.ConfigurationException)7 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 CopyCmdAnswer (org.apache.cloudstack.storage.command.CopyCmdAnswer)7 SAXException (org.xml.sax.SAXException)7