Search in sources :

Example 6 with SnapshotVO

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

the class ApiResponseHelper method createUsageResponse.

@Override
public UsageRecordResponse createUsageResponse(Usage usageRecord) {
    UsageRecordResponse usageRecResponse = new UsageRecordResponse();
    Account account = ApiDBUtils.findAccountById(usageRecord.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        //find the project
        Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
        if (project != null) {
            usageRecResponse.setProjectId(project.getUuid());
            usageRecResponse.setProjectName(project.getName());
        }
    } else {
        usageRecResponse.setAccountId(account.getUuid());
        usageRecResponse.setAccountName(account.getAccountName());
    }
    Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
    if (domain != null) {
        usageRecResponse.setDomainId(domain.getUuid());
        usageRecResponse.setDomainName(domain.getName());
    }
    if (usageRecord.getZoneId() != null) {
        DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
        if (zone != null) {
            usageRecResponse.setZoneId(zone.getUuid());
        }
    }
    usageRecResponse.setDescription(usageRecord.getDescription());
    usageRecResponse.setUsage(usageRecord.getUsageDisplay());
    usageRecResponse.setUsageType(usageRecord.getUsageType());
    if (usageRecord.getVmInstanceId() != null) {
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
        if (vm != null) {
            usageRecResponse.setVirtualMachineId(vm.getUuid());
        }
    }
    usageRecResponse.setVmName(usageRecord.getVmName());
    if (usageRecord.getTemplateId() != null) {
        VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
        if (template != null) {
            usageRecResponse.setTemplateId(template.getUuid());
        }
    }
    if (usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM) {
        ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
        //Service Offering Id
        usageRecResponse.setOfferingId(svcOffering.getUuid());
        //VM Instance ID
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
        if (vm != null) {
            usageRecResponse.setUsageId(vm.getUuid());
        }
        //Hypervisor Type
        usageRecResponse.setType(usageRecord.getType());
        //Dynamic compute offerings details
        usageRecResponse.setCpuNumber(usageRecord.getCpuCores());
        usageRecResponse.setCpuSpeed(usageRecord.getCpuSpeed());
        usageRecResponse.setMemory(usageRecord.getMemory());
    } else if (usageRecord.getUsageType() == UsageTypes.IP_ADDRESS) {
        //isSourceNAT
        usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat")) ? true : false);
        //isSystem
        usageRecResponse.setSystem((usageRecord.getSize() == 1) ? true : false);
        //IP Address ID
        IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
        if (ip != null) {
            usageRecResponse.setUsageId(ip.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED) {
        //Device Type
        usageRecResponse.setType(usageRecord.getType());
        if (usageRecord.getType().equals("DomainRouter")) {
            //Domain Router Id
            VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
            if (vm != null) {
                usageRecResponse.setUsageId(vm.getUuid());
            }
        } else {
            //External Device Host Id
            HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
            if (host != null) {
                usageRecResponse.setUsageId(host.getUuid());
            }
        }
        //Network ID
        if ((usageRecord.getNetworkId() != null) && (usageRecord.getNetworkId() != 0)) {
            NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
            if (network != null) {
                usageRecResponse.setNetworkId(network.getUuid());
            }
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) {
        //Device Type
        usageRecResponse.setType(usageRecord.getType());
        //VM Instance Id
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
        if (vm != null) {
            usageRecResponse.setVirtualMachineId(vm.getUuid());
        }
        //Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VOLUME) {
        //Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
        }
        //Volume Size
        usageRecResponse.setSize(usageRecord.getSize());
        //Disk Offering Id
        if (usageRecord.getOfferingId() != null) {
            DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
            usageRecResponse.setOfferingId(diskOff.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO) {
        //Template/ISO ID
        VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
        if (tmpl != null) {
            usageRecResponse.setUsageId(tmpl.getUuid());
        }
        //Template/ISO Size
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getUsageType() == UsageTypes.ISO) {
            usageRecResponse.setVirtualSize(usageRecord.getSize());
        } else {
            usageRecResponse.setVirtualSize(usageRecord.getVirtualSize());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SNAPSHOT) {
        //Snapshot ID
        SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
        if (snap != null) {
            usageRecResponse.setUsageId(snap.getUuid());
        }
        //Snapshot Size
        usageRecResponse.setSize(usageRecord.getSize());
    } else if (usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY) {
        //Load Balancer Policy ID
        LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
        if (lb != null) {
            usageRecResponse.setUsageId(lb.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE) {
        //Port Forwarding Rule ID
        PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
        if (pf != null) {
            usageRecResponse.setUsageId(pf.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING) {
        //Network Offering Id
        NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
        usageRecResponse.setOfferingId(netOff.getUuid());
        //is Default
        usageRecResponse.setDefault((usageRecord.getUsageId() == 1) ? true : false);
    } else if (usageRecord.getUsageType() == UsageTypes.VPN_USERS) {
        //VPN User ID
        VpnUserVO vpnUser = _entityMgr.findByIdIncludingRemoved(VpnUserVO.class, usageRecord.getUsageId().toString());
        if (vpnUser != null) {
            usageRecResponse.setUsageId(vpnUser.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP) {
        //Security Group Id
        SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
        if (sg != null) {
            usageRecResponse.setUsageId(sg.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_SNAPSHOT) {
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
        if (vm != null) {
            usageRecResponse.setVmName(vm.getInstanceName());
            usageRecResponse.setUsageId(vm.getUuid());
        }
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getOfferingId() != null) {
            usageRecResponse.setOfferingId(usageRecord.getOfferingId().toString());
        }
    }
    if (usageRecord.getRawUsage() != null) {
        DecimalFormat decimalFormat = new DecimalFormat("###########.######");
        usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
    }
    if (usageRecord.getStartDate() != null) {
        usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
    }
    if (usageRecord.getEndDate() != null) {
        usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
    }
    return usageRecResponse;
}
Also used : UsageRecordResponse(org.apache.cloudstack.api.response.UsageRecordResponse) ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) SecurityGroupVO(com.cloud.network.security.SecurityGroupVO) VpnUserVO(com.cloud.network.VpnUserVO) DecimalFormat(java.text.DecimalFormat) VMTemplateVO(com.cloud.storage.VMTemplateVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) HostVO(com.cloud.host.HostVO) Project(com.cloud.projects.Project) DataCenter(com.cloud.dc.DataCenter) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) Domain(com.cloud.domain.Domain)

Example 7 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.

the class SnapshotManagerImpl method revertSnapshot.

@Override
public Snapshot revertSnapshot(final Long snapshotId) {
    final SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
    if (snapshot == null) {
        throw new InvalidParameterValueException("No such snapshot");
    }
    final VolumeVO volume = _volsDao.findById(snapshot.getVolumeId());
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("The volume is not in Ready state.");
    }
    final Long instanceId = volume.getInstanceId();
    // in order to revert the volume
    if (instanceId != null) {
        final UserVmVO vm = _vmDao.findById(instanceId);
        if (vm.getState() != State.Stopped && vm.getState() != State.Shutdowned) {
            throw new InvalidParameterValueException("The VM the specified disk is attached to is not in the shutdown state.");
        }
        // If target VM has associated VM snapshots then don't allow to revert from snapshot
        final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(instanceId);
        if (vmSnapshots.size() > 0) {
            throw new InvalidParameterValueException("Unable to revert snapshot for VM, please remove VM snapshots before reverting VM from snapshot");
        }
    }
    final SnapshotInfo snapshotInfo = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
    if (snapshotInfo == null) {
        throw new CloudRuntimeException("snapshot:" + snapshotId + " not exist in data store");
    }
    final SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.REVERT);
    if (snapshotStrategy == null) {
        s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
        return null;
    }
    final boolean result = snapshotStrategy.revertSnapshot(snapshotInfo);
    if (result) {
        // update volume size and primary storage count
        _resourceLimitMgr.decrementResourceCount(snapshot.getAccountId(), ResourceType.primary_storage, volume.getSize() - snapshot.getSize());
        volume.setSize(snapshot.getSize());
        _volsDao.update(volume.getId(), volume);
        return snapshotInfo;
    }
    return null;
}
Also used : VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) UserVmVO(com.cloud.vm.UserVmVO) SnapshotInfo(com.cloud.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SnapshotStrategy(com.cloud.engine.subsystem.api.storage.SnapshotStrategy)

Example 8 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.

the class SnapshotManagerImpl method deleteSnapshotDirsForAccount.

@Override
public boolean deleteSnapshotDirsForAccount(final long accountId) {
    final List<VolumeVO> volumes = _volsDao.findIncludingRemovedByAccount(accountId);
    // The above call will list only non-destroyed volumes.
    // So call this method before marking the volumes as destroyed.
    // i.e Call them before the VMs for those volumes are destroyed.
    boolean success = true;
    for (final VolumeVO volume : volumes) {
        if (volume.getPoolId() == null) {
            continue;
        }
        final Long volumeId = volume.getId();
        final Long dcId = volume.getDataCenterId();
        if (_snapshotDao.listByVolumeIdIncludingRemoved(volumeId).isEmpty()) {
            // This volume doesn't have any snapshots. Nothing do delete.
            continue;
        }
        final List<DataStore> ssHosts = dataStoreMgr.getImageStoresByScope(new ZoneScope(dcId));
        for (final DataStore ssHost : ssHosts) {
            final String snapshotDir = TemplateConstants.DEFAULT_SNAPSHOT_ROOT_DIR + "/" + accountId + "/" + volumeId;
            final DeleteSnapshotsDirCommand cmd = new DeleteSnapshotsDirCommand(ssHost.getTO(), snapshotDir);
            final EndPoint ep = _epSelector.select(ssHost);
            final Answer answer;
            if (ep == null) {
                final String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
                s_logger.error(errMsg);
                answer = new Answer(cmd, false, errMsg);
            } else {
                answer = ep.sendMessage(cmd);
            }
            if (answer != null && answer.getResult()) {
                s_logger.debug("Deleted all snapshots for volume: " + volumeId + " under account: " + accountId);
            } else {
                success = false;
                if (answer != null) {
                    s_logger.warn("Failed to delete all snapshot for volume " + volumeId + " on secondary storage " + ssHost.getUri());
                    s_logger.error(answer.getDetails());
                }
            }
        }
        // Either way delete the snapshots for this volume.
        final List<SnapshotVO> snapshots = listSnapsforVolume(volumeId);
        for (final SnapshotVO snapshot : snapshots) {
            final SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.DELETE);
            if (snapshotStrategy == null) {
                s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshot.getId() + "'");
                continue;
            }
            final SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Image);
            if (snapshotStrategy.deleteSnapshot(snapshot.getId())) {
                if (Type.MANUAL == snapshot.getRecurringType()) {
                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.snapshot);
                    if (snapshotStoreRef != null) {
                        _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(snapshotStoreRef.getPhysicalSize()));
                    }
                }
            }
        }
    }
    // Returns true if snapshotsDir has been deleted for all volumes.
    return success;
}
Also used : SnapshotDataStoreVO(com.cloud.storage.datastore.db.SnapshotDataStoreVO) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) ZoneScope(com.cloud.engine.subsystem.api.storage.ZoneScope) DeleteSnapshotsDirCommand(com.cloud.agent.api.DeleteSnapshotsDirCommand) Answer(com.cloud.agent.api.Answer) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) SnapshotStrategy(com.cloud.engine.subsystem.api.storage.SnapshotStrategy)

Example 9 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.

the class SnapshotManagerImpl method listSnapshots.

@Override
public Pair<List<? extends Snapshot>, Integer> listSnapshots(final ListSnapshotsCmd cmd) {
    final Long volumeId = cmd.getVolumeId();
    final String name = cmd.getSnapshotName();
    final Long id = cmd.getId();
    final String keyword = cmd.getKeyword();
    final String snapshotTypeStr = cmd.getSnapshotType();
    final String intervalTypeStr = cmd.getIntervalType();
    final Map<String, String> tags = cmd.getTags();
    final Long zoneId = cmd.getZoneId();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    // Verify parameters
    if (volumeId != null) {
        final VolumeVO volume = _volsDao.findById(volumeId);
        if (volume != null) {
            _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
        }
    }
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    final 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("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()) {
        final 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);
    }
    final 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 (final 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);
    }
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (keyword != null) {
        final SearchCriteria<SnapshotVO> ssc = _snapshotDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (snapshotTypeStr != null) {
        final 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) {
        final 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());
    }
    final Pair<List<SnapshotVO>, Integer> result = _snapshotDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) ResourceType(com.cloud.configuration.Resource.ResourceType) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) ScopeType(com.cloud.storage.ScopeType) Type(com.cloud.storage.Snapshot.Type) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) 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.utils.exception.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair)

Example 10 with SnapshotVO

use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.

the class SnapshotManagerImpl method backupSnapshotFromVmSnapshot.

@Override
public Snapshot backupSnapshotFromVmSnapshot(final Long snapshotId, final Long vmId, final Long volumeId, final Long vmSnapshotId) {
    final 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");
    }
    final VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId);
    if (vmSnapshot == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to vmSnapshot:" + vmSnapshotId + " doesn't exist");
    }
    // check vmsnapshot permissions
    final Account caller = CallContext.current().getCallingAccount();
    _accountMgr.checkAccess(caller, null, true, vmSnapshot);
    final SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
    if (snapshot == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to snapshot:" + snapshotId + " doesn't exist");
    }
    final 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.");
    }
    final DataStore store = volume.getDataStore();
    final SnapshotDataStoreVO parentSnapshotDataStoreVO = _snapshotStoreDao.findParent(store.getRole(), store.getId(), volumeId);
    if (parentSnapshotDataStoreVO != null) {
        // Double check the snapshot is removed or not
        final 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);
    final SnapshotDataStoreVO snapshotOnPrimaryStore = this._snapshotStoreDao.findBySnapshot(snapshot.getId(), store.getRole());
    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);
    final Long snapshotOwnerId = vm.getAccountId();
    try {
        final 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 (final Exception e) {
        s_logger.debug("Failed to backup snapshot from vm snapshot", e);
        _resourceLimitMgr.decrementResourceCount(snapshotOwnerId, ResourceType.snapshot);
        _resourceLimitMgr.decrementResourceCount(snapshotOwnerId, ResourceType.secondary_storage, volume.getSize());
        throw new CloudRuntimeException("Failed to backup snapshot from vm snapshot", e);
    }
    return snapshotInfo;
}
Also used : Account(com.cloud.user.Account) SnapshotDataStoreVO(com.cloud.storage.datastore.db.SnapshotDataStoreVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotInfo(com.cloud.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) SnapshotStrategy(com.cloud.engine.subsystem.api.storage.SnapshotStrategy)

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