Search in sources :

Example 46 with ResourceAllocationException

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

the class UserVmManagerImpl method verifyVmLimits.

private void verifyVmLimits(UserVmVO vmInstance, Map<String, String> details) {
    Account owner = _accountDao.findById(vmInstance.getAccountId());
    if (owner == null) {
        throw new InvalidParameterValueException("The owner of " + vmInstance + " does not exist: " + vmInstance.getAccountId());
    }
    long newCpu = NumberUtils.toLong(details.get(VmDetailConstants.CPU_NUMBER));
    long newMemory = NumberUtils.toLong(details.get(VmDetailConstants.MEMORY));
    ServiceOfferingVO currentServiceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
    ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vmInstance.getServiceOfferingId());
    boolean isDynamic = currentServiceOffering.isDynamic();
    if (isDynamic) {
        Map<String, String> customParameters = new HashMap<>();
        customParameters.put(VmDetailConstants.CPU_NUMBER, String.valueOf(newCpu));
        customParameters.put(VmDetailConstants.MEMORY, String.valueOf(newMemory));
        customParameters.put(VmDetailConstants.CPU_SPEED, details.get(VmDetailConstants.CPU_SPEED));
        validateCustomParameters(svcOffering, customParameters);
    }
    if (VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
        return;
    }
    long currentCpu = currentServiceOffering.getCpu();
    long currentMemory = currentServiceOffering.getRamSize();
    try {
        if (newCpu > currentCpu) {
            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.cpu, newCpu - currentCpu);
        }
        if (newMemory > currentMemory) {
            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.memory, newMemory - currentMemory);
        }
    } catch (ResourceAllocationException e) {
        s_logger.error(String.format("Failed to updated VM due to: %s", e.getLocalizedMessage()));
        throw new InvalidParameterValueException(e.getLocalizedMessage());
    }
    if (newCpu > currentCpu) {
        _resourceLimitMgr.incrementResourceCount(owner.getAccountId(), ResourceType.cpu, newCpu - currentCpu);
    } else if (newCpu > 0 && currentCpu > newCpu) {
        _resourceLimitMgr.decrementResourceCount(owner.getAccountId(), ResourceType.cpu, currentCpu - newCpu);
    }
    if (newMemory > currentMemory) {
        _resourceLimitMgr.incrementResourceCount(owner.getAccountId(), ResourceType.memory, newMemory - currentMemory);
    } else if (newMemory > 0 && currentMemory > newMemory) {
        _resourceLimitMgr.decrementResourceCount(owner.getAccountId(), ResourceType.memory, currentMemory - newMemory);
    }
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Example 47 with ResourceAllocationException

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

the class UserVmManagerImpl method recoverVirtualMachine.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VM_RECOVER, eventDescription = "Recovering VM")
public UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
    final Long vmId = cmd.getId();
    Account caller = CallContext.current().getCallingAccount();
    final Long userId = caller.getAccountId();
    // Verify input parameters
    final UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    // When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
    if (!_accountMgr.isAdmin(userId) && !AllowUserExpungeRecoverVm.valueIn(userId)) {
        throw new PermissionDeniedException("Recovering a vm can only be done by an Admin. Or when the allow.user.expunge.recover.vm key is set.");
    }
    if (vm.getRemoved() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unable to find vm or vm is removed: " + vmId);
        }
        throw new InvalidParameterValueException("Unable to find vm by id " + vmId);
    }
    if (vm.getState() != State.Destroyed) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("vm is not in the right state: " + vmId);
        }
        throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Recovering vm " + vmId);
    }
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
            Account account = _accountDao.lockRow(vm.getAccountId(), true);
            // if the account is deleted, throw error
            if (account.getRemoved() != null) {
                throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
            }
            // Get serviceOffering for Virtual Machine
            ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
            // accountId will not be exceeded
            if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
                resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
            }
            _haMgr.cancelDestroy(vm, vm.getHostId());
            try {
                if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) {
                    s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId);
                    throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
                }
            } catch (NoTransitionException e) {
                throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
            }
            // Recover the VM's disks
            List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
            for (VolumeVO volume : volumes) {
                if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
                    // Create an event
                    Long templateId = volume.getTemplateId();
                    Long diskOfferingId = volume.getDiskOfferingId();
                    Long offeringId = null;
                    if (diskOfferingId != null) {
                        DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
                        if (offering != null && !offering.isComputeOnly()) {
                            offeringId = offering.getId();
                        }
                    }
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
                }
            }
            // Update Resource Count for the given account
            resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
        }
    });
    return _vmDao.findById(vmId);
}
Also used : Account(com.cloud.user.Account) TransactionStatus(com.cloud.utils.db.TransactionStatus) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 48 with ResourceAllocationException

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

the class UserVmManagerImpl method startVirtualMachine.

private UserVm startVirtualMachine(long vmId, Long podId, Long clusterId, Long hostId, Map<Long, DiskOffering> diskOfferingMap, Map<VirtualMachineProfile.Param, Object> additonalParams, String deploymentPlannerToUse) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
    UserVmVO vm = _vmDao.findById(vmId);
    Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = null;
    try {
        vmParamPair = startVirtualMachine(vmId, podId, clusterId, hostId, additonalParams, deploymentPlannerToUse);
        vm = vmParamPair.first();
        // At this point VM should be in "Running" state
        UserVmVO tmpVm = _vmDao.findById(vm.getId());
        if (!tmpVm.getState().equals(State.Running)) {
            // Some other thread changed state of VM, possibly vmsync
            s_logger.error("VM " + tmpVm + " unexpectedly went to " + tmpVm.getState() + " state");
            throw new ConcurrentOperationException("Failed to deploy VM " + vm);
        }
        try {
            if (!diskOfferingMap.isEmpty()) {
                List<VolumeVO> vols = _volsDao.findByInstance(tmpVm.getId());
                for (VolumeVO vol : vols) {
                    if (vol.getVolumeType() == Volume.Type.DATADISK) {
                        DiskOffering doff = _entityMgr.findById(DiskOffering.class, vol.getDiskOfferingId());
                        _volService.resizeVolumeOnHypervisor(vol.getId(), doff.getDiskSize(), tmpVm.getHostId(), vm.getInstanceName());
                    }
                }
            }
        } catch (Exception e) {
            s_logger.fatal("Unable to resize the data disk for vm " + vm.getDisplayName() + " due to " + e.getMessage(), e);
        }
    } finally {
        updateVmStateForFailedVmCreation(vm.getId(), hostId);
    }
    // Check that the password was passed in and is valid
    VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
    if (template.isEnablePassword()) {
        // this value is not being sent to the backend; need only for api
        // display purposes
        vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
    }
    return vm;
}
Also used : DiskOffering(com.cloud.offering.DiskOffering) VolumeVO(com.cloud.storage.VolumeVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) IOException(java.io.IOException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) AffinityConflictException(com.cloud.exception.AffinityConflictException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException)

Example 49 with ResourceAllocationException

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

the class CreateStorageNetworkIpRangeCmd method execute.

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

Example 50 with ResourceAllocationException

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

the class UpdateStorageNetworkIpRangeCmd method execute.

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