Search in sources :

Example 71 with SnapshotVO

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

the class SnapshotDaoImpl method updateVolumeIds.

@Override
public void updateVolumeIds(final long oldVolId, final long newVolId) {
    final SearchCriteria<SnapshotVO> sc = VolumeIdSearch.create();
    sc.setParameters("volumeId", oldVolId);
    final SnapshotVO snapshot = createForUpdate();
    snapshot.setVolumeId(newVolId);
    final UpdateBuilder ub = getUpdateBuilder(snapshot);
    update(ub, sc, null);
}
Also used : SnapshotVO(com.cloud.storage.SnapshotVO) UpdateBuilder(com.cloud.utils.db.UpdateBuilder)

Example 72 with SnapshotVO

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

the class TemplateManagerImpl method createPrivateTemplateRecord.

@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true)
public VMTemplateVO createPrivateTemplateRecord(final CreateTemplateCmd cmd, final Account templateOwner) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final boolean isAdmin = _accountMgr.isAdmin(caller.getId());
    _accountMgr.checkAccess(caller, null, true, templateOwner);
    final String name = cmd.getTemplateName();
    if (name == null || name.length() > 32) {
        throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters");
    }
    if (cmd.getTemplateTag() != null) {
        if (!_accountService.isRootAdmin(caller.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    // do some parameter defaulting
    final Integer bits = cmd.getBits();
    final Boolean requiresHvm = cmd.getRequiresHvm();
    final Boolean passwordEnabled = cmd.isPasswordEnabled();
    Boolean isPublic = cmd.isPublic();
    Boolean featured = cmd.isFeatured();
    final int bitsValue = bits == null ? 64 : bits;
    final boolean requiresHvmValue = requiresHvm == null || requiresHvm;
    final boolean passwordEnabledValue = passwordEnabled != null && passwordEnabled;
    if (isPublic == null) {
        isPublic = Boolean.FALSE;
    }
    final boolean isDynamicScalingEnabled = cmd.isDynamicallyScalable();
    // check whether template owner can create public templates
    final boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(templateOwner.getId());
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
        throw new PermissionDeniedException("Failed to create template " + name + ", only private templates can be created.");
    }
    final Long volumeId = cmd.getVolumeId();
    final Long snapshotId = cmd.getSnapshotId();
    if (volumeId == null && snapshotId == null) {
        throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.");
    }
    if (volumeId != null && snapshotId != null) {
        throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")");
    }
    HypervisorType hyperType;
    final VolumeVO volume;
    SnapshotVO snapshot = null;
    final VMTemplateVO privateTemplate;
    if (volumeId != null) {
        // create template from volume
        volume = _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);
        // created
        if (!_volumeMgr.volumeInactive(volume)) {
            final 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 = _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 could be removed so find including removed to record source template id.
        volume = _volumeDao.findByIdIncludingRemoved(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, volume != null ? volume.getSize() : snapshot.getSize());
    if (!isAdmin || featured == null) {
        featured = Boolean.FALSE;
    }
    final Long guestOSId = cmd.getOsTypeId();
    final GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
    if (guestOS == null) {
        throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist.");
    }
    final Long nextTemplateId = _tmpltDao.getNextInSequence(Long.class, "id");
    final String description = cmd.getDisplayText();
    boolean isExtractable = false;
    Long sourceTemplateId = null;
    if (volume != null) {
        final VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
        if (volume.getIsoId() != null && volume.getIsoId() != 0) {
            sourceTemplateId = volume.getIsoId();
        } else if (volume.getTemplateId() != null) {
            sourceTemplateId = volume.getTemplateId();
        }
    }
    final String templateTag = cmd.getTemplateTag();
    if (templateTag != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding template tag: " + templateTag);
        }
    }
    // if specified from the API, use that one
    if (cmd.getHypervisor() != null) {
        hyperType = HypervisorType.getType(cmd.getHypervisor());
    }
    privateTemplate = new VMTemplateVO(nextTemplateId, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, requiresHvmValue, bitsValue, templateOwner.getId(), null, description, passwordEnabledValue, guestOS.getId(), true, hyperType, templateTag, cmd.getDetails(), false, 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);
        }
    }
    // for region wide storage, set cross zones flag
    final List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
    if (!CollectionUtils.isEmpty(stores)) {
        privateTemplate.setCrossZones(true);
    }
    privateTemplate.setSourceTemplateId(sourceTemplateId);
    final VMTemplateVO template = _tmpltDao.persist(privateTemplate);
    // Increment the number of templates
    if (template != null) {
        final Map<String, String> details = new HashMap<>();
        if (volume != null) {
            final Long vmId = volume.getInstanceId();
            if (vmId != null) {
                final UserVmVO userVm = _userVmDao.findById(vmId);
                if (userVm != null) {
                    _userVmDao.loadDetails(userVm);
                    details.putAll(userVm.getDetails());
                }
            }
        }
        if (cmd.getDetails() != null) {
            // new password will be generated during vm deployment from password enabled template
            details.remove("Encrypted.Password");
            details.putAll(cmd.getDetails());
        }
        if (!details.isEmpty()) {
            privateTemplate.setDetails(details);
            _tmpltDao.saveDetails(privateTemplate);
        }
        _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 {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) GuestOSVO(com.cloud.storage.GuestOSVO) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ImageStoreVO(com.cloud.storage.datastore.db.ImageStoreVO) ActionEvent(com.cloud.event.ActionEvent)

Example 73 with SnapshotVO

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

the class TemplateManagerImpl method templateIsDeleteable.

@Override
public boolean templateIsDeleteable(final VMTemplateHostVO templateHostRef) {
    final VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templateHostRef.getTemplateId());
    final long templateId = template.getId();
    final HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId());
    final long zoneId = secondaryStorageHost.getDataCenterId();
    final DataCenterVO zone = _dcDao.findById(zoneId);
    // Check if there are VMs running in the template host ref's zone that
    // use the template
    final List<VMInstanceVO> nonExpungedVms = _vmInstanceDao.listNonExpungedByZoneAndTemplate(zoneId, templateId);
    if (!nonExpungedVms.isEmpty()) {
        s_logger.debug("Template " + template.getName() + " in zone " + zone.getName() + " is not deleteable because there are non-expunged VMs deployed from this template.");
        return false;
    }
    final List<UserVmVO> userVmUsingIso = _userVmDao.listByIsoId(templateId);
    // check if there is any VM using this ISO.
    if (!userVmUsingIso.isEmpty()) {
        s_logger.debug("ISO " + template.getName() + " in zone " + zone.getName() + " is not deleteable because it is attached to " + userVmUsingIso.size() + " VMs");
        return false;
    }
    // Check if there are any snapshots for the template in the template
    // host ref's zone
    final List<VolumeVO> volumes = _volumeDao.findByTemplateAndZone(templateId, zoneId);
    for (final VolumeVO volume : volumes) {
        final List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdVersion(volume.getId(), "2.1");
        if (!snapshots.isEmpty()) {
            s_logger.debug("Template " + template.getName() + " in zone " + zone.getName() + " is not deleteable because there are 2.1 snapshots using this template.");
            return false;
        }
    }
    return true;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) UserVmVO(com.cloud.vm.UserVmVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) VMTemplateHostVO(com.cloud.storage.VMTemplateHostVO) HostVO(com.cloud.host.HostVO)

Example 74 with SnapshotVO

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

the class SnapshotManagerImpl method deleteSnapshot.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_DELETE, eventDescription = "deleting snapshot", async = true)
public boolean deleteSnapshot(final long snapshotId) {
    final Account caller = CallContext.current().getCallingAccount();
    // Verify parameters
    final SnapshotVO snapshotCheck = _snapshotDao.findById(snapshotId);
    if (snapshotCheck == null) {
        throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
    }
    _accountMgr.checkAccess(caller, null, true, snapshotCheck);
    final SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshotCheck, SnapshotOperation.DELETE);
    if (snapshotStrategy == null) {
        s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
        return false;
    }
    try {
        final boolean result = snapshotStrategy.deleteSnapshot(snapshotId);
        if (result) {
            if (snapshotCheck.getState() != Snapshot.State.Error && snapshotCheck.getState() != Snapshot.State.Destroyed) {
                _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.snapshot);
            }
            if (snapshotCheck.getState() == Snapshot.State.BackedUp) {
                final SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Image);
                if (snapshotStoreRef != null) {
                    _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.secondary_storage, new Long(snapshotStoreRef.getPhysicalSize()));
                }
            }
        }
        return result;
    } catch (final Exception e) {
        s_logger.debug("Failed to delete snapshot: " + snapshotCheck.getId() + ":" + e.toString());
        throw new CloudRuntimeException("Failed to delete snapshot:" + e.toString());
    }
}
Also used : Account(com.cloud.user.Account) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SnapshotDataStoreVO(com.cloud.storage.datastore.db.SnapshotDataStoreVO) SnapshotStrategy(com.cloud.engine.subsystem.api.storage.SnapshotStrategy) 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) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 75 with SnapshotVO

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

the class SnapshotManagerImpl method allocSnapshot.

@Override
public Snapshot allocSnapshot(final Long volumeId, final Long policyId, String snapshotName, final boolean fromVmSnapshot) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final VolumeInfo volume = volFactory.getVolume(volumeId);
    if (!fromVmSnapshot) {
        supportedByHypervisor(volume);
    }
    // Verify permissions
    _accountMgr.checkAccess(caller, null, true, volume);
    final Type snapshotType = Type.MANUAL;
    final Account owner = _accountMgr.getAccount(volume.getAccountId());
    try {
        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, volume.getSize());
    } catch (final ResourceAllocationException e) {
        throw e;
    }
    // Determine the name for this snapshot
    // Snapshot Name: VMInstancename + volumeName + timeString
    final String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT);
    final VMInstanceVO vmInstance = _vmDao.findById(volume.getInstanceId());
    String vmDisplayName = "detached";
    if (vmInstance != null) {
        vmDisplayName = vmInstance.getHostName();
    }
    if (snapshotName == null) {
        snapshotName = vmDisplayName + "_" + volume.getName() + "_" + timeString;
    }
    HypervisorType hypervisorType;
    final StoragePoolVO storagePool = _storagePoolDao.findById(volume.getDataStore().getId());
    if (storagePool.getScope() == ScopeType.ZONE) {
        hypervisorType = storagePool.getHypervisor();
        // at the time being, managed storage only supports XenServer, ESX(i), and KVM (i.e. not Hyper-V), so the VHD file type can be mapped to XenServer
        if (storagePool.isManaged() && HypervisorType.Any.equals(hypervisorType) && ImageFormat.VHD.equals(volume.getFormat())) {
            hypervisorType = HypervisorType.XenServer;
        }
    } else {
        hypervisorType = volume.getHypervisorType();
    }
    final SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), snapshotName, (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), volume.getMinIops(), volume.getMaxIops(), hypervisorType);
    final SnapshotVO snapshot = _snapshotDao.persist(snapshotVO);
    if (snapshot == null) {
        throw new CloudRuntimeException("Failed to create snapshot for volume: " + volume.getId());
    }
    _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.snapshot);
    _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, new Long(volume.getSize()));
    return snapshot;
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Account(com.cloud.user.Account) 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) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Date(java.util.Date)

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