Search in sources :

Example 1 with AccountLimitException

use of com.cloud.legacymodel.exceptions.AccountLimitException in project cosmic by MissionCriticalCloud.

the class IpAddressManagerImpl method fetchNewPublicIp.

@DB
public PublicIp fetchNewPublicIp(final long dcId, final Long podId, final List<Long> vlanDbIds, final Account owner, final VlanType vlanUse, final Long guestNetworkId, final boolean sourceNat, final boolean assign, final String requestedIp, final boolean isSystem, final Long vpcId, final Boolean displayIp) throws InsufficientAddressCapacityException {
    final IPAddressVO addr = Transaction.execute(new TransactionCallbackWithException<IPAddressVO, InsufficientAddressCapacityException>() {

        @Override
        public IPAddressVO doInTransaction(final TransactionStatus status) throws InsufficientAddressCapacityException {
            final StringBuilder errorMessage = new StringBuilder("Unable to get ip adress in ");
            boolean fetchFromDedicatedRange = false;
            final List<Long> dedicatedVlanDbIds = new ArrayList<>();
            final List<Long> nonDedicatedVlanDbIds = new ArrayList<>();
            SearchCriteria<IPAddressVO> sc = null;
            if (podId != null) {
                sc = AssignIpAddressFromPodVlanSearch.create();
                sc.setJoinParameters("podVlanMapSB", "podId", podId);
                errorMessage.append(" pod id=" + podId);
            } else {
                sc = AssignIpAddressSearch.create();
                errorMessage.append(" zone id=" + dcId);
            }
            // If owner has dedicated Public IP ranges, fetch IP from the dedicated range
            // Otherwise fetch IP from the system pool
            final List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByAccount(owner.getId());
            for (final AccountVlanMapVO map : maps) {
                if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId())) {
                    dedicatedVlanDbIds.add(map.getVlanDbId());
                }
            }
            final List<DomainVlanMapVO> domainMaps = _domainVlanMapDao.listDomainVlanMapsByDomain(owner.getDomainId());
            for (final DomainVlanMapVO map : domainMaps) {
                if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId())) {
                    dedicatedVlanDbIds.add(map.getVlanDbId());
                }
            }
            final List<VlanVO> nonDedicatedVlans = _vlanDao.listZoneWideNonDedicatedVlans(dcId);
            for (final VlanVO nonDedicatedVlan : nonDedicatedVlans) {
                if (vlanDbIds == null || vlanDbIds.contains(nonDedicatedVlan.getId())) {
                    nonDedicatedVlanDbIds.add(nonDedicatedVlan.getId());
                }
            }
            if (dedicatedVlanDbIds != null && !dedicatedVlanDbIds.isEmpty()) {
                fetchFromDedicatedRange = true;
                sc.setParameters("vlanId", dedicatedVlanDbIds.toArray());
                errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray()));
            } else if (nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) {
                sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
                errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
            } else {
                if (podId != null) {
                    final InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId);
                    ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid());
                    throw ex;
                }
                s_logger.warn(errorMessage.toString());
                final InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId);
                ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid());
                throw ex;
            }
            sc.setParameters("dc", dcId);
            final DataCenter zone = _entityMgr.findById(DataCenter.class, dcId);
            // for direct network take ip addresses only from the vlans belonging to the network
            if (vlanUse == VlanType.DirectAttached) {
                sc.setJoinParameters("vlan", "networkId", guestNetworkId);
                errorMessage.append(", network id=" + guestNetworkId);
            }
            sc.setJoinParameters("vlan", "type", vlanUse);
            if (requestedIp != null) {
                sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp);
                errorMessage.append(": requested ip " + requestedIp + " is not available");
            }
            final Filter filter = new Filter(IPAddressVO.class, "vlanId", true, 0l, 1l);
            List<IPAddressVO> addrs = _ipAddressDao.lockRows(sc, filter, true);
            // If all the dedicated IPs of the owner are in use fetch an IP from the system pool
            if (addrs.size() == 0 && fetchFromDedicatedRange) {
                // Verify if account is allowed to acquire IPs from the system
                final boolean useSystemIps = UseSystemPublicIps.valueIn(owner.getId());
                if (useSystemIps && nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) {
                    fetchFromDedicatedRange = false;
                    sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
                    errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
                    addrs = _ipAddressDao.lockRows(sc, filter, true);
                }
            }
            if (addrs.size() == 0) {
                if (podId != null) {
                    final InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId);
                    // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object.
                    ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid());
                    throw ex;
                }
                s_logger.warn(errorMessage.toString());
                final InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId);
                ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid());
                throw ex;
            }
            assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size();
            if (!fetchFromDedicatedRange && VlanType.VirtualNetwork.equals(vlanUse)) {
                // Check that the maximum number of public IPs for the given accountId will not be exceeded
                try {
                    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.public_ip);
                } catch (final ResourceAllocationException ex) {
                    s_logger.warn("Failed to allocate resource of type " + ex.getResourceType() + " for account " + owner);
                    throw new AccountLimitException("Maximum number of public IP addresses for account: " + owner.getAccountName() + " has been exceeded.");
                }
            }
            final IPAddressVO addr = addrs.get(0);
            addr.setSourceNat(sourceNat);
            addr.setAllocatedTime(new Date());
            addr.setAllocatedInDomainId(owner.getDomainId());
            addr.setAllocatedToAccountId(owner.getId());
            addr.setSystem(isSystem);
            addr.setIpACLId(NetworkACL.DEFAULT_ALLOW);
            if (displayIp != null) {
                addr.setDisplay(displayIp);
            }
            if (assign) {
                markPublicIpAsAllocated(addr);
            } else {
                addr.setState(IpAddress.State.Allocating);
            }
            addr.setState(assign ? IpAddress.State.Allocated : IpAddress.State.Allocating);
            if (vlanUse != VlanType.DirectAttached) {
                addr.setAssociatedWithNetworkId(guestNetworkId);
                addr.setVpcId(vpcId);
            }
            _ipAddressDao.update(addr.getId(), addr);
            return addr;
        }
    });
    if (vlanUse == VlanType.VirtualNetwork) {
        _firewallMgr.addSystemFirewallRules(addr, owner);
    }
    return PublicIp.createFromAddrAndVlan(addr, _vlanDao.findById(addr.getVlanId()));
}
Also used : Pod(com.cloud.legacymodel.dc.Pod) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) SearchCriteria(com.cloud.utils.db.SearchCriteria) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) Date(java.util.Date) DataCenter(com.cloud.legacymodel.dc.DataCenter) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO) ArrayList(java.util.ArrayList) List(java.util.List) VlanVO(com.cloud.dc.VlanVO) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) AccountLimitException(com.cloud.legacymodel.exceptions.AccountLimitException) DB(com.cloud.utils.db.DB)

Example 2 with AccountLimitException

use of com.cloud.legacymodel.exceptions.AccountLimitException in project cosmic by MissionCriticalCloud.

the class ApiServer method handleRequest.

@Override
public String handleRequest(final Map params, final String responseType, final StringBuilder auditTrailSb) throws ServerApiException {
    checkCharacterInkParams(params);
    final String response;
    String[] command = null;
    try {
        command = (String[]) params.get("command");
        if (command == null) {
            s_logger.error("invalid request, no command sent");
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("dumping request parameters");
                for (final Object key : params.keySet()) {
                    final String keyStr = (String) key;
                    final String[] value = (String[]) params.get(key);
                    s_logger.trace("   key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
                }
            }
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
        } else {
            // Don't allow Login/Logout APIs to go past this point
            if (_authManager.getAPIAuthenticator(command[0]) != null) {
                return null;
            }
            final Map<String, String> paramMap = new HashMap<>();
            final Set keys = params.keySet();
            final Iterator keysIter = keys.iterator();
            while (keysIter.hasNext()) {
                final String key = (String) keysIter.next();
                if ("command".equalsIgnoreCase(key)) {
                    continue;
                }
                final String[] value = (String[]) params.get(key);
                paramMap.put(key, value[0]);
            }
            final Class<?> cmdClass = getCmdClass(command[0]);
            if (cmdClass != null) {
                final APICommand annotation = cmdClass.getAnnotation(APICommand.class);
                if (annotation == null) {
                    s_logger.error("No APICommand annotation found for class " + cmdClass.getCanonicalName());
                    throw new CloudRuntimeException("No APICommand annotation found for class " + cmdClass.getCanonicalName());
                }
                BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
                cmdObj = ComponentContext.inject(cmdObj);
                cmdObj.configure();
                cmdObj.setFullUrlParams(paramMap);
                cmdObj.setResponseType(responseType);
                cmdObj.setHttpMethod(paramMap.get(ApiConstants.HTTPMETHOD).toString());
                // This is where the command is either serialized, or directly dispatched
                final StringBuilder log = new StringBuilder();
                response = queueCommand(cmdObj, paramMap, log);
                buildAuditTrail(auditTrailSb, command[0], log.toString());
            } else {
                final String errorString = "Unknown API command: " + command[0];
                s_logger.warn(errorString);
                auditTrailSb.append(" " + errorString);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString);
            }
        }
    } catch (final InvalidParameterValueException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (final IllegalArgumentException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (final PermissionDeniedException ex) {
        final ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
        if (idList != null) {
            final StringBuffer buf = new StringBuffer();
            for (final ExceptionProxyObject obj : idList) {
                buf.append(obj.getDescription());
                buf.append(":");
                buf.append(obj.getUuid());
                buf.append(" ");
            }
            s_logger.info("PermissionDenied: " + ex.getMessage() + " on objs: [" + buf.toString() + "]");
        } else {
            s_logger.info("PermissionDenied: " + ex.getMessage());
        }
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
    } catch (final AccountLimitException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
    } catch (final InsufficientCapacityException ex) {
        s_logger.info(ex.getMessage());
        String errorMsg = ex.getMessage();
        if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
    } catch (final ResourceAllocationException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage(), ex);
    } catch (final ResourceUnavailableException ex) {
        s_logger.info(ex.getMessage());
        String errorMsg = ex.getMessage();
        if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
    } catch (final ServerApiException ex) {
        s_logger.info(ex.getDescription());
        throw ex;
    } catch (final Exception ex) {
        s_logger.error("Unhandled exception executing api command: " + ((command == null) ? "null" : printCommand(command)), ex);
        String errorMsg = ex.getMessage();
        if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
    }
    return response;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) EventBusException(com.cloud.framework.events.EventBusException) HttpException(org.apache.http.HttpException) AccountLimitException(com.cloud.legacymodel.exceptions.AccountLimitException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) RequestLimitException(com.cloud.legacymodel.exceptions.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ParseException(java.text.ParseException) CloudAuthenticationException(com.cloud.legacymodel.exceptions.CloudAuthenticationException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Iterator(java.util.Iterator) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ExceptionProxyObject(com.cloud.legacymodel.exceptions.ExceptionProxyObject) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ExceptionProxyObject(com.cloud.legacymodel.exceptions.ExceptionProxyObject) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) AccountLimitException(com.cloud.legacymodel.exceptions.AccountLimitException)

Aggregations

AccountLimitException (com.cloud.legacymodel.exceptions.AccountLimitException)2 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)2 ArrayList (java.util.ArrayList)2 AccountVlanMapVO (com.cloud.dc.AccountVlanMapVO)1 DomainVlanMapVO (com.cloud.dc.DomainVlanMapVO)1 VlanVO (com.cloud.dc.VlanVO)1 EventBusException (com.cloud.framework.events.EventBusException)1 DataCenter (com.cloud.legacymodel.dc.DataCenter)1 Pod (com.cloud.legacymodel.dc.Pod)1 CloudAuthenticationException (com.cloud.legacymodel.exceptions.CloudAuthenticationException)1 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)1 ExceptionProxyObject (com.cloud.legacymodel.exceptions.ExceptionProxyObject)1 InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)1 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)1 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)1 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)1 RequestLimitException (com.cloud.legacymodel.exceptions.RequestLimitException)1 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)1 IPAddressVO (com.cloud.network.dao.IPAddressVO)1 DB (com.cloud.utils.db.DB)1