Package org.apache.cloudstack.storage.to

Examples of org.apache.cloudstack.storage.to.SnapshotObjectTO


                if (!answer.getResult()) {
                    return answer;
                }
                NfsTO cacheStore = (NfsTO)cmd.getCacheTO().getDataStore();
                String parentPath = storageResource.getRootDir(cacheStore.getUrl());
                SnapshotObjectTO newSnapshot = (SnapshotObjectTO)answer.getNewData();
                String path = newSnapshot.getPath();
                int index = path.lastIndexOf(File.separator);
                String name = path.substring(index + 1);
                String dir = path.substring(0, index);
                storageManager.createOva(parentPath + File.separator + dir, name);
                newSnapshot.setPath(newSnapshot.getPath() + ".ova");
                newSnapshot.setDataStore(cmd.getCacheTO().getDataStore());
                CopyCommand newCmd = new CopyCommand(newSnapshot, destData, cmd.getWait(), cmd.executeInSequence());
                Answer result = storageResource.defaultAction(newCmd);

                //clean up data on staging area
                try {
                    newSnapshot.setPath(path);
                    DeleteCommand deleteCommand = new DeleteCommand(newSnapshot);
                    storageResource.defaultAction(deleteCommand);
                } catch (Exception e) {
                    s_logger.debug("Failed to clean up staging area:", e);
                }
View Full Code Here


        }
    }

    @Override
    public Answer createTemplateFromSnapshot(CopyCommand cmd) {
        SnapshotObjectTO snapshot = (SnapshotObjectTO)cmd.getSrcTO();
        TemplateObjectTO template = (TemplateObjectTO)cmd.getDestTO();
        DataStoreTO imageStore = template.getDataStore();
        String details;
        String uniqeName = UUID.randomUUID().toString();

        VmwareContext context = hostService.getServiceContext(cmd);
        try {
            if (!(imageStore instanceof  NfsTO)) {
                return new CopyCmdAnswer("Only support create template from snapshot, when the dest store is nfs");
            }

            NfsTO nfsSvr = (NfsTO)imageStore;
            Ternary<String, Long, Long> result = createTemplateFromSnapshot(template.getPath(),
                    uniqeName,
                    nfsSvr.getUrl(), snapshot.getPath(),
                    template.getId()
                    );

            TemplateObjectTO newTemplate = new TemplateObjectTO();
            newTemplate.setPath(result.first());
View Full Code Here

        return new Ternary<String, String, String[]>(backupUuid + "/" + backupUuid, snapshotInfo.first(), snapshotInfo.second());
    }

    @Override
    public Answer backupSnapshot(CopyCommand cmd) {
        SnapshotObjectTO srcSnapshot = (SnapshotObjectTO)cmd.getSrcTO();
        PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)srcSnapshot.getDataStore();
        SnapshotObjectTO destSnapshot = (SnapshotObjectTO)cmd.getDestTO();
        DataStoreTO destStore = destSnapshot.getDataStore();
        if (!(destStore instanceof NfsTO)) {
            return new CopyCmdAnswer("unsupported protocol");
        }

        NfsTO destNfsStore = (NfsTO)destStore;

        String secondaryStorageUrl = destNfsStore.getUrl();
        String snapshotUuid = srcSnapshot.getPath();
        String prevSnapshotUuid = srcSnapshot.getParentSnapshotPath();
        String prevBackupUuid = destSnapshot.getParentSnapshotPath();
        VirtualMachineMO workerVm=null;
        String workerVMName = null;
        String volumePath = srcSnapshot.getVolume().getPath();
        ManagedObjectReference morDs = null;
        DatastoreMO dsMo=null;

        // By default assume failure
        String details = null;
        boolean success = false;
        String snapshotBackupUuid = null;
       
        boolean hasOwnerVm = false;
        Ternary<String, String, String[]> backupResult = null;

        VmwareContext context = hostService.getServiceContext(cmd);
        VirtualMachineMO vmMo = null;
        String vmName = srcSnapshot.getVmName();
        try {
            VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
            morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());

            CopyCmdAnswer answer = null;
           
            try {
                if (vmName != null) {
                    vmMo = hyperHost.findVmOnHyperHost(vmName);
                }
                if (vmMo == null) {
                    if(s_logger.isDebugEnabled()) {
                        s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter");
                    }
                    if (vmName != null) {
                        vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
                    }
                    if(vmMo == null) {
                        dsMo = new DatastoreMO(hyperHost.getContext(), morDs);

                        workerVMName = hostService.getWorkerName(context, cmd, 0);

                        vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, workerVMName);

                        if (vmMo == null) {
                            throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName);
                        }
                        workerVm = vmMo;

                        // attach volume to worker VM
                        String datastoreVolumePath = dsMo.getDatastorePath(volumePath + ".vmdk");
                        vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs);
                    } else {
                      s_logger.info("Using owner VM " + vmName + " for snapshot operation");
                      hasOwnerVm = true;
                    }
                } else {
                  s_logger.info("Using owner VM " + vmName + " for snapshot operation");
                  hasOwnerVm = true;
                }

                if (!vmMo.createSnapshot(snapshotUuid, "Snapshot taken for " + srcSnapshot.getName(), false, false)) {
                    throw new Exception("Failed to take snapshot " + srcSnapshot.getName() + " on vm: " + vmName);
                }

                backupResult = backupSnapshotToSecondaryStorage(vmMo, destSnapshot.getPath(), srcSnapshot.getVolume().getPath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid,
                        hostService.getWorkerName(context, cmd, 1));
                snapshotBackupUuid = backupResult.first();

                success = (snapshotBackupUuid != null);
                if (!success) {
                    details = "Failed to backUp the snapshot with uuid: " + snapshotUuid + " to secondary storage.";
                    answer = new CopyCmdAnswer(details);
                } else {
                    details = "Successfully backedUp the snapshot with Uuid: " + snapshotUuid + " to secondary storage.";
                    SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
                    newSnapshot.setPath(destSnapshot.getPath() + "/" + snapshotBackupUuid);
                    answer = new CopyCmdAnswer(newSnapshot);
                }
            } finally {
                if(vmMo != null){
                    ManagedObjectReference snapshotMor = vmMo.getSnapshotMor(snapshotUuid);
                    if (snapshotMor != null) {
                        vmMo.removeSnapshot(snapshotUuid, false);
                       
                        // Snapshot operation may cause disk consolidation in VMware, when this happens
                        // we need to update CloudStack DB
                        //
                        // TODO: this post operation fixup is not atomic and not safe when management server stops
                        // in the middle
                        if(backupResult != null && hasOwnerVm) {
                          s_logger.info("Check if we have disk consolidation after snapshot operation");
                         
                          boolean chainConsolidated = false;
                          for(String vmdkDsFilePath : backupResult.third()) {
                            s_logger.info("Validate disk chain file:" + vmdkDsFilePath);
                           
                            if(vmMo.getDiskDevice(vmdkDsFilePath, false) == null) {
                              s_logger.info("" + vmdkDsFilePath + " no longer exists, consolidation detected");
                              chainConsolidated = true;
                              break;
                            } else {
                              s_logger.info("" + vmdkDsFilePath + " is found still in chain");
                            }
                          }
                         
                          if(chainConsolidated) {
                            String topVmdkFilePath = null;
                            try {
                              topVmdkFilePath = vmMo.getDiskCurrentTopBackingFileInChain(backupResult.second());
                            } catch(Exception e) {
                              s_logger.error("Unexpected exception", e);
                            }
                           
                            s_logger.info("Disk has been consolidated, top VMDK is now: " + topVmdkFilePath);
                            if(topVmdkFilePath != null) {
                              DatastoreFile file = new DatastoreFile(topVmdkFilePath);
                             
                              SnapshotObjectTO snapshotInfo = (SnapshotObjectTO)answer.getNewData();
                              VolumeObjectTO vol = new VolumeObjectTO();
                              vol.setUuid(srcSnapshot.getVolume().getUuid());
                              vol.setPath(file.getFileBaseName());
                              snapshotInfo.setVolume(vol);
                            } else {
                              s_logger.error("Disk has been consolidated, but top VMDK is not found ?!");
                            }
                          }
                        }
View Full Code Here

    @Override
    public Answer createSnapshot(CreateObjectCommand cmd) {
        // snapshot operation (create or destroy) is handled inside BackupSnapshotCommand(), we just fake
        // a success return here
        String snapshotUUID = UUID.randomUUID().toString();
        SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(snapshotUUID);
        return new CreateObjectAnswer(newSnapshot);
    }
View Full Code Here

    }

    @Override
    public Answer createVolumeFromSnapshot(CopyCommand cmd) {
        DataTO srcData = cmd.getSrcTO();
        SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData;
        DataTO destData = cmd.getDestTO();
        PrimaryDataStoreTO pool = (PrimaryDataStoreTO)destData.getDataStore();
        DataStoreTO imageStore = srcData.getDataStore();


        if (!(imageStore instanceof NfsTO)) {
            return new CopyCmdAnswer("unsupported protocol");
        }

        NfsTO nfsImageStore = (NfsTO)imageStore;
        String primaryStorageNameLabel = pool.getUuid();

        String secondaryStorageUrl = nfsImageStore.getUrl();
        String backedUpSnapshotUuid = snapshot.getPath();
        int index = backedUpSnapshotUuid.lastIndexOf(File.separator);
        String backupPath = backedUpSnapshotUuid.substring(0, index);
        backedUpSnapshotUuid = backedUpSnapshotUuid.substring(index + 1);
        String details = null;
        String newVolumeName = VmwareHelper.getVCenterSafeUuid();
View Full Code Here

        return new CopyCmdAnswer(details);
    }

    @Override
    public Answer deleteSnapshot(DeleteCommand cmd) {
        SnapshotObjectTO snapshot = (SnapshotObjectTO)cmd.getData();
        DataStoreTO store = snapshot.getDataStore();
        if (store.getRole() == DataStoreRole.Primary) {
            return new Answer(cmd);
        } else {
            return new Answer(cmd, false, "unsupported command");
        }
View Full Code Here

    @Override
    public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback<CreateCmdResult> callback) {
        CreateCmdResult result = null;
        try {
            SnapshotObjectTO snapshotTO = (SnapshotObjectTO) snapshot.getTO();
            Object payload = snapshot.getPayload();
            if (payload != null && payload instanceof CreateSnapshotPayload) {
                CreateSnapshotPayload snapshotPayload = (CreateSnapshotPayload) payload;
                snapshotTO.setQuiescevm(snapshotPayload.getQuiescevm());
            }

            CreateObjectCommand cmd = new CreateObjectCommand(snapshotTO);
            EndPoint ep = this.epSelector.select(snapshot, StorageAction.TAKESNAPSHOT);
            Answer answer = null;
View Full Code Here

            cacheStore = (NfsTO)destData.getDataStore();
            secondaryStorageUrl = cacheStore.getUrl();
            destPath = destData.getPath();
        }

        SnapshotObjectTO snapshotTO = (SnapshotObjectTO)srcData;
        SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO)destData;
        String snapshotUuid = snapshotTO.getPath();

        String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
        String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
        Map<String, String> options = cmd.getOptions();
        // By default assume failure
        String details = null;
        String snapshotBackupUuid = null;
        boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
        try {
            SR 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);
            Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));

            VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
            String snapshotPaUuid = null;

            URI uri = new URI(secondaryStorageUrl);
            String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
            DataStoreTO destStore = destData.getDataStore();
            String folder = destPath;
            String finalPath = null;

            String localMountPoint =  BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
            if (fullbackup) {
                SR snapshotSr = null;
                Task task = null;
                try {
                    String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes());
                    mountNfs(conn, secondaryStorageMountPath, localDir);
                    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.copyAsync2(conn, snapshotSr, null, null);
                    // poll every 1 seconds ,
                    hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
                    hypervisorResource.checkForSuccess(conn, task);
                    VDI backedVdi = Types.toVDI(task, conn);
                    snapshotBackupUuid = backedVdi.getUuid(conn);

                    if( destStore instanceof SwiftTO) {
                        try {
                            String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                            String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO)destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait);
                            String swiftPath = container + File.separator + destSnapshotName;
                            finalPath = swiftPath;
                        } finally {
                            try {
                                deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid);
                            } catch (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 (Exception e) {
                                s_logger.debug("Failed to delete snapshot on cache storages" ,e);
                            }
                        }
                        // finalPath = folder + File.separator + snapshotBackupUuid;
                    } else {
                        finalPath = folder + File.separator + snapshotBackupUuid;
                    }

                } finally {
                    if (task != null) {
                        try {
                            task.destroy(conn);
                        } catch (Exception e) {
                            s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString());
                        }
                    }
                    if( snapshotSr != null) {
                        hypervisorResource.removeSR(conn, snapshotSr);
                    }
                }
            } else {
                String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
                if( destStore instanceof SwiftTO ) {
                    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 {
                    snapshotBackupUuid = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder,
                            secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI, wait);

                    finalPath = folder + File.separator + snapshotBackupUuid;
                }
            }
            String volumeUuid = snapshotTO.getVolume().getPath();
            destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);

            SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
            newSnapshot.setPath(finalPath);
            if (fullbackup) {
                newSnapshot.setParentSnapshotPath(null);
            } else {
                newSnapshot.setParentSnapshotPath(prevBackupUuid);
            }
            return new CopyCmdAnswer(newSnapshot);
        } catch (Types.XenAPIException e) {
            details = "BackupSnapshot Failed due to " + e.toString();
            s_logger.warn(details, e);
View Full Code Here

    @Override
    public Answer createVolumeFromSnapshot(CopyCommand cmd) {
        Connection conn = hypervisorResource.getConnection();
        DataTO srcData = cmd.getSrcTO();
        SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData;
        DataTO destData = cmd.getDestTO();
        PrimaryDataStoreTO pool = (PrimaryDataStoreTO)destData.getDataStore();
        VolumeObjectTO volume = (VolumeObjectTO)destData;
                DataStoreTO imageStore = srcData.getDataStore();

        if (!(imageStore instanceof NfsTO)) {
            return new CopyCmdAnswer("unsupported protocol");
        }

        NfsTO nfsImageStore = (NfsTO)imageStore;
        String primaryStorageNameLabel = pool.getUuid();
        String secondaryStorageUrl = nfsImageStore.getUrl();
        int wait = cmd.getWait();
        boolean result = false;
        // Generic error message.
        String details = null;
        String volumeUUID = null;

        if (secondaryStorageUrl == null) {
            details += " because the URL passed: " + secondaryStorageUrl + " is invalid.";
            return new CopyCmdAnswer(details);
        }
        SR srcSr = null;
        VDI destVdi = null;
        try {
            SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
            if (primaryStorageSR == null) {
                throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: "
                        + primaryStorageNameLabel);
            }
            String nameLabel = "cloud-" + UUID.randomUUID().toString();
            destVdi = createVdi(conn, nameLabel, primaryStorageSR, volume.getSize());
            volumeUUID = destVdi.getUuid(conn);
            String snapshotInstallPath = snapshot.getPath();
            int index = snapshotInstallPath.lastIndexOf(File.separator);
            String snapshotDirectory = snapshotInstallPath.substring(0, index);
            String snapshotUuid = getSnapshotUuid(snapshotInstallPath);

            URI uri = new URI(secondaryStorageUrl);
            srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), snapshotDirectory);

            String[] parents = snapshot.getParents();
            List<VDI> snapshotChains = new ArrayList<VDI>();
            if (parents != null) {
                for(int i = 0; i < parents.length; i++) {
                    String snChainPath = parents[i];
                    String uuid = getSnapshotUuid(snChainPath);
View Full Code Here

    public Answer createTemplateFromSnapshot(CopyCommand cmd) {
        Connection conn = hypervisorResource.getConnection();
        DataTO srcData = cmd.getSrcTO();
        DataTO destData = cmd.getDestTO();
        int wait = cmd.getWait();
        SnapshotObjectTO srcObj = (SnapshotObjectTO)srcData;
        TemplateObjectTO destObj = (TemplateObjectTO)destData;
        NfsTO srcStore = (NfsTO)srcObj.getDataStore();
        NfsTO destStore = (NfsTO)destObj.getDataStore();

        URI srcUri = null;
        URI destUri = null;
        try {
            srcUri = new URI(srcStore.getUrl());
            destUri = new URI(destStore.getUrl());
        } catch (Exception e) {
            s_logger.debug("incorrect url", e);
            return new CopyCmdAnswer("incorrect url" + e.toString());
        }

        String srcPath = srcObj.getPath();
        int index = srcPath.lastIndexOf("/");
        String srcDir = srcPath.substring(0, index);
        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);

            String destNfsPath = destUri.getHost() + ":" + destUri.getPath();
            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);

            String nameLabel = "cloud-" + UUID.randomUUID().toString();

            String[] parents = srcObj.getParents();
            List<VDI> snapshotChains = new ArrayList<VDI>();
            if (parents != null) {
                for(int i = 0; i < parents.length; i++) {
                    String snChainPath = parents[i];
                    String uuid = getSnapshotUuid(snChainPath);
View Full Code Here

TOP

Related Classes of org.apache.cloudstack.storage.to.SnapshotObjectTO

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.