Search in sources :

Example 86 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method takeSnapshot.

@Override
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "taking snapshot", async = true)
public Snapshot takeSnapshot(final Long volumeId, final Long policyId, final Long snapshotId, final Account account, final boolean quiescevm) throws ResourceAllocationException {
    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.");
    }
    VMInstanceVO vm = null;
    if (volume.getInstanceId() != null) {
        vm = _vmInstanceDao.findById(volume.getInstanceId());
    }
    if (vm != null) {
        // serialize VM operation
        final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
        if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
            // avoid re-entrance
            final VmWorkJobVO placeHolder;
            placeHolder = createPlaceHolderWork(vm.getId());
            try {
                return orchestrateTakeVolumeSnapshot(volumeId, policyId, snapshotId, account, quiescevm);
            } finally {
                _workJobDao.expunge(placeHolder.getId());
            }
        } else {
            final Outcome<Snapshot> outcome = takeVolumeSnapshotThroughJobQueue(vm.getId(), volumeId, policyId, snapshotId, account.getId(), quiescevm);
            try {
                outcome.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException("Operation is interrupted", e);
            } catch (final java.util.concurrent.ExecutionException e) {
                throw new RuntimeException("Execution excetion", e);
            }
            final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
            if (jobResult != null) {
                if (jobResult instanceof ConcurrentOperationException) {
                    throw (ConcurrentOperationException) jobResult;
                } else if (jobResult instanceof ResourceAllocationException) {
                    throw (ResourceAllocationException) jobResult;
                } else if (jobResult instanceof Throwable) {
                    throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
                }
            }
            return _snapshotDao.findById(snapshotId);
        }
    } else {
        final CreateSnapshotPayload payload = new CreateSnapshotPayload();
        payload.setSnapshotId(snapshotId);
        payload.setAccount(account);
        payload.setQuiescevm(quiescevm);
        volume.addPayload(payload);
        return volService.takeSnapshot(volume);
    }
}
Also used : AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) ExecutionException(java.util.concurrent.ExecutionException) VmWorkTakeVolumeSnapshot(com.cloud.vm.VmWorkTakeVolumeSnapshot) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DataObject(com.cloud.engine.subsystem.api.storage.DataObject) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ActionEvent(com.cloud.event.ActionEvent)

Example 87 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method attachVolumeToVM.

public Volume attachVolumeToVM(final Long vmId, final Long volumeId, final Long deviceId) {
    final Account caller = CallContext.current().getCallingAccount();
    // Check that the volume ID is valid
    final VolumeInfo volumeToAttach = volFactory.getVolume(volumeId);
    // Check that the volume is a data volume
    if (volumeToAttach == null || !(volumeToAttach.getVolumeType() == Volume.Type.DATADISK || volumeToAttach.getVolumeType() == Volume.Type.ROOT)) {
        throw new InvalidParameterValueException("Please specify a volume with the valid type: " + Volume.Type.ROOT.toString() + " or " + Volume.Type.DATADISK.toString());
    }
    // Check that the volume is not currently attached to any VM
    if (volumeToAttach.getInstanceId() != null) {
        throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
    }
    // Check that the volume is not destroyed
    if (volumeToAttach.getState() == Volume.State.Destroy) {
        throw new InvalidParameterValueException("Please specify a volume that is not destroyed.");
    }
    // Check that the virtual machine ID is valid and it's a user vm
    final UserVmVO vm = _userVmDao.findById(vmId);
    if (vm == null || vm.getType() != VirtualMachine.Type.User) {
        throw new InvalidParameterValueException("Please specify a valid User VM.");
    }
    // Check that the VM is in the correct state
    if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
        throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
    }
    // Check that the VM and the volume are in the same zone
    if (vm.getDataCenterId() != volumeToAttach.getDataCenterId()) {
        throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.");
    }
    // Check that the device ID is valid
    if (deviceId != null) {
        // validate ROOT volume type
        if (deviceId.longValue() == 0) {
            validateRootVolumeDetachAttach(_volsDao.findById(volumeToAttach.getId()), vm);
            // vm shouldn't have any volume with deviceId 0
            if (!_volsDao.findByInstanceAndDeviceId(vm.getId(), 0).isEmpty()) {
                throw new InvalidParameterValueException("Vm already has root volume attached to it");
            }
            // volume can't be in Uploaded state
            if (volumeToAttach.getState() == Volume.State.Uploaded) {
                throw new InvalidParameterValueException("No support for Root volume attach in state " + Volume.State.Uploaded);
            }
        }
    }
    // that supported by hypervisor
    if (deviceId == null || deviceId.longValue() != 0) {
        final List<VolumeVO> existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK);
        final int maxDataVolumesSupported = getMaxDataVolumesSupported(vm);
        if (existingDataVolumes.size() >= maxDataVolumesSupported) {
            throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxDataVolumesSupported + "). Please specify another" + " VM.");
        }
    }
    // If local storage is disabled then attaching a volume with local disk
    // offering not allowed
    final DataCenterVO dataCenter = _dcDao.findById(volumeToAttach.getDataCenterId());
    if (!dataCenter.isLocalStorageEnabled()) {
        final DiskOfferingVO diskOffering = _diskOfferingDao.findById(volumeToAttach.getDiskOfferingId());
        if (diskOffering.getUseLocalStorage()) {
            throw new InvalidParameterValueException("Zone is not configured to use local storage but volume's disk offering " + diskOffering.getName() + " uses it");
        }
    }
    // if target VM has associated VM snapshots
    final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
    if (vmSnapshots.size() > 0) {
        throw new InvalidParameterValueException("Unable to attach volume, please specify a VM that does not have VM snapshots");
    }
    // permission check
    _accountMgr.checkAccess(caller, null, true, volumeToAttach, vm);
    if (!(Volume.State.Allocated.equals(volumeToAttach.getState()) || Volume.State.Ready.equals(volumeToAttach.getState()) || Volume.State.Uploaded.equals(volumeToAttach.getState()))) {
        throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state");
    }
    final Account owner = _accountDao.findById(volumeToAttach.getAccountId());
    if (!(volumeToAttach.getState() == Volume.State.Allocated || volumeToAttach.getState() == Volume.State.Ready)) {
        try {
            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, volumeToAttach.getSize());
        } catch (final ResourceAllocationException e) {
            s_logger.error("primary storage resource limit check failed", e);
            throw new InvalidParameterValueException(e.getMessage());
        }
    }
    final HypervisorType rootDiskHyperType = vm.getHypervisorType();
    final HypervisorType volumeToAttachHyperType = _volsDao.getHypervisorType(volumeToAttach.getId());
    final StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId());
    // only perform this check if the volume's storage pool is not null and not managed
    if (volumeToAttachStoragePool != null && !volumeToAttachStoragePool.isManaged()) {
        if (volumeToAttachHyperType != HypervisorType.None && rootDiskHyperType != volumeToAttachHyperType) {
            throw new InvalidParameterValueException("Can't attach a volume created by: " + volumeToAttachHyperType + " to a " + rootDiskHyperType + " vm");
        }
    }
    final AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (asyncExecutionContext != null) {
        final AsyncJob job = asyncExecutionContext.getJob();
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Trying to attaching volume " + volumeId + " to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
        }
        _jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
    }
    final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        final VmWorkJobVO placeHolder;
        placeHolder = createPlaceHolderWork(vmId);
        try {
            return orchestrateAttachVolumeToVM(vmId, volumeId, deviceId);
        } finally {
            _workJobDao.expunge(placeHolder.getId());
        }
    } else {
        final Outcome<Volume> outcome = attachVolumeToVmThroughJobQueue(vmId, volumeId, deviceId);
        Volume vol = null;
        try {
            outcome.get();
        } catch (final InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (final java.util.concurrent.ExecutionException e) {
            throw new RuntimeException("Execution excetion", e);
        }
        final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
        if (jobResult != null) {
            if (jobResult instanceof ConcurrentOperationException) {
                throw (ConcurrentOperationException) jobResult;
            } else if (jobResult instanceof InvalidParameterValueException) {
                throw (InvalidParameterValueException) jobResult;
            } else if (jobResult instanceof RuntimeException) {
                throw (RuntimeException) jobResult;
            } else if (jobResult instanceof Throwable) {
                throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
            } else if (jobResult instanceof Long) {
                vol = _volsDao.findById((Long) jobResult);
            }
        }
        return vol;
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) AsyncJob(com.cloud.framework.jobs.AsyncJob) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) DataCenterVO(com.cloud.dc.DataCenterVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ExecutionException(java.util.concurrent.ExecutionException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) 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) DataObject(com.cloud.engine.subsystem.api.storage.DataObject)

Example 88 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException 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)

Example 89 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException in project cloudstack by apache.

the class DeleteStorageNetworkIpRangeCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
    try {
        _storageNetworkService.deleteIpRange(this);
        SuccessResponse response = new SuccessResponse(getCommandName());
        this.setResponseObject(response);
    } catch (Exception e) {
        s_logger.warn("Failed to delete storage network ip range " + getId(), e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : SuccessResponse(org.apache.cloudstack.api.response.SuccessResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Example 90 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException in project cloudstack by apache.

the class UpdateStorageNetworkIpRangeCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
    try {
        StorageNetworkIpRange result = _storageNetworkService.updateIpRange(this);
        StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
    } catch (Exception e) {
        s_logger.warn("Update storage network IP range failed", e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) StorageNetworkIpRange(com.cloud.dc.StorageNetworkIpRange) StorageNetworkIpRangeResponse(org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Aggregations

ResourceAllocationException (com.cloud.exception.ResourceAllocationException)127 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)81 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)76 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)74 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)55 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)41 ServerApiException (org.apache.cloudstack.api.ServerApiException)37 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)33 Account (com.cloud.user.Account)33 DB (com.cloud.utils.db.DB)30 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)27 ArrayList (java.util.ArrayList)25 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)22 ConfigurationException (javax.naming.ConfigurationException)22 ServerApiException (com.cloud.api.ServerApiException)19 TransactionStatus (com.cloud.utils.db.TransactionStatus)18 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)18 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)17 ActionEvent (com.cloud.event.ActionEvent)15 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)15