Search in sources :

Example 71 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException in project CloudStack-archive by CloudStack-extras.

the class CreateLoadBalancerRuleCmd method execute.

@Override
public void execute() throws ResourceAllocationException, ResourceUnavailableException {
    UserContext callerContext = UserContext.current();
    boolean success = true;
    LoadBalancer rule = null;
    try {
        UserContext.current().setEventDetails("Rule Id: " + getEntityId());
        if (getOpenFirewall()) {
            success = success && _firewallService.applyFirewallRules(getSourceIpAddressId(), callerContext.getCaller());
        }
        // State might be different after the rule is applied, so get new object here
        rule = _entityMgr.findById(LoadBalancer.class, getEntityId());
        LoadBalancerResponse lbResponse = new LoadBalancerResponse();
        if (rule != null) {
            lbResponse = _responseGenerator.createLoadBalancerResponse(rule);
            setResponseObject(lbResponse);
        }
        lbResponse.setResponseName(getCommandName());
    } catch (Exception ex) {
        s_logger.warn("Failed to create LB rule due to exception ", ex);
    } finally {
        if (!success || rule == null) {
            if (getOpenFirewall()) {
                _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
            }
            // no need to apply the rule on the backend as it exists in the db only
            _lbService.deleteLoadBalancerRule(getEntityId(), false);
            throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create load balancer rule");
        }
    }
}
Also used : LoadBalancerResponse(com.cloud.api.response.LoadBalancerResponse) ServerApiException(com.cloud.api.ServerApiException) UserContext(com.cloud.user.UserContext) LoadBalancer(com.cloud.network.rules.LoadBalancer) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ServerApiException(com.cloud.api.ServerApiException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException)

Example 72 with ResourceAllocationException

use of com.cloud.exception.ResourceAllocationException in project CloudStack-archive by CloudStack-extras.

the class listStorageNetworkIpRangeCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
    try {
        List<StorageNetworkIpRange> results = _storageNetworkService.listIpRange(this);
        ListResponse<StorageNetworkIpRangeResponse> response = new ListResponse<StorageNetworkIpRangeResponse>();
        List<StorageNetworkIpRangeResponse> resList = new ArrayList<StorageNetworkIpRangeResponse>(results.size());
        for (StorageNetworkIpRange r : results) {
            StorageNetworkIpRangeResponse resp = _responseGenerator.createStorageNetworkIpRangeResponse(r);
            resList.add(resp);
        }
        response.setResponses(resList);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
    } catch (Exception e) {
        s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId());
        throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : ListResponse(com.cloud.api.response.ListResponse) ServerApiException(com.cloud.api.ServerApiException) StorageNetworkIpRange(com.cloud.dc.StorageNetworkIpRange) StorageNetworkIpRangeResponse(com.cloud.api.response.StorageNetworkIpRangeResponse) ArrayList(java.util.ArrayList) 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 73 with ResourceAllocationException

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

the class VpcManagerImpl method createVpcPrivateGateway.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating VPC private gateway", create = true)
public PrivateGateway createVpcPrivateGateway(final long vpcId, final String ipAddress, final String gateway, final String netmask, final long gatewayDomainId, final Long networkId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    // Validate parameters
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
        ex.addProxyObject(String.valueOf(vpcId), "VPC");
        throw ex;
    }
    // permission check on the VPC
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    _accountMgr.checkAccess(caller, null, false, vpc);
    if (gateway != null || netmask != null) {
        throw new InvalidParameterValueException("Gateway/netmask fields are not supported anymore");
    }
    final Network privateNtwk = _ntwkDao.findById(networkId);
    if (privateNtwk == null) {
        throw new InvalidParameterValueException("The private network specified could not be found.");
    }
    if (privateNtwk.getDomainId() != vpc.getDomainId() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new InvalidParameterValueException("VPC '" + vpc.getName() + "' does not have permission to operate on private network '" + privateNtwk.getName() + "' as they need to belong to the same domain.");
    }
    if (NetUtils.isNetworkAWithinNetworkB(privateNtwk.getCidr(), vpc.getCidr())) {
        throw new InvalidParameterValueException("CIDR of the private network to be connected " + privateNtwk.getCidr() + " should be outside of the VPC super CIDR " + vpc.getCidr());
    }
    if (!NetUtils.isIpWithtInCidrRange(ipAddress, privateNtwk.getCidr())) {
        throw new InvalidParameterValueException("The specified ip address for the private network " + ipAddress + " should be within the CIDR of the private network " + privateNtwk.getCidr());
    }
    final SortedSet<Long> availableIps = _ntwkModel.getAvailableIps(privateNtwk, ipAddress);
    if (availableIps == null || availableIps.isEmpty()) {
        throw new InvalidParameterValueException("The requested ip address " + ipAddress + " is not available in private network " + privateNtwk.getName());
    }
    final Long privateNetworkId = privateNtwk.getId();
    final List<PrivateGateway> privateGateways = getVpcPrivateGateways(vpcId);
    for (final PrivateGateway privateGateway : privateGateways) {
        if (privateNetworkId == privateGateway.getNetworkId()) {
            throw new InvalidParameterValueException("VPC with uuid " + vpc.getUuid() + " is already connected to network '" + privateNtwk.getName() + "'");
        }
    }
    final VpcGatewayVO gatewayVO;
    try {
        gatewayVO = Transaction.execute(new TransactionCallbackWithException<VpcGatewayVO, Exception>() {

            @Override
            public VpcGatewayVO doInTransaction(final TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
                // create the nic/ip as createPrivateNetwork doesn't do that work for us now
                s_logger.info("found and using existing network for vpc " + vpc + ": " + privateNtwk.getBroadcastUri());
                final DataCenterVO dc = _dcDao.lockRow(vpc.getZoneId(), true);
                // add entry to private_ip_address table
                PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
                if (privateIp != null) {
                    throw new InvalidParameterValueException("Private IP address " + ipAddress + " already used for private gateway in zone " + _entityMgr.findById(DataCenter.class, vpc.getZoneId()).getName());
                }
                final Long mac = dc.getMacAddress();
                final Long nextMac = mac + 1;
                dc.setMacAddress(nextMac);
                s_logger.info("creating private IP address for VPC (" + ipAddress + ", " + privateNtwk.getId() + ", " + nextMac + ", " + vpcId + ", " + isSourceNat + ")");
                privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, isSourceNat);
                _privateIpDao.persist(privateIp);
                _dcDao.update(dc.getId(), dc);
                long networkAclId = NetworkACL.DEFAULT_DENY;
                if (aclId != null) {
                    final NetworkACLVO aclVO = _networkAclDao.findById(aclId);
                    if (aclVO == null) {
                        throw new InvalidParameterValueException("Invalid network acl id passed ");
                    }
                    if (aclVO.getVpcId() != vpcId && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
                        throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
                    }
                    networkAclId = aclId;
                }
                // 2) create gateway entry
                final VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
                _vpcGatewayDao.persist(gatewayVO);
                s_logger.debug("Created vpc gateway entry " + gatewayVO);
                return gatewayVO;
            }
        });
    } catch (final Exception e) {
        ExceptionUtil.rethrowRuntime(e);
        ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
        ExceptionUtil.rethrow(e, ResourceAllocationException.class);
        throw new IllegalStateException(e);
    }
    CallContext.current().setEventDetails("Private Gateway Id: " + gatewayVO.getId());
    return getVpcPrivateGateway(gatewayVO.getId());
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(com.cloud.context.CallContext) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ServerApiException(com.cloud.api.ServerApiException) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 74 with ResourceAllocationException

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

the class ResourceLimitManagerImpl method checkResourceLimit.

@Override
@DB
public void checkResourceLimit(final Account account, final ResourceType type, final long... count) throws ResourceAllocationException {
    final long numResources = ((count.length == 0) ? 1 : count[0]);
    Project project = null;
    // Don't place any limits on system or root admin accounts
    if (_accountMgr.isRootAdmin(account.getId())) {
        return;
    }
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        project = _projectDao.findByProjectAccountId(account.getId());
    }
    final Project projectFinal = project;
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) throws ResourceAllocationException {
            // Lock all rows first so nobody else can read it
            final Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type);
            final SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
            sc.setParameters("id", rowIdsToLock.toArray());
            _resourceCountDao.lockRows(sc, null, true);
            // Check account limits
            final long accountLimit = findCorrectResourceLimitForAccount(account, type);
            final long potentialCount = _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources;
            if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
                String message = "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName() + " in domain id=" + account.getDomainId() + " has been exceeded.";
                if (projectFinal != null) {
                    message = "Maximum number of resources of type '" + type + "' for project name=" + projectFinal.getName() + " in domain id=" + account.getDomainId() + " has been exceeded.";
                }
                final ResourceAllocationException e = new ResourceAllocationException(message, type);
                s_logger.error(message, e);
                throw e;
            }
            // check all domains in the account's domain hierarchy
            Long domainId;
            if (projectFinal != null) {
                domainId = projectFinal.getDomainId();
            } else {
                domainId = account.getDomainId();
            }
            while (domainId != null) {
                final DomainVO domain = _domainDao.findById(domainId);
                // no limit check if it is ROOT domain
                if (domainId != Domain.ROOT_DOMAIN) {
                    final long domainLimit = findCorrectResourceLimitForDomain(domain, type);
                    final long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type) + numResources;
                    if (domainLimit != Resource.RESOURCE_UNLIMITED && domainCount > domainLimit) {
                        throw new ResourceAllocationException("Maximum number of resources of type '" + type + "' for domain id=" + domainId + " has been exceeded.", type);
                    }
                }
                domainId = domain.getParent();
            }
        }
    });
}
Also used : Project(com.cloud.projects.Project) DomainVO(com.cloud.domain.DomainVO) Set(java.util.Set) TransactionStatus(com.cloud.utils.db.TransactionStatus) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) SearchCriteria(com.cloud.utils.db.SearchCriteria) DB(com.cloud.utils.db.DB)

Example 75 with ResourceAllocationException

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

the class AddNetworkServiceProviderCmdTest method testCreateProviderToPhysicalNetworkSuccess.

@Test
public void testCreateProviderToPhysicalNetworkSuccess() {
    final NetworkService networkService = Mockito.mock(NetworkService.class);
    addNetworkServiceProviderCmd._networkService = networkService;
    final PhysicalNetworkServiceProvider physicalNetworkServiceProvider = Mockito.mock(PhysicalNetworkServiceProvider.class);
    Mockito.when(networkService.addProviderToPhysicalNetwork(Matchers.anyLong(), Matchers.anyString(), Matchers.anyLong(), Matchers.anyList())).thenReturn(physicalNetworkServiceProvider);
    try {
        addNetworkServiceProviderCmd.create();
    } catch (final ResourceAllocationException e) {
        e.printStackTrace();
    }
}
Also used : NetworkService(com.cloud.network.NetworkService) PhysicalNetworkServiceProvider(com.cloud.network.PhysicalNetworkServiceProvider) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Test(org.junit.Test)

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