Search in sources :

Example 46 with SnapshotVO

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

the class SnapshotManagerImpl method revertSnapshot.

@Override
public Snapshot revertSnapshot(Long snapshotId) {
    SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
    if (snapshot == null) {
        throw new InvalidParameterValueException("No such snapshot");
    }
    VolumeVO volume = _volsDao.findById(snapshot.getVolumeId());
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("The volume is not in Ready state.");
    }
    Long instanceId = volume.getInstanceId();
    // in order to revert the volume
    if (instanceId != null) {
        UserVmVO vm = _vmDao.findById(instanceId);
        if (vm.getState() != State.Stopped && vm.getState() != State.Shutdown) {
            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
        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");
        }
    }
    DataStoreRole dataStoreRole = getDataStoreRole(snapshot);
    SnapshotInfo snapshotInfo = snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
    if (snapshotInfo == null) {
        throw new CloudRuntimeException(String.format("snapshot %s [%s] does not exists in data store", snapshot.getName(), snapshot.getUuid()));
    }
    SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.REVERT);
    if (snapshotStrategy == null) {
        s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
        String errorMsg = String.format("Revert snapshot command failed for snapshot with id %d, because this command is supported only for KVM hypervisor", snapshotId);
        throw new CloudRuntimeException(errorMsg);
    }
    boolean result = snapshotStrategy.revertSnapshot(snapshotInfo);
    if (result) {
        // update volume size and primary storage count
        _resourceLimitMgr.decrementResourceCount(snapshot.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize() - snapshot.getSize()));
        volume.setSize(snapshot.getSize());
        _volsDao.update(volume.getId(), volume);
        return snapshotInfo;
    }
    return null;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) DataStoreRole(com.cloud.storage.DataStoreRole) SnapshotInfo(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SnapshotStrategy(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy)

Example 47 with SnapshotVO

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

the class SnapshotSchedulerImpl method checkStatusOfCurrentlyExecutingSnapshots.

private void checkStatusOfCurrentlyExecutingSnapshots() {
    final SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria();
    sc.addAnd("asyncJobId", SearchCriteria.Op.NNULL);
    final List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc, null);
    for (final SnapshotScheduleVO snapshotSchedule : snapshotSchedules) {
        final Long asyncJobId = snapshotSchedule.getAsyncJobId();
        final AsyncJobVO asyncJob = _asyncJobDao.findByIdIncludingRemoved(asyncJobId);
        switch(asyncJob.getStatus()) {
            case SUCCEEDED:
                // The snapshot has been successfully backed up.
                // The snapshot state has also been cleaned up.
                // We can schedule the next job for this snapshot.
                // Remove the existing entry in the snapshot_schedule table.
                scheduleNextSnapshotJob(snapshotSchedule);
                break;
            case FAILED:
                // Check the snapshot status.
                final Long snapshotId = snapshotSchedule.getSnapshotId();
                if (snapshotId == null) {
                    // createSnapshotAsync exited, successfully or unsuccessfully,
                    // even before creating a snapshot record
                    // No cleanup needs to be done.
                    // Schedule the next snapshot.
                    scheduleNextSnapshotJob(snapshotSchedule);
                } else {
                    final SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
                    if (snapshot == null || snapshot.getRemoved() != null) {
                        // This snapshot has been deleted successfully from the primary storage
                        // Again no cleanup needs to be done.
                        // Schedule the next snapshot.
                        // There's very little probability that the code reaches this point.
                        // The snapshotId is a foreign key for the snapshot_schedule table
                        // set to ON DELETE CASCADE. So if the snapshot entry is deleted, the snapshot_schedule entry will be too.
                        // But what if it has only been marked as removed?
                        scheduleNextSnapshotJob(snapshotSchedule);
                    } else {
                        // The management server executing this snapshot job appears to have crashed
                        // while creating the snapshot on primary storage/or backing it up.
                        // We have no idea whether the snapshot was successfully taken on the primary or not.
                        // Schedule the next snapshot job.
                        // The ValidatePreviousSnapshotCommand will take appropriate action on this snapshot
                        // If the snapshot was taken successfully on primary, it will retry backing it up.
                        // and cleanup the previous snapshot
                        // Set the userId to that of system.
                        // _snapshotManager.validateSnapshot(1L, snapshot);
                        // In all cases, schedule the next snapshot job
                        scheduleNextSnapshotJob(snapshotSchedule);
                    }
                }
                break;
            case IN_PROGRESS:
                // And it will remain in stasis.
                break;
        }
    }
}
Also used : VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) SnapshotScheduleVO(com.cloud.storage.SnapshotScheduleVO) AsyncJobVO(org.apache.cloudstack.framework.jobs.impl.AsyncJobVO)

Example 48 with SnapshotVO

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

the class VMSnapshotManagerImpl method allocVMSnapshot.

@Override
public VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDescription, Boolean snapshotMemory) throws ResourceAllocationException {
    Account caller = getCaller();
    // check if VM exists
    UserVmVO userVmVo = _userVMDao.findById(vmId);
    if (userVmVo == null) {
        throw new InvalidParameterValueException("Creating VM snapshot failed due to VM:" + vmId + " is a system VM or does not exist");
    }
    // VM snapshot with memory is not supported for VGPU Vms
    if (snapshotMemory && _serviceOfferingDetailsDao.findDetail(userVmVo.getServiceOfferingId(), GPU.Keys.vgpuType.toString()) != null) {
        throw new InvalidParameterValueException("VM snapshot with MEMORY is not supported for vGPU enabled VMs.");
    }
    // check hypervisor capabilities
    if (!_hypervisorCapabilitiesDao.isVmSnapshotEnabled(userVmVo.getHypervisorType(), "default"))
        throw new InvalidParameterValueException("VM snapshot is not enabled for hypervisor type: " + userVmVo.getHypervisorType());
    // parameter length check
    if (vsDisplayName != null && vsDisplayName.length() > 255)
        throw new InvalidParameterValueException("Creating VM snapshot failed due to length of VM snapshot vsDisplayName should not exceed 255");
    if (vsDescription != null && vsDescription.length() > 255)
        throw new InvalidParameterValueException("Creating VM snapshot failed due to length of VM snapshot vsDescription should not exceed 255");
    // VM snapshot display name must be unique for a VM
    String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT);
    String vmSnapshotName = userVmVo.getInstanceName() + "_VS_" + timeString;
    if (vsDisplayName == null) {
        vsDisplayName = vmSnapshotName;
    }
    if (_vmSnapshotDao.findByName(vmId, vsDisplayName) != null) {
        throw new InvalidParameterValueException("Creating VM snapshot failed due to VM snapshot with name" + vsDisplayName + "  already exists");
    }
    // check VM state
    if (userVmVo.getState() != VirtualMachine.State.Running && userVmVo.getState() != VirtualMachine.State.Stopped) {
        throw new InvalidParameterValueException("Creating vm snapshot failed due to VM:" + vmId + " is not in the running or Stopped state");
    }
    if (snapshotMemory && userVmVo.getState() != VirtualMachine.State.Running) {
        throw new InvalidParameterValueException("Can not snapshot memory when VM is not in Running state");
    }
    List<VolumeVO> rootVolumes = _volumeDao.findReadyRootVolumesByInstance(userVmVo.getId());
    if (rootVolumes == null || rootVolumes.isEmpty()) {
        throw new CloudRuntimeException("Unable to find root volume for the user vm:" + userVmVo.getUuid());
    }
    VolumeVO rootVolume = rootVolumes.get(0);
    StoragePoolVO rootVolumePool = _storagePoolDao.findById(rootVolume.getPoolId());
    if (rootVolumePool == null) {
        throw new CloudRuntimeException("Unable to find root volume storage pool for the user vm:" + userVmVo.getUuid());
    }
    // for KVM, only allow snapshot with memory when VM is in running state
    if (userVmVo.getHypervisorType() == HypervisorType.KVM) {
        if (rootVolumePool.getPoolType() != Storage.StoragePoolType.PowerFlex) {
            if (userVmVo.getState() == State.Running && !snapshotMemory) {
                throw new InvalidParameterValueException("KVM VM does not allow to take a disk-only snapshot when VM is in running state");
            }
        } else {
            if (snapshotMemory) {
                throw new InvalidParameterValueException("Can not snapshot memory for PowerFlex storage pool");
            }
            // All volumes should be on the same PowerFlex storage pool for VM Snapshot
            if (!isVolumesOfUserVmOnSameStoragePool(userVmVo.getId(), rootVolumePool.getId())) {
                throw new InvalidParameterValueException("All volumes of the VM: " + userVmVo.getUuid() + " should be on the same PowerFlex storage pool");
            }
        }
    }
    // check access
    _accountMgr.checkAccess(caller, null, true, userVmVo);
    // check max snapshot limit for per VM
    if (_vmSnapshotDao.findByVm(vmId).size() >= _vmSnapshotMax) {
        throw new CloudRuntimeException("Creating vm snapshot failed due to a VM can just have : " + _vmSnapshotMax + " VM snapshots. Please delete old ones");
    }
    // check if there are active volume snapshots tasks
    List<VolumeVO> listVolumes = _volumeDao.findByInstance(vmId);
    for (VolumeVO volume : listVolumes) {
        List<SnapshotVO> activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
        if (activeSnapshots.size() > 0) {
            throw new CloudRuntimeException("There is other active volume snapshot tasks on the instance to which the volume is attached, please try again later.");
        }
        if (userVmVo.getHypervisorType() == HypervisorType.KVM) {
            if (volume.getPoolType() != Storage.StoragePoolType.PowerFlex) {
                if (volume.getFormat() != ImageFormat.QCOW2) {
                    throw new CloudRuntimeException("We only support create vm snapshots from vm with QCOW2 image");
                }
            } else if (volume.getFormat() != ImageFormat.RAW) {
                throw new CloudRuntimeException("Only support create vm snapshots for volumes on PowerFlex with RAW image");
            }
        }
    }
    // check if there are other active VM snapshot tasks
    if (hasActiveVMSnapshotTasks(vmId)) {
        throw new CloudRuntimeException("There is other active vm snapshot tasks on the instance, please try again later");
    }
    VMSnapshot.Type vmSnapshotType = VMSnapshot.Type.Disk;
    if (snapshotMemory && userVmVo.getState() == VirtualMachine.State.Running)
        vmSnapshotType = VMSnapshot.Type.DiskAndMemory;
    if (rootVolumePool.getPoolType() == Storage.StoragePoolType.PowerFlex) {
        vmSnapshotType = VMSnapshot.Type.Disk;
    }
    try {
        return createAndPersistVMSnapshot(userVmVo, vsDescription, vmSnapshotName, vsDisplayName, vmSnapshotType);
    } catch (Exception e) {
        String msg = e.getMessage();
        s_logger.error("Create vm snapshot record failed for vm: " + vmId + " due to: " + msg);
    }
    return null;
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) Date(java.util.Date) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO)

Example 49 with SnapshotVO

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

the class UserVmManagerImpl method checkStatusOfVolumeSnapshots.

private boolean checkStatusOfVolumeSnapshots(long vmId, Volume.Type type) {
    List<VolumeVO> listVolumes = null;
    if (type == Volume.Type.ROOT) {
        listVolumes = _volsDao.findByInstanceAndType(vmId, type);
    } else if (type == Volume.Type.DATADISK) {
        listVolumes = _volsDao.findByInstanceAndType(vmId, type);
    } else {
        listVolumes = _volsDao.findByInstance(vmId);
    }
    s_logger.debug("Found " + listVolumes.size() + " no. of volumes of type " + type + " for vm with VM ID " + vmId);
    for (VolumeVO volume : listVolumes) {
        Long volumeId = volume.getId();
        s_logger.debug("Checking status of snapshots for Volume with Volume Id: " + volumeId);
        List<SnapshotVO> ongoingSnapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
        int ongoingSnapshotsCount = ongoingSnapshots.size();
        s_logger.debug("The count of ongoing Snapshots for VM with ID " + vmId + " and disk type " + type + " is " + ongoingSnapshotsCount);
        if (ongoingSnapshotsCount > 0) {
            s_logger.debug("Found " + ongoingSnapshotsCount + " no. of snapshots, on volume of type " + type + ", which snapshots are not yet backed up");
            return true;
        }
    }
    return false;
}
Also used : VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO)

Example 50 with SnapshotVO

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

the class SnapshotDaoImpl method updateState.

@Override
public boolean updateState(final State currentState, final Event event, final State nextState, final SnapshotVO snapshot, final Object data) {
    final TransactionLegacy txn = TransactionLegacy.currentTxn();
    txn.start();
    final SnapshotVO snapshotVO = snapshot;
    snapshotVO.setState(nextState);
    super.update(snapshotVO.getId(), snapshotVO);
    txn.commit();
    return true;
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) SnapshotVO(com.cloud.storage.SnapshotVO)

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