Search in sources :

Example 41 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cloudstack by apache.

the class SnapshotManagerImpl method backupSnapshotFromVmSnapshot.

@Override
public Snapshot backupSnapshotFromVmSnapshot(Long snapshotId, Long vmId, Long volumeId, Long vmSnapshotId) {
    VMInstanceVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to vm:" + vmId + " doesn't exist");
    }
    if (!HypervisorType.KVM.equals(vm.getHypervisorType())) {
        throw new InvalidParameterValueException("Unsupported hypervisor type " + vm.getHypervisorType() + ". This supports KVM only");
    }
    VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId);
    if (vmSnapshot == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to vmSnapshot:" + vmSnapshotId + " doesn't exist");
    }
    // check vmsnapshot permissions
    Account caller = CallContext.current().getCallingAccount();
    _accountMgr.checkAccess(caller, null, true, vmSnapshot);
    SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
    if (snapshot == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to snapshot:" + snapshotId + " doesn't exist");
    }
    VolumeInfo volume = volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
    }
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
    }
    DataStore store = volume.getDataStore();
    SnapshotDataStoreVO parentSnapshotDataStoreVO = _snapshotStoreDao.findParent(store.getRole(), store.getId(), volumeId);
    if (parentSnapshotDataStoreVO != null) {
        // Double check the snapshot is removed or not
        SnapshotVO parentSnap = _snapshotDao.findById(parentSnapshotDataStoreVO.getSnapshotId());
        if (parentSnap != null && parentSnapshotDataStoreVO.getInstallPath() != null && parentSnapshotDataStoreVO.getInstallPath().equals(vmSnapshot.getName())) {
            throw new InvalidParameterValueException("Creating snapshot failed due to snapshot : " + parentSnap.getUuid() + " is created from the same vm snapshot");
        }
    }
    SnapshotInfo snapshotInfo = this.snapshotFactory.getSnapshot(snapshotId, store);
    snapshotInfo = (SnapshotInfo) store.create(snapshotInfo);
    SnapshotDataStoreVO snapshotOnPrimaryStore = this._snapshotStoreDao.findByStoreSnapshot(store.getRole(), store.getId(), snapshot.getId());
    snapshotOnPrimaryStore.setState(ObjectInDataStoreStateMachine.State.Ready);
    snapshotOnPrimaryStore.setInstallPath(vmSnapshot.getName());
    _snapshotStoreDao.update(snapshotOnPrimaryStore.getId(), snapshotOnPrimaryStore);
    snapshot.setState(Snapshot.State.CreatedOnPrimary);
    _snapshotDao.update(snapshot.getId(), snapshot);
    snapshotInfo = this.snapshotFactory.getSnapshot(snapshotId, store);
    Long snapshotOwnerId = vm.getAccountId();
    try {
        SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.BACKUP);
        if (snapshotStrategy == null) {
            throw new CloudRuntimeException("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
        }
        snapshotInfo = snapshotStrategy.backupSnapshot(snapshotInfo);
    } catch (Exception e) {
        s_logger.debug("Failed to backup snapshot from vm snapshot", e);
        _resourceLimitMgr.decrementResourceCount(snapshotOwnerId, ResourceType.snapshot);
        _resourceLimitMgr.decrementResourceCount(snapshotOwnerId, ResourceType.secondary_storage, new Long(volume.getSize()));
        throw new CloudRuntimeException("Failed to backup snapshot from vm snapshot", e);
    }
    return snapshotInfo;
}
Also used : Account(com.cloud.user.Account) SnapshotDataStoreVO(org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotInfo(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) SnapshotStrategy(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy)

Example 42 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cloudstack by apache.

the class SnapshotManagerImpl method supportedByHypervisor.

private boolean supportedByHypervisor(VolumeInfo volume) {
    HypervisorType hypervisorType;
    StoragePoolVO storagePool = _storagePoolDao.findById(volume.getDataStore().getId());
    ScopeType scope = storagePool.getScope();
    if (scope.equals(ScopeType.ZONE)) {
        hypervisorType = storagePool.getHypervisor();
    } else {
        hypervisorType = volume.getHypervisorType();
    }
    if (hypervisorType.equals(HypervisorType.Ovm)) {
        throw new InvalidParameterValueException("Ovm won't support taking snapshot");
    }
    if (hypervisorType.equals(HypervisorType.KVM)) {
        List<HostVO> hosts = null;
        if (scope.equals(ScopeType.CLUSTER)) {
            ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId());
            hosts = _resourceMgr.listAllHostsInCluster(cluster.getId());
        } else if (scope.equals(ScopeType.ZONE)) {
            hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(hypervisorType, volume.getDataCenterId());
        }
        if (hosts != null && !hosts.isEmpty()) {
            HostVO host = hosts.get(0);
            if (!hostSupportSnapsthotForVolume(host, volume)) {
                throw new CloudRuntimeException("KVM Snapshot is not supported for Running VMs. It is disabled by default due to a possible volume corruption in certain cases. To enable it set global settings kvm.snapshot.enabled to True. See the documentation for more details.");
            }
        }
    }
    // 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:" + volume.getId() + " 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.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
                if (activeSnapshots.size() > 0) {
                    throw new InvalidParameterValueException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later");
                }
            }
            List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(userVm.getId(), VMSnapshot.State.Creating, VMSnapshot.State.Reverting, VMSnapshot.State.Expunging);
            if (activeVMSnapshots.size() > 0) {
                throw new CloudRuntimeException("There is other active vm snapshot tasks on the instance to which the volume is attached, please try again later");
            }
        }
    }
    return true;
}
Also used : ScopeType(com.cloud.storage.ScopeType) UserVmVO(com.cloud.vm.UserVmVO) ClusterVO(com.cloud.dc.ClusterVO) HostVO(com.cloud.host.HostVO) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO)

Example 43 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cloudstack by apache.

the class SnapshotManagerImpl method createSnapshot.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "creating snapshot", async = true)
public Snapshot createSnapshot(Long volumeId, Long policyId, Long snapshotId, Account snapshotOwner) {
    VolumeInfo volume = volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("No such volume exist");
    }
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("Volume is not in ready state");
    }
    // does the caller have the authority to act on this volume
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
    SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
    if (snapshot == null) {
        s_logger.debug("Failed to create snapshot");
        throw new CloudRuntimeException("Failed to create snapshot");
    }
    try {
        postCreateSnapshot(volumeId, snapshot.getId(), policyId);
        // 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) {
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
        }
        _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
    } catch (Exception e) {
        s_logger.debug("Failed to create snapshot", e);
        throw new CloudRuntimeException("Failed to create snapshot", e);
    }
    return snapshot;
}
Also used : SnapshotInfo(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 44 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cloudstack by apache.

the class SnapshotManagerImpl method listSnapshots.

@Override
public Pair<List<? extends Snapshot>, Integer> listSnapshots(ListSnapshotsCmd cmd) {
    Long volumeId = cmd.getVolumeId();
    String name = cmd.getSnapshotName();
    Long id = cmd.getId();
    String keyword = cmd.getKeyword();
    String snapshotTypeStr = cmd.getSnapshotType();
    String intervalTypeStr = cmd.getIntervalType();
    Map<String, String> tags = cmd.getTags();
    Long zoneId = cmd.getZoneId();
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    // Verify parameters
    if (volumeId != null) {
        VolumeVO volume = _volsDao.findById(volumeId);
        if (volume != null) {
            _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
        }
    }
    List<Long> ids = getIdsListFromCmd(cmd.getId(), cmd.getIds());
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<SnapshotVO> sb = _snapshotDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    // exclude those Destroyed snapshot, not showing on UI
    sb.and("statusNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
    sb.and("volumeId", sb.entity().getVolumeId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
    sb.and("snapshotTypeEQ", sb.entity().getSnapshotType(), SearchCriteria.Op.IN);
    sb.and("snapshotTypeNEQ", sb.entity().getSnapshotType(), SearchCriteria.Op.NEQ);
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    if (tags != null && !tags.isEmpty()) {
        SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    SearchCriteria<SnapshotVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sc.setParameters("statusNEQ", Snapshot.State.Destroyed);
    if (volumeId != null) {
        sc.setParameters("volumeId", volumeId);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Snapshot.toString());
        for (String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (zoneId != null) {
        sc.setParameters("dataCenterId", zoneId);
    }
    setIdsListToSearchCriteria(sc, ids);
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (keyword != null) {
        SearchCriteria<SnapshotVO> ssc = _snapshotDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (snapshotTypeStr != null) {
        Type snapshotType = SnapshotVO.getSnapshotType(snapshotTypeStr);
        if (snapshotType == null) {
            throw new InvalidParameterValueException("Unsupported snapshot type " + snapshotTypeStr);
        }
        if (snapshotType == Type.RECURRING) {
            sc.setParameters("snapshotTypeEQ", Type.HOURLY.ordinal(), Type.DAILY.ordinal(), Type.WEEKLY.ordinal(), Type.MONTHLY.ordinal());
        } else {
            sc.setParameters("snapshotTypeEQ", snapshotType.ordinal());
        }
    } else if (intervalTypeStr != null && volumeId != null) {
        Type type = SnapshotVO.getSnapshotType(intervalTypeStr);
        if (type == null) {
            throw new InvalidParameterValueException("Unsupported snapstho interval type " + intervalTypeStr);
        }
        sc.setParameters("snapshotTypeEQ", type.ordinal());
    } else {
        // Show only MANUAL and RECURRING snapshot types
        sc.setParameters("snapshotTypeNEQ", Snapshot.Type.TEMPLATE.ordinal());
    }
    Pair<List<SnapshotVO>, Integer> result = _snapshotDao.searchAndCount(sc, searchFilter);
    return new Pair<List<? extends Snapshot>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) ScopeType(com.cloud.storage.ScopeType) Type(com.cloud.storage.Snapshot.Type) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ResourceType(com.cloud.configuration.Resource.ResourceType) IntervalType(com.cloud.utils.DateUtil.IntervalType) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) StoragePoolType(com.cloud.storage.Storage.StoragePoolType) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair)

Example 45 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cloudstack by apache.

the class SnapshotManagerImpl method postCreateSnapshot.

private void postCreateSnapshot(Long volumeId, Long snapshotId, Long policyId) {
    Long userId = getSnapshotUserId();
    SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
    if (policyId != Snapshot.MANUAL_POLICY_ID) {
        SnapshotScheduleVO snapshotSchedule = _snapshotScheduleDao.getCurrentSchedule(volumeId, policyId, true);
        if (snapshotSchedule != null) {
            snapshotSchedule.setSnapshotId(snapshotId);
            _snapshotScheduleDao.update(snapshotSchedule.getId(), snapshotSchedule);
        }
    }
    if (snapshot != null && snapshot.isRecursive()) {
        postCreateRecurringSnapshotForPolicy(userId, volumeId, snapshotId, policyId);
    }
}
Also used : VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) SnapshotScheduleVO(com.cloud.storage.SnapshotScheduleVO)

Aggregations

SnapshotVO (com.cloud.storage.SnapshotVO)105 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)46 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)29 VolumeVO (com.cloud.storage.VolumeVO)28 Account (com.cloud.user.Account)22 SnapshotInfo (org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo)22 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)18 ArrayList (java.util.ArrayList)17 DataStore (org.apache.cloudstack.engine.subsystem.api.storage.DataStore)16 VolumeInfo (org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo)16 SnapshotDataStoreVO (org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO)16 HostVO (com.cloud.host.HostVO)15 VMTemplateVO (com.cloud.storage.VMTemplateVO)15 DB (com.cloud.utils.db.DB)14 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)12 ConfigurationException (javax.naming.ConfigurationException)12 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)11 UserVmVO (com.cloud.vm.UserVmVO)10 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 ActionEvent (com.cloud.event.ActionEvent)9