Search in sources :

Example 1 with ResourceAllocationException

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

the class IpAddressManagerImpl method assignSystemIp.

@Override
public IpAddress assignSystemIp(final long networkId, final Account owner, final boolean forElasticLb, final boolean forElasticIp) throws InsufficientAddressCapacityException {
    final Network guestNetwork = _networksDao.findById(networkId);
    final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
    IpAddress ip = null;
    if ((off.getElasticLb() && forElasticLb) || (off.getElasticIp() && forElasticIp)) {
        try {
            s_logger.debug("Allocating system IP address for load balancer rule...");
            // allocate ip
            ip = allocateIP(owner, true, guestNetwork.getDataCenterId());
            // apply ip associations
            ip = associateIPToGuestNetwork(ip.getId(), networkId, true);
        } catch (final ResourceAllocationException ex) {
            throw new CloudRuntimeException("Failed to allocate system ip due to ", ex);
        } catch (final ConcurrentOperationException ex) {
            throw new CloudRuntimeException("Failed to allocate system lb ip due to ", ex);
        } catch (final ResourceUnavailableException ex) {
            throw new CloudRuntimeException("Failed to allocate system lb ip due to ", ex);
        }
        if (ip == null) {
            throw new CloudRuntimeException("Failed to allocate system ip");
        }
    }
    return ip;
}
Also used : NetworkOffering(com.cloud.offering.NetworkOffering) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException)

Example 2 with ResourceAllocationException

use of com.cloud.legacymodel.exceptions.ResourceAllocationException 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 3 with ResourceAllocationException

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

the class NetworkServiceImpl method createPrivateNetwork.

@Override
@DB
public Network createPrivateNetwork(final String networkName, final String displayText, final long physicalNetworkId, final String broadcastUriString, final String startIp, String endIp, final String gateway, final String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    final Account owner = _accountMgr.getAccount(networkOwnerId);
    // Get system network offering
    NetworkOfferingVO ntwkOff = null;
    if (networkOfferingId != null) {
        ntwkOff = _networkOfferingDao.findById(networkOfferingId);
    }
    if (ntwkOff == null) {
        ntwkOff = findSystemNetworkOffering(NetworkOffering.DefaultPrivateGatewayNetworkOffering);
    }
    // Validate physical network
    final PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
    if (pNtwk == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" + " having the given id");
        ex.addProxyObject(String.valueOf(physicalNetworkId), "physicalNetworkId");
        throw ex;
    }
    // if end ip is not specified, default it to startIp
    if (!NetUtils.isValidIp4(startIp)) {
        throw new InvalidParameterValueException("Invalid format for the ip address parameter");
    }
    if (endIp == null) {
        endIp = startIp;
    } else if (!NetUtils.isValidIp4(endIp)) {
        throw new InvalidParameterValueException("Invalid format for the endIp address parameter");
    }
    if (!NetUtils.isValidIp4(gateway)) {
        throw new InvalidParameterValueException("Invalid gateway");
    }
    if (!NetUtils.isValidIp4Netmask(netmask)) {
        throw new InvalidParameterValueException("Invalid netmask");
    }
    final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
    final URI uri = BroadcastDomainType.fromString(broadcastUriString);
    final String uriString = uri.toString();
    final BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
    // TODO make a test for any supported scheme
    if (!(tiep == BroadcastDomainType.Vlan || tiep == BroadcastDomainType.Lswitch)) {
        throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
    }
    final NetworkOfferingVO ntwkOffFinal = ntwkOff;
    try {
        return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {

            @Override
            public Network doInTransaction(final TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
                // lock datacenter as we need to get mac address seq from there
                final DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
                // check if we need to create guest network
                Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId);
                if (privateNetwork == null) {
                    // create Guest network
                    privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null, dc.getDns1(), dc.getDns2(), null, null, null);
                    if (privateNetwork != null) {
                        s_logger.debug("Successfully created guest network " + privateNetwork);
                    } else {
                        throw new CloudRuntimeException("Creating guest network failed");
                    }
                } else {
                    s_logger.debug("Private network already exists: " + privateNetwork);
                    // Do not allow multiple private gateways with same Vlan within a VPC
                    if (vpcId != null && vpcId.equals(privateNetwork.getVpcId())) {
                        throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr  " + cidr + "  already exists " + "for Vpc " + vpcId + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
                    }
                }
                if (vpcId != null) {
                    // add entry to private_ip_address table
                    PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
                    if (privateIp != null) {
                        throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
                    }
                    final Long mac = dc.getMacAddress();
                    final Long nextMac = mac + 1;
                    dc.setMacAddress(nextMac);
                    privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
                    _privateIpDao.persist(privateIp);
                    _dcDao.update(dc.getId(), dc);
                }
                s_logger.debug("Private network " + privateNetwork + " is created");
                return privateNetwork;
            }
        });
    } catch (final Exception e) {
        ExceptionUtil.rethrowRuntime(e);
        ExceptionUtil.rethrow(e, ResourceAllocationException.class);
        ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
        throw new IllegalStateException(e);
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.legacymodel.user.Account) TransactionStatus(com.cloud.utils.db.TransactionStatus) PrivateIpVO(com.cloud.network.vpc.PrivateIpVO) URI(java.net.URI) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) SQLException(java.sql.SQLException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) UnknownHostException(java.net.UnknownHostException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) UnsupportedServiceException(com.cloud.legacymodel.exceptions.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) BroadcastDomainType(com.cloud.model.enumeration.BroadcastDomainType) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) DB(com.cloud.utils.db.DB)

Example 4 with ResourceAllocationException

use of com.cloud.legacymodel.exceptions.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.legacymodel.dc.StorageNetworkIpRange) StorageNetworkIpRangeResponse(com.cloud.api.response.StorageNetworkIpRangeResponse) ServerApiException(com.cloud.api.ServerApiException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException)

Example 5 with ResourceAllocationException

use of com.cloud.legacymodel.exceptions.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.legacymodel.dc.StorageNetworkIpRange) StorageNetworkIpRangeResponse(com.cloud.api.response.StorageNetworkIpRangeResponse) ServerApiException(com.cloud.api.ServerApiException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException)

Aggregations

ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)37 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)20 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)19 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)18 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)18 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)17 ServerApiException (com.cloud.api.ServerApiException)14 DB (com.cloud.utils.db.DB)13 Account (com.cloud.legacymodel.user.Account)11 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)8 ArrayList (java.util.ArrayList)8 ConfigurationException (javax.naming.ConfigurationException)8 InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)7 ExecutionException (java.util.concurrent.ExecutionException)6 NetworkRuleConflictException (com.cloud.legacymodel.exceptions.NetworkRuleConflictException)5 Network (com.cloud.legacymodel.network.Network)5 HypervisorType (com.cloud.model.enumeration.HypervisorType)5 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)5 VolumeInfo (com.cloud.engine.subsystem.api.storage.VolumeInfo)4