Search in sources :

Example 1 with MigrateVolumeCmd

use of org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd in project cloudstack by apache.

the class VolumeApiServiceImpl method changeDiskOfferingForVolumeInternal.

private Volume changeDiskOfferingForVolumeInternal(VolumeVO volume, Long newDiskOfferingId, Long newSize, Long newMinIops, Long newMaxIops, boolean autoMigrateVolume, boolean shrinkOk) throws ResourceAllocationException {
    DiskOfferingVO existingDiskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
    DiskOfferingVO newDiskOffering = _diskOfferingDao.findById(newDiskOfferingId);
    Integer newHypervisorSnapshotReserve = null;
    boolean volumeMigrateRequired = false;
    boolean volumeResizeRequired = false;
    // VALIDATIONS
    Long[] updateNewSize = { newSize };
    Long[] updateNewMinIops = { newMinIops };
    Long[] updateNewMaxIops = { newMaxIops };
    Integer[] updateNewHypervisorSnapshotReserve = { newHypervisorSnapshotReserve };
    validateVolumeResizeWithNewDiskOfferingAndLoad(volume, existingDiskOffering, newDiskOffering, updateNewSize, updateNewMinIops, updateNewMaxIops, updateNewHypervisorSnapshotReserve);
    newSize = updateNewSize[0];
    newMinIops = updateNewMinIops[0];
    newMaxIops = updateNewMaxIops[0];
    newHypervisorSnapshotReserve = updateNewHypervisorSnapshotReserve[0];
    long currentSize = volume.getSize();
    validateVolumeResizeWithSize(volume, currentSize, newSize, shrinkOk);
    // We need to publish this event to usage_volume table
    if (volume.getState() == Volume.State.Allocated) {
        s_logger.debug(String.format("Volume %s is in the allocated state, but has never been created. Simply updating database with new size and IOPS.", volume.getUuid()));
        volume.setSize(newSize);
        volume.setMinIops(newMinIops);
        volume.setMaxIops(newMaxIops);
        volume.setHypervisorSnapshotReserve(newHypervisorSnapshotReserve);
        if (newDiskOffering != null) {
            volume.setDiskOfferingId(newDiskOfferingId);
        }
        _volsDao.update(volume.getId(), volume);
        if (currentSize != newSize) {
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_RESIZE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid());
        }
        return volume;
    }
    if (currentSize != newSize || newMaxIops != volume.getMaxIops() || newMinIops != volume.getMinIops()) {
        volumeResizeRequired = true;
        validateVolumeReadyStateAndHypervisorChecks(volume, currentSize, newSize);
    }
    StoragePoolVO existingStoragePool = _storagePoolDao.findById(volume.getPoolId());
    Pair<List<? extends StoragePool>, List<? extends StoragePool>> poolsPair = managementService.listStoragePoolsForMigrationOfVolumeInternal(volume.getId(), newDiskOffering.getId(), newSize, newMinIops, newMaxIops, true);
    List<? extends StoragePool> suitableStoragePools = poolsPair.second();
    if (!suitableStoragePools.stream().anyMatch(p -> (p.getId() == existingStoragePool.getId()))) {
        volumeMigrateRequired = true;
        if (!autoMigrateVolume) {
            throw new InvalidParameterValueException(String.format("Failed to change offering for volume %s since automigrate is set to false but volume needs to migrated", volume.getUuid()));
        }
    }
    if (!volumeMigrateRequired && !volumeResizeRequired) {
        _volsDao.updateDiskOffering(volume.getId(), newDiskOffering.getId());
        volume = _volsDao.findById(volume.getId());
        return volume;
    }
    if (volumeMigrateRequired) {
        if (CollectionUtils.isEmpty(poolsPair.first()) && CollectionUtils.isEmpty(poolsPair.second())) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Volume change offering operation failed for volume ID: %s as no suitable pool(s) found for migrating to support new disk offering", volume.getUuid()));
        }
        Collections.shuffle(suitableStoragePools);
        MigrateVolumeCmd migrateVolumeCmd = new MigrateVolumeCmd(volume.getId(), suitableStoragePools.get(0).getId(), newDiskOffering.getId(), true);
        try {
            volume = (VolumeVO) migrateVolume(migrateVolumeCmd);
            if (volume == null) {
                throw new CloudRuntimeException(String.format("Volume change offering operation failed for volume ID: %s migration failed to storage pool %s", volume.getUuid(), suitableStoragePools.get(0).getId()));
            }
        } catch (Exception e) {
            throw new CloudRuntimeException(String.format("Volume change offering operation failed for volume ID: %s migration failed to storage pool %s due to %s", volume.getUuid(), suitableStoragePools.get(0).getId(), e.getMessage()));
        }
    }
    if (volumeResizeRequired) {
        // refresh volume data
        volume = _volsDao.findById(volume.getId());
        try {
            volume = resizeVolumeInternal(volume, newDiskOffering, currentSize, newSize, newMinIops, newMaxIops, newHypervisorSnapshotReserve, shrinkOk);
        } catch (Exception e) {
            if (volumeMigrateRequired) {
                s_logger.warn(String.format("Volume change offering operation succeeded for volume ID: %s but volume resize operation failed, so please try resize volume operation separately", volume.getUuid()));
            } else {
                throw new CloudRuntimeException(String.format("Volume change offering operation failed for volume ID: %s due to resize volume operation failed", volume.getUuid()));
            }
        }
    }
    return volume;
}
Also used : ServiceOfferingJoinVO(com.cloud.api.query.vo.ServiceOfferingJoinVO) UserVmManager(com.cloud.vm.UserVmManager) Arrays(java.util.Arrays) DateTimeZone(org.joda.time.DateTimeZone) UsageEventUtils(com.cloud.event.UsageEventUtils) HostDao(com.cloud.host.dao.HostDao) VolumeService(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService) ResourceState(com.cloud.resource.ResourceState) Pod(com.cloud.dc.Pod) Transaction(com.cloud.utils.db.Transaction) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) AgentManager(com.cloud.agent.AgentManager) ServiceOfferingDetailsDao(com.cloud.service.dao.ServiceOfferingDetailsDao) StringUtils(org.apache.commons.lang3.StringUtils) GsonBuilder(com.google.gson.GsonBuilder) SnapshotDao(com.cloud.storage.dao.SnapshotDao) DiskOffering(com.cloud.offering.DiskOffering) AsyncJobExecutionContext(org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext) AttachVolumeCmd(org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ServiceOfferingDao(com.cloud.service.dao.ServiceOfferingDao) Scope(org.apache.cloudstack.engine.subsystem.api.storage.Scope) Map(java.util.Map) ResizeVolumeCmd(org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd) StoragePoolAllocator(org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator) CallContext(org.apache.cloudstack.context.CallContext) VolumeOrchestrationService(org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService) PrimaryDataStoreInfo(org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo) VmDiskStatisticsDao(com.cloud.user.dao.VmDiskStatisticsDao) ModifyTargetsCommand(com.cloud.agent.api.ModifyTargetsCommand) DataTO(com.cloud.agent.api.to.DataTO) TransactionStatus(com.cloud.utils.db.TransactionStatus) DiskProfile(com.cloud.vm.DiskProfile) Set(java.util.Set) DettachCommand(org.apache.cloudstack.storage.command.DettachCommand) ApiDBUtils(com.cloud.api.ApiDBUtils) VolumeDataStoreDao(org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao) VmWorkConstants(com.cloud.vm.VmWorkConstants) MigrateVolumeCmd(org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd) ExtractVolumeCmd(org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) HypervisorCapabilitiesDao(com.cloud.hypervisor.dao.HypervisorCapabilitiesDao) ServiceOfferingJoinDao(com.cloud.api.query.dao.ServiceOfferingJoinDao) AccountDao(com.cloud.user.dao.AccountDao) SnapshotDataStoreVO(org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO) VmWorkJobDao(org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao) ImageStoreUtil(org.apache.cloudstack.utils.imagestore.ImageStoreUtil) NumbersUtil(com.cloud.utils.NumbersUtil) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) AsyncCallFuture(org.apache.cloudstack.framework.async.AsyncCallFuture) ManagerBase(com.cloud.utils.component.ManagerBase) SnapshotApiService(com.cloud.storage.snapshot.SnapshotApiService) ServerApiException(org.apache.cloudstack.api.ServerApiException) AsyncJobVO(org.apache.cloudstack.framework.jobs.impl.AsyncJobVO) VMTemplateDao(com.cloud.storage.dao.VMTemplateDao) DataCenterVO(com.cloud.dc.DataCenterVO) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) ArrayList(java.util.ArrayList) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SearchCriteria(com.cloud.utils.db.SearchCriteria) User(com.cloud.user.User) UserVmDetailVO(com.cloud.vm.UserVmDetailVO) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob) DiskOfferingDetailsDao(org.apache.cloudstack.resourcedetail.dao.DiskOfferingDetailsDao) VMInstanceDao(com.cloud.vm.dao.VMInstanceDao) ResourceTag(com.cloud.server.ResourceTag) VmWorkTakeVolumeSnapshot(com.cloud.vm.VmWorkTakeVolumeSnapshot) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) UserVmDao(com.cloud.vm.dao.UserVmDao) UploadVolumeCmd(org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) DB(com.cloud.utils.db.DB) EnumUtils(com.cloud.utils.EnumUtils) DetachVolumeCmd(org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd) ExecutionException(java.util.concurrent.ExecutionException) ObjectInDataStoreStateMachine(org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine) VolumeDataFactory(org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory) SnapshotManager(com.cloud.storage.snapshot.SnapshotManager) ActionEvent(com.cloud.event.ActionEvent) AccountManager(com.cloud.user.AccountManager) ImageFormat(com.cloud.storage.Storage.ImageFormat) UserVmService(com.cloud.vm.UserVmService) ClusterDetailsDao(com.cloud.dc.ClusterDetailsDao) ConfigurationDao(org.apache.cloudstack.framework.config.dao.ConfigurationDao) StoragePoolTagsDao(com.cloud.storage.dao.StoragePoolTagsDao) ApiErrorCode(org.apache.cloudstack.api.ApiErrorCode) DataObject(org.apache.cloudstack.engine.subsystem.api.storage.DataObject) ManagementService(com.cloud.server.ManagementService) TemplateManager(com.cloud.template.TemplateManager) URL(java.net.URL) Date(java.util.Date) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) CreateVolumeCmd(org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd) Grouping(com.cloud.org.Grouping) UriUtils(com.cloud.utils.UriUtils) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceType(com.cloud.configuration.Resource.ResourceType) Logger(org.apache.log4j.Logger) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) SnapshotDataStoreDao(org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Gson(com.google.gson.Gson) ResourceLimitService(com.cloud.user.ResourceLimitService) Answer(com.cloud.agent.api.Answer) VolumeDetailsDao(com.cloud.storage.dao.VolumeDetailsDao) VmWorkJobHandler(com.cloud.vm.VmWorkJobHandler) Config(com.cloud.configuration.Config) VmWorkSerializer(com.cloud.vm.VmWorkSerializer) PrimaryDataStoreDao(org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionCallback(com.cloud.utils.db.TransactionCallback) StateMachine2(com.cloud.utils.fsm.StateMachine2) State(com.cloud.vm.VirtualMachine.State) GetUploadParamsResponse(org.apache.cloudstack.api.response.GetUploadParamsResponse) GetUploadParamsForVolumeCmd(org.apache.cloudstack.api.command.user.volume.GetUploadParamsForVolumeCmd) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO) Account(com.cloud.user.Account) UUID(java.util.UUID) Pair(com.cloud.utils.Pair) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) Status(com.cloud.host.Status) VMSnapshotDao(com.cloud.vm.snapshot.dao.VMSnapshotDao) List(java.util.List) VolumeDataStoreVO(org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO) DataCenterDao(com.cloud.dc.dao.DataCenterDao) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) Optional(java.util.Optional) EncryptionUtil(com.cloud.utils.EncryptionUtil) Predicate(com.cloud.utils.Predicate) TaggedResourceService(com.cloud.server.TaggedResourceService) JsonParseException(com.google.gson.JsonParseException) VirtualMachine(com.cloud.vm.VirtualMachine) VmDiskStatisticsVO(com.cloud.user.VmDiskStatisticsVO) AsyncJobManager(org.apache.cloudstack.framework.jobs.AsyncJobManager) EntityManager(com.cloud.utils.db.EntityManager) HostScope(org.apache.cloudstack.engine.subsystem.api.storage.HostScope) DataStoreManager(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager) DiskOfferingDao(com.cloud.storage.dao.DiskOfferingDao) HashMap(java.util.HashMap) VmWorkResizeVolume(com.cloud.vm.VmWorkResizeVolume) Domain(com.cloud.domain.Domain) EventTypes(com.cloud.event.EventTypes) HashSet(java.util.HashSet) Inject(javax.inject.Inject) ConfigKey(org.apache.cloudstack.framework.config.ConfigKey) ReflectionUse(com.cloud.utils.ReflectionUse) VmDetailConstants(com.cloud.vm.VmDetailConstants) Outcome(org.apache.cloudstack.framework.jobs.Outcome) AttachCommand(org.apache.cloudstack.storage.command.AttachCommand) TemplateOrVolumePostUploadCommand(org.apache.cloudstack.storage.command.TemplateOrVolumePostUploadCommand) CollectionUtils(org.apache.commons.collections.CollectionUtils) VmWorkJobHandlerProxy(com.cloud.vm.VmWorkJobHandlerProxy) UserVmDetailsDao(com.cloud.vm.dao.UserVmDetailsDao) ChapInfo(org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo) Configurable(org.apache.cloudstack.framework.config.Configurable) VolumeDao(com.cloud.storage.dao.VolumeDao) ManagementServerNode(org.apache.cloudstack.utils.identity.ManagementServerNode) DataCenter(com.cloud.dc.DataCenter) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VmWorkAttachVolume(com.cloud.vm.VmWorkAttachVolume) HostVO(com.cloud.host.HostVO) GPU(com.cloud.gpu.GPU) JobInfo(org.apache.cloudstack.jobs.JobInfo) ConfigurationManager(com.cloud.configuration.ConfigurationManager) MalformedURLException(java.net.MalformedURLException) MapUtils(org.apache.commons.collections.MapUtils) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) DateTime(org.joda.time.DateTime) ChangeOfferingForVolumeCmd(org.apache.cloudstack.api.command.user.volume.ChangeOfferingForVolumeCmd) DiskTO(com.cloud.agent.api.to.DiskTO) VmWork(com.cloud.vm.VmWork) DateUtil(com.cloud.utils.DateUtil) OutcomeImpl(org.apache.cloudstack.framework.jobs.impl.OutcomeImpl) UUIDManager(com.cloud.utils.db.UUIDManager) UserVmVO(com.cloud.vm.UserVmVO) GsonHelper(com.cloud.serializer.GsonHelper) VolumeApiResult(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult) DiskOfferingDetailVO(org.apache.cloudstack.resourcedetail.DiskOfferingDetailVO) ImageStoreEntity(org.apache.cloudstack.storage.image.datastore.ImageStoreEntity) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) VmWorkExtractVolume(com.cloud.vm.VmWorkExtractVolume) HypervisorCapabilitiesVO(com.cloud.hypervisor.HypervisorCapabilitiesVO) Collections(java.util.Collections) MigrateVolumeCmd(org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ServerApiException(org.apache.cloudstack.api.ServerApiException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) JsonParseException(com.google.gson.JsonParseException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) MalformedURLException(java.net.MalformedURLException) ServerApiException(org.apache.cloudstack.api.ServerApiException) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) VmWorkResizeVolume(com.cloud.vm.VmWorkResizeVolume) VmWorkAttachVolume(com.cloud.vm.VmWorkAttachVolume) VmWorkExtractVolume(com.cloud.vm.VmWorkExtractVolume) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

AgentManager (com.cloud.agent.AgentManager)1 Answer (com.cloud.agent.api.Answer)1 ModifyTargetsCommand (com.cloud.agent.api.ModifyTargetsCommand)1 DataTO (com.cloud.agent.api.to.DataTO)1 DiskTO (com.cloud.agent.api.to.DiskTO)1 ApiDBUtils (com.cloud.api.ApiDBUtils)1 ServiceOfferingJoinDao (com.cloud.api.query.dao.ServiceOfferingJoinDao)1 ServiceOfferingJoinVO (com.cloud.api.query.vo.ServiceOfferingJoinVO)1 Config (com.cloud.configuration.Config)1 ConfigurationManager (com.cloud.configuration.ConfigurationManager)1 ResourceType (com.cloud.configuration.Resource.ResourceType)1 ClusterDetailsDao (com.cloud.dc.ClusterDetailsDao)1 DataCenter (com.cloud.dc.DataCenter)1 DataCenterVO (com.cloud.dc.DataCenterVO)1 Pod (com.cloud.dc.Pod)1 DataCenterDao (com.cloud.dc.dao.DataCenterDao)1 Domain (com.cloud.domain.Domain)1 ActionEvent (com.cloud.event.ActionEvent)1 EventTypes (com.cloud.event.EventTypes)1 UsageEventUtils (com.cloud.event.UsageEventUtils)1