Package com.cloud.storage

Examples of com.cloud.storage.SnapshotVO


            Future<Boolean> task = pool.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    boolean r = true;
                    try {
                        SnapshotVO snapshotVO = createSnapshotInDb(vol.getId());
                        VolumeObject volumeObject = (VolumeObject)vol;
                        Account account = mock(Account.class);
                        when(account.getId()).thenReturn(1L);
                        CreateSnapshotPayload createSnapshotPayload = mock(CreateSnapshotPayload.class);
                        when(createSnapshotPayload.getAccount()).thenReturn(account);
                        when(createSnapshotPayload.getSnapshotId()).thenReturn(snapshotVO.getId());
                        when(createSnapshotPayload.getSnapshotPolicyId()).thenReturn(0L);
                        volumeObject.addPayload(createSnapshotPayload);
                        if (cnt > 8) {
                            mockStorageMotionStrategy.makeBackupSnapshotSucceed(false);
                        }
View Full Code Here


        long templateId = command.getEntityId();
        Long volumeId = command.getVolumeId();
        Long snapshotId = command.getSnapshotId();
        VMTemplateVO privateTemplate = null;
        Long accountId = null;
        SnapshotVO snapshot = null;
        VolumeVO volume = null;

        try {
            TemplateInfo tmplInfo = this._tmplFactory.getTemplate(templateId, DataStoreRole.Image);
            long zoneId = 0;
            if (snapshotId != null) {
                snapshot = _snapshotDao.findById(snapshotId);
                zoneId = snapshot.getDataCenterId();
            } else if (volumeId != null) {
                volume = _volumeDao.findById(volumeId);
                zoneId = volume.getDataCenterId();
            }
            DataStore store = this._dataStoreMgr.getImageStore(zoneId);
            if (store == null) {
                throw new CloudRuntimeException("cannot find an image store for zone " + zoneId);
            }
            AsyncCallFuture<TemplateApiResult> future = null;
            if (snapshotId != null) {
                SnapshotInfo snapInfo = this._snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
                DataStore snapStore = snapInfo.getDataStore();
                if ( snapStore != null ){
                    store = snapStore; // pick snapshot image store to create template
                }
                future = this._tmpltSvr.createTemplateFromSnapshotAsync(snapInfo, tmplInfo, store);
            } else if (volumeId != null) {
                VolumeInfo volInfo = this._volFactory.getVolume(volumeId);
                future = this._tmpltSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store);
            } else {
                throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId");
            }

            CommandResult result = null;
            try {
                result = future.get();
                if (result.isFailed()) {
                    privateTemplate = null;
                    s_logger.debug("Failed to create template" + result.getResult());
                    throw new CloudRuntimeException("Failed to create template" + result.getResult());
                }

                VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
                this._tmpltZoneDao.persist(templateZone);

                privateTemplate = this._tmpltDao.findById(templateId);
                if (snapshotId != null) {
                    //getting the prent volume
                    long parentVolumeId=_snapshotDao.findById(snapshotId).getVolumeId();
                    VolumeVO parentVolume = _volumeDao.findById(parentVolumeId);
                    if (parentVolume != null && parentVolume.getIsoId() != null && parentVolume.getIsoId() != 0) {
                        privateTemplate.setSourceTemplateId(parentVolume.getIsoId());
                        _tmpltDao.update(privateTemplate.getId(), privateTemplate);
                    } else if (parentVolume != null && parentVolume.getTemplateId() != null) {
                        privateTemplate.setSourceTemplateId(parentVolume.getTemplateId());
                        _tmpltDao.update(privateTemplate.getId(), privateTemplate);
                    }
                }
                else if (volumeId != null) {
                    VolumeVO parentVolume = _volumeDao.findById(volumeId);
                    if (parentVolume.getIsoId() != null && parentVolume.getIsoId() != 0) {
                        privateTemplate.setSourceTemplateId(parentVolume.getIsoId());
                        _tmpltDao.update(privateTemplate.getId(), privateTemplate);
                    } else if (parentVolume.getTemplateId() != null) {
                        privateTemplate.setSourceTemplateId(parentVolume.getTemplateId());
                        _tmpltDao.update(privateTemplate.getId(), privateTemplate);
                    }
                }
                TemplateDataStoreVO srcTmpltStore = this._tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
                UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), zoneId,
                        privateTemplate.getId(), privateTemplate.getName(), null, privateTemplate.getSourceTemplateId(), srcTmpltStore.getPhysicalSize(), privateTemplate.getSize());
                _usageEventDao.persist(usageEvent);
            } catch (InterruptedException e) {
                s_logger.debug("Failed to create template", e);
                throw new CloudRuntimeException("Failed to create template", e);
            } catch (ExecutionException e) {
                s_logger.debug("Failed to create template", e);
                throw new CloudRuntimeException("Failed to create template", e);
            }

        } finally {
            /*if (snapshot != null && snapshot.getSwiftId() != null
                    && secondaryStorageURL != null && zoneId != null
                    && accountId != null && volumeId != null) {
                _snapshotMgr.deleteSnapshotsForVolume(secondaryStorageURL,
                        zoneId, accountId, volumeId);
            }*/
            if (privateTemplate == null) {
                Transaction txn = Transaction.currentTxn();
                txn.start();
                // template_store_ref entries should have been removed using our
                // DataObject.processEvent command in case of failure, but clean
                // it up here to avoid
                // some leftovers which will cause removing template from
                // vm_template table fail.
                this._tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
                // Remove the template_zone_ref record
                this._tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
                // Remove the template record
                this._tmpltDao.expunge(templateId);

                // decrement resource count
                if (accountId != null) {
                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volume != null ? volume.getSize()
                            : snapshot.getSize()));
                }
                txn.commit();
            }
        }

View Full Code Here

                    + ") and snapshot ID (" + snapshotId + ")");
        }

        HypervisorType hyperType;
        VolumeVO volume = null;
        SnapshotVO snapshot = null;
        VMTemplateVO privateTemplate = null;
        if (volumeId != null) { // create template from volume
            volume = this._volumeDao.findById(volumeId);
            if (volume == null) {
                throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId);
            }
            // check permissions
            _accountMgr.checkAccess(caller, null, true, volume);

            // If private template is created from Volume, check that the volume
            // will not be active when the private template is
            // created
            if (!this._volumeMgr.volumeInactive(volume)) {
                String msg = "Unable to create private template for volume: " + volume.getName()
                        + "; volume is attached to a non-stopped VM, please stop the VM first";
                if (s_logger.isInfoEnabled()) {
                    s_logger.info(msg);
                }
                throw new CloudRuntimeException(msg);
            }

            hyperType = this._volumeDao.getHypervisorType(volumeId);
        } else { // create template from snapshot
            snapshot = _snapshotDao.findById(snapshotId);
            if (snapshot == null) {
                throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId);
            }

            volume = this._volumeDao.findById(snapshot.getVolumeId());

            // check permissions
            _accountMgr.checkAccess(caller, null, true, snapshot);

            if (snapshot.getState() != Snapshot.State.BackedUp) {
                throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp
                        + " state yet and can't be used for template creation");
            }

            /*
             * // bug #11428. Operation not supported if vmware and snapshots
             * parent volume = ROOT if(snapshot.getHypervisorType() ==
             * HypervisorType.VMware && snapshotVolume.getVolumeType() ==
             * Type.DATADISK){ throw new UnsupportedServiceException(
             * "operation not supported, snapshot with id " + snapshotId +
             * " is created from Data Disk"); }
             */

            hyperType = snapshot.getHypervisorType();
        }

        _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
        _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.secondary_storage,
                new Long(volume != null ? volume.getSize() : snapshot.getSize()));

        if (!isAdmin || featured == null) {
            featured = Boolean.FALSE;
        }
        Long guestOSId = cmd.getOsTypeId();
        GuestOSVO guestOS = this._guestOSDao.findById(guestOSId);
        if (guestOS == null) {
            throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist.");
        }

        String uniqueName = Long.valueOf((userId == null) ? 1 : userId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString();
        Long nextTemplateId = this._tmpltDao.getNextInSequence(Long.class, "id");
        String description = cmd.getDisplayText();
        boolean isExtractable = false;
        Long sourceTemplateId = null;
        if (volume != null) {
            VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
            isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
            if (template != null) {
                sourceTemplateId = template.getId();
            } else if (volume.getVolumeType() == Volume.Type.ROOT) { // vm
                // created
                // out
                // of blank
                // template
                UserVm userVm = ApiDBUtils.findUserVmById(volume.getInstanceId());
                sourceTemplateId = userVm.getIsoId();
            }
        }
        String templateTag = cmd.getTemplateTag();
        if (templateTag != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Adding template tag: " + templateTag);
            }
        }
        privateTemplate = new VMTemplateVO(nextTemplateId, uniqueName, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER,
                null, null, requiresHvmValue, bitsValue, templateOwner.getId(), null, description, passwordEnabledValue, guestOS.getId(), true,
                hyperType, templateTag, cmd.getDetails());
        privateTemplate.setDynamicallyScalable(isDynamicScalingEnabled);

        if (sourceTemplateId != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("This template is getting created from other template, setting source template Id to: " + sourceTemplateId);
            }
        }
        privateTemplate.setSourceTemplateId(sourceTemplateId);

        VMTemplateVO template = this._tmpltDao.persist(privateTemplate);
        // Increment the number of templates
        if (template != null) {
            Map<String, String> details = new HashMap<String, String>();
            if ( volume != null ) {
                Long vmId = volume.getInstanceId();
                if ( vmId != null ) {
                    Map<String, String> vmdetails = _vmDetailsDao.findDetails(vmId);
                    if ( vmdetails != null ) {
                        details.putAll(vmdetails);
                    }
                }
            }
            if(cmd.getDetails() != null) {
                details.putAll(cmd.getDetails());
            }
            if( !details.isEmpty()) {
                this._templateDetailsDao.persist(template.getId(), details);
            }

            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.secondary_storage,
                    new Long(volume != null ? volume.getSize() : snapshot.getSize()));
        }

        if (template != null) {
            return template;
        } else {
View Full Code Here

    @Override
    @DB
    public boolean remove(Long id) {
        Transaction txn = Transaction.currentTxn();
        txn.start();
        SnapshotVO entry = findById(id);
        if (entry != null) {
            _tagsDao.removeByIdAndType(id, TaggedResourceType.Snapshot);
        }
        boolean result = super.remove(id);
        txn.commit();
View Full Code Here

    @Override
    public boolean updateState(State currentState, Event event, State nextState, SnapshotVO snapshot, Object data) {
        Transaction txn = Transaction.currentTxn();
        txn.start();
        SnapshotVO snapshotVO = (SnapshotVO) snapshot;
        snapshotVO.setState(nextState);
        super.update(snapshotVO.getId(), snapshotVO);
        txn.commit();
        return true;
    }
View Full Code Here

        return null;
    }

    @Override
    public SnapshotVO createSnapshotOnPrimary(VolumeVO volume, Long policyId, Long snapshotId) {
        SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
        if (snapshot == null) {
            throw new CloudRuntimeException("Can not find snapshot " + snapshotId);
        }
        // Send a ManageSnapshotCommand to the agent
        String vmName = _storageMgr.getVmNameOnVolume(volume);
        long volumeId = volume.getId();
        long preId = _snapshotDao.getLastSnapshot(volumeId, snapshotId);

        String preSnapshotPath = null;
        SnapshotVO preSnapshotVO = null;
        if (preId != 0 && !(volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId()))) {
            preSnapshotVO = _snapshotDao.findByIdIncludingRemoved(preId);
            if (preSnapshotVO != null && preSnapshotVO.getBackupSnapshotId() != null) {
                preSnapshotPath = preSnapshotVO.getPath();
            }
        }
        StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId());

        // RBD volumes do not support snapshotting in the way CloudStack does it.
        // For now we leave the snapshot feature disabled for RBD volumes
        if (srcPool.getPoolType() == StoragePoolType.RBD) {
            throw new CloudRuntimeException("RBD volumes do not support snapshotting");
        }

        ManageSnapshotCommand cmd = new ManageSnapshotCommand(snapshotId, volume.getPath(), srcPool, preSnapshotPath, snapshot.getName(), vmName);
     
        ManageSnapshotAnswer answer = (ManageSnapshotAnswer) sendToPool(volume, cmd);
        // Update the snapshot in the database
        if ((answer != null) && answer.getResult()) {
            // The snapshot was successfully created
            if (preSnapshotPath != null && preSnapshotPath.equals(answer.getSnapshotPath())) {
                // empty snapshot
                s_logger.debug("CreateSnapshot: this is empty snapshot ");
                snapshot.setPath(preSnapshotPath);
                snapshot.setBackupSnapshotId(preSnapshotVO.getBackupSnapshotId());
                snapshot.setSwiftId(preSnapshotVO.getSwiftId());

                snapshot.setStatus(Snapshot.Status.BackedUp);
                snapshot.setPrevSnapshotId(preId);
                snapshot.setSecHostId(preSnapshotVO.getSecHostId());
                _snapshotDao.update(snapshotId, snapshot);
            } else {
                long preSnapshotId = 0;
              
                if (preSnapshotVO != null && preSnapshotVO.getBackupSnapshotId() != null) {
                    preSnapshotId = preId;
                    // default delta snap number is 16
                    int deltaSnap = _deltaSnapshotMax;

                    int i;
                    for (i = 1; i < deltaSnap; i++) {
                        String prevBackupUuid = preSnapshotVO.getBackupSnapshotId();
                        // previous snapshot doesn't have backup, create a full snapshot
                        if (prevBackupUuid == null) {
                            preSnapshotId = 0;
                            break;
                        }
                        long preSSId = preSnapshotVO.getPrevSnapshotId();
                        if (preSSId == 0) {
                            break;
                        }
                        preSnapshotVO = _snapshotDao.findByIdIncludingRemoved(preSSId);
                    }
View Full Code Here

       
        if (volume.getState() != Volume.State.Ready) {
          throw new InvalidParameterValueException("Volume is not in ready state");
        }
       
        SnapshotVO snapshot = null;
    
        boolean backedUp = false;
        UserVmVO uservm = null;
        // does the caller have the authority to act on this volume
        _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume);
       
        try {
   
            Long poolId = volume.getPoolId();
            if (poolId == null) {
                throw new CloudRuntimeException("You cannot take a snapshot of a volume until it has been attached to an instance");
            }

            if (_volsDao.getHypervisorType(volume.getId()).equals(HypervisorType.KVM)) {
              uservm = _vmDao.findById(volume.getInstanceId());
              if (uservm != null && uservm.getType() != VirtualMachine.Type.User) {
                throw new CloudRuntimeException("Can't take a snapshot on system vm ");
              }
             
                StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId());
                ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId());
                List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(cluster.getId());
                if (hosts != null && !hosts.isEmpty()) {
                    HostVO host = hosts.get(0);
                    if (!hostSupportSnapsthot(host)) {
                        throw new CloudRuntimeException("KVM Snapshot is not supported on cluster: " + host.getId());
                    }
                }
            }

            // if volume is attached to a vm in destroyed or expunging state; disallow
            if (volume.getInstanceId() != null) {
                UserVmVO userVm = _vmDao.findById(volume.getInstanceId());
                if (userVm != null) {
                    if (userVm.getState().equals(State.Destroyed) || userVm.getState().equals(State.Expunging)) {
                        throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volumeId + " is associated with vm:" + userVm.getInstanceName() + " is in "
                                + userVm.getState().toString() + " state");
                    }
                   
                    if(userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) {
                        List<SnapshotVO> activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.Status.Creating,  Snapshot.Status.CreatedOnPrimary,  Snapshot.Status.BackingUp);
                        if(activeSnapshots.size() > 1)
                            throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later");
                    }
                }
            }

            snapshot = createSnapshotOnPrimary(volume, policyId, snapshotId);
            if (snapshot != null) {
                if (snapshot.getStatus() == Snapshot.Status.CreatedOnPrimary) {
                    backedUp = backupSnapshotToSecondaryStorage(snapshot);
                } else if (snapshot.getStatus() == Snapshot.Status.BackedUp) {
                    // For empty snapshot we set status to BackedUp in createSnapshotOnPrimary
                    backedUp = true;
                } else {
                    snapshot.setStatus(Status.Error);
                    _snapshotDao.update(snapshot.getId(), snapshot);
                    throw new CloudRuntimeException("Failed to create snapshot: " + snapshot + " on primary storage");
                }
                if (!backedUp) {
                    snapshot.setStatus(Status.Error);
                    _snapshotDao.update(snapshot.getId(), snapshot);
                    throw new CloudRuntimeException("Created snapshot: " + snapshot + " on primary but failed to backup on secondary");
                }
            } else {
                throw new CloudRuntimeException("Failed to create snapshot: " + snapshot + " on primary storage");
            }
        } finally {
            // Cleanup jobs to do after the snapshot has been created; decrement resource count
            if (snapshot != null) {
                postCreateSnapshot(volumeId, snapshot.getId(), policyId, backedUp);
                //Check if the snapshot was removed while backingUp. If yes, do not log snapshot create usage event
                SnapshotVO freshSnapshot = _snapshotDao.findById(snapshot.getId());
                if ((freshSnapshot != null) && backedUp) {
                    UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null,
                            volume.getSize());
                    _usageEventDao.persist(usageEvent);
                }
View Full Code Here

        return snapshot;
    }

    private SnapshotVO updateDBOnCreate(Long id, String snapshotPath, long preSnapshotId) {
        SnapshotVO createdSnapshot = _snapshotDao.findByIdIncludingRemoved(id);
        createdSnapshot.setPath(snapshotPath);
        createdSnapshot.setStatus(Snapshot.Status.CreatedOnPrimary);
        createdSnapshot.setPrevSnapshotId(preSnapshotId);
        _snapshotDao.update(id, createdSnapshot);
        return createdSnapshot;
    }
View Full Code Here

        HostVO secHost = _storageMgr.getSecondaryStorageHost(dcId);
        String secondaryStoragePoolUrl = secHost.getStorageUrl();

        Long swiftId = ss.getSwiftId();
        SwiftTO swift = _swiftMgr.getSwiftTO(swiftId);
        SnapshotVO tss = ss;
        List<String> BackupUuids = new ArrayList<String>(30);
        while (true) {
            BackupUuids.add(0, tss.getBackupSnapshotId());
            if (tss.getPrevSnapshotId() == 0)
                break;
            Long id = tss.getPrevSnapshotId();
            tss = _snapshotDao.findById(id);
            assert tss != null : " can not find snapshot " + id;
        }
        String parent = null;
        try {
View Full Code Here

    @Override
    @DB
    public boolean backupSnapshotToSecondaryStorage(SnapshotVO ss) {
        long snapshotId = ss.getId();
        SnapshotVO snapshot = _snapshotDao.acquireInLockTable(snapshotId);
        if (snapshot == null) {
            throw new CloudRuntimeException("Can not acquire lock for snapshot: " + ss);
        }
        try {

            snapshot.setStatus(Snapshot.Status.BackingUp);
            _snapshotDao.update(snapshot.getId(), snapshot);

            long volumeId = snapshot.getVolumeId();
            VolumeVO volume = _volsDao.lockRow(volumeId, true);

            String primaryStoragePoolNameLabel = _storageMgr.getPrimaryStorageNameLabel(volume);
            Long dcId = volume.getDataCenterId();
            Long accountId = volume.getAccountId();
           
            HostVO secHost = getSecHost(volumeId, volume.getDataCenterId());
           
            String secondaryStoragePoolUrl = secHost.getStorageUrl();
            String snapshotUuid = snapshot.getPath();
            // In order to verify that the snapshot is not empty,
            // we check if the parent of the snapshot is not the same as the parent of the previous snapshot.
            // We pass the uuid of the previous snapshot to the plugin to verify this.
            SnapshotVO prevSnapshot = null;
            String prevSnapshotUuid = null;
            String prevBackupUuid = null;


            SwiftTO swift = _swiftMgr.getSwiftTO();
           
            long prevSnapshotId = snapshot.getPrevSnapshotId();
            if (prevSnapshotId > 0) {
                prevSnapshot = _snapshotDao.findByIdIncludingRemoved(prevSnapshotId);
                if ( prevSnapshot.getBackupSnapshotId() != null && swift == null) {
                    if (prevSnapshot.getVersion() != null && prevSnapshot.getVersion().equals("2.2")) {                  
                        prevBackupUuid = prevSnapshot.getBackupSnapshotId();
                        prevSnapshotUuid = prevSnapshot.getPath();
                    }
                } else if ( prevSnapshot.getSwiftId() != null && swift != null ) {
                    prevBackupUuid = prevSnapshot.getBackupSnapshotId();
                    prevSnapshotUuid = prevSnapshot.getPath();
                }
            }
            boolean isVolumeInactive = _storageMgr.volumeInactive(volume);
            String vmName = _storageMgr.getVmNameOnVolume(volume);
            StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId());
View Full Code Here

TOP

Related Classes of com.cloud.storage.SnapshotVO

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.