Search in sources :

Example 6 with ResourceAllocationException

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

the class UploadSslCertCmd method execute.

/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
    try {
        SslCertResponse response = _certService.uploadSslCert(this);
        setResponseObject(response);
        response.setResponseName(getCommandName());
    } catch (Exception e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) SslCertResponse(org.apache.cloudstack.api.response.SslCertResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Example 7 with ResourceAllocationException

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

the class CreateServiceInstanceCmd method create.

@Override
public void create() throws ResourceAllocationException {
    // Parameter validation
    try {
        DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
        if (zone == null) {
            throw new InvalidParameterValueException("Unable to find zone ID " + zoneId);
        }
        Account owner = _accountService.getActiveAccountById(getEntityOwnerId());
        VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId);
        if (template == null) {
            throw new InvalidParameterValueException("Invalid template ID " + templateId);
        }
        ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
        if (serviceOffering == null) {
            throw new InvalidParameterValueException("Invalid service offering ID " + serviceOfferingId);
        }
        Network left = _networkService.getNetwork(leftNetworkId);
        if (left == null) {
            throw new InvalidParameterValueException("Invalid ID for left network " + leftNetworkId);
        }
        Network right = _networkService.getNetwork(rightNetworkId);
        if (right == null) {
            throw new InvalidParameterValueException("Invalid ID for right network " + rightNetworkId);
        }
        if (name.isEmpty()) {
            throw new InvalidParameterValueException("service instance name is empty");
        }
        ServiceVirtualMachine svm = _vrouterService.createServiceInstance(zone, owner, template, serviceOffering, name, left, right);
        if (svm == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Unable to create service instance");
        }
        setEntityId(svm.getId());
        setEntityUuid(svm.getUuid());
    } catch (Exception ex) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    }
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ServiceOffering(com.cloud.offering.ServiceOffering) Network(com.cloud.network.Network) ServiceVirtualMachine(org.apache.cloudstack.network.contrail.management.ServiceVirtualMachine) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Example 8 with ResourceAllocationException

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

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 {
    IPAddressVO addr = Transaction.execute(new TransactionCallbackWithException<IPAddressVO, InsufficientAddressCapacityException>() {

        @Override
        public IPAddressVO doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
            StringBuilder errorMessage = new StringBuilder("Unable to get ip adress in ");
            boolean fetchFromDedicatedRange = false;
            List<Long> dedicatedVlanDbIds = new ArrayList<Long>();
            List<Long> nonDedicatedVlanDbIds = new ArrayList<Long>();
            DataCenter zone = _entityMgr.findById(DataCenter.class, dcId);
            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
            Network network = _networksDao.findById(guestNetworkId);
            //Checking if network is null in the case of system VM's. At the time of allocation of IP address to systemVm, no network is present.
            if (network == null || !(network.getGuestType() == GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) {
                List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByAccount(owner.getId());
                for (AccountVlanMapVO map : maps) {
                    if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId()))
                        dedicatedVlanDbIds.add(map.getVlanDbId());
                }
            }
            List<DomainVlanMapVO> domainMaps = _domainVlanMapDao.listDomainVlanMapsByDomain(owner.getDomainId());
            for (DomainVlanMapVO map : domainMaps) {
                if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId()))
                    dedicatedVlanDbIds.add(map.getVlanDbId());
            }
            List<VlanVO> nonDedicatedVlans = _vlanDao.listZoneWideNonDedicatedVlans(dcId);
            for (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) {
                    InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId);
                    ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid());
                    throw ex;
                }
                s_logger.warn(errorMessage.toString());
                InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId);
                ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid());
                throw ex;
            }
            sc.setParameters("dc", 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");
            }
            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
                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) {
                    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());
                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 (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.");
                }
            }
            IPAddressVO addr = addrs.get(0);
            addr.setSourceNat(sourceNat);
            addr.setAllocatedTime(new Date());
            addr.setAllocatedInDomainId(owner.getDomainId());
            addr.setAllocatedToAccountId(owner.getId());
            addr.setSystem(isSystem);
            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.dc.Pod) InsufficientAddressCapacityException(com.cloud.exception.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.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.exception.ResourceAllocationException) AccountLimitException(com.cloud.exception.AccountLimitException) DB(com.cloud.utils.db.DB)

Example 9 with ResourceAllocationException

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

the class IpAddressManagerImpl method associateIPToGuestNetwork.

@DB
@Override
public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
    Account caller = CallContext.current().getCallingAccount();
    Account owner = null;
    IPAddressVO ipToAssoc = _ipAddressDao.findById(ipId);
    if (ipToAssoc != null) {
        Network network = _networksDao.findById(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Invalid network id is given");
        }
        DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
        if (zone.getNetworkType() == NetworkType.Advanced) {
            if (network.getGuestType() == Network.GuestType.Shared) {
                if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
                    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, false, network);
                } else {
                    throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if " + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network");
                }
            }
        } else {
            _accountMgr.checkAccess(caller, null, true, ipToAssoc);
        }
        owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId());
    } else {
        s_logger.debug("Unable to find ip address by id: " + ipId);
        return null;
    }
    if (ipToAssoc.getAssociatedWithNetworkId() != null) {
        s_logger.debug("IP " + ipToAssoc + " is already assocaited with network id" + networkId);
        return ipToAssoc;
    }
    Network network = _networksDao.findById(networkId);
    if (network != null) {
        _accountMgr.checkAccess(owner, AccessType.UseEntry, false, network);
    } else {
        s_logger.debug("Unable to find ip address by id: " + ipId);
        return null;
    }
    DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
    // allow associating IP addresses to guest network only
    if (network.getTrafficType() != TrafficType.Guest) {
        throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest);
    }
    //     - and it belongs to the system
    if (network.getAccountId() != owner.getId()) {
        if (zone.getNetworkType() != NetworkType.Basic && !(zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Shared)) {
            throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP");
        }
    }
    if (zone.getNetworkType() == NetworkType.Advanced) {
        // In Advance zone allow to do IP assoc only for Isolated networks with source nat service enabled
        if (network.getGuestType() == GuestType.Isolated && !(_networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) {
            throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled");
        }
        // In Advance zone allow to do IP assoc only for shared networks with source nat/static nat/lb/pf services enabled
        if (network.getGuestType() == GuestType.Shared && !isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
            throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated with network of guest type " + GuestType.Shared + "only if at " + "least one of the services " + Service.SourceNat.getName() + "/" + Service.StaticNat.getName() + "/" + Service.Lb.getName() + "/" + Service.PortForwarding.getName() + " is enabled");
        }
    }
    NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
    boolean sharedSourceNat = offering.getSharedSourceNat();
    boolean isSourceNat = false;
    if (!sharedSourceNat) {
        if (getExistingSourceNatInNetwork(owner.getId(), networkId) == null) {
            if (network.getGuestType() == GuestType.Isolated && network.getVpcId() == null && !ipToAssoc.isPortable()) {
                isSourceNat = true;
            }
        }
    }
    s_logger.debug("Associating ip " + ipToAssoc + " to network " + network);
    IPAddressVO ip = _ipAddressDao.findById(ipId);
    //update ip address with networkId
    ip.setAssociatedWithNetworkId(networkId);
    ip.setSourceNat(isSourceNat);
    _ipAddressDao.update(ipId, ip);
    boolean success = false;
    try {
        success = applyIpAssociations(network, false);
        if (success) {
            s_logger.debug("Successfully associated ip address " + ip.getAddress().addr() + " to network " + network);
        } else {
            s_logger.warn("Failed to associate ip address " + ip.getAddress().addr() + " to network " + network);
        }
        return ip;
    } finally {
        if (!success && releaseOnFailure) {
            if (ip != null) {
                try {
                    s_logger.warn("Failed to associate ip address, so releasing ip from the database " + ip);
                    _ipAddressDao.markAsUnavailable(ip.getId());
                    if (!applyIpAssociations(network, true)) {
                        // if fail to apply ip assciations again, unassign ip address without updating resource
                        // count and generating usage event as there is no need to keep it in the db
                        _ipAddressDao.unassignIpAddress(ip.getId());
                    }
                } catch (Exception e) {
                    s_logger.warn("Unable to disassociate ip address for recovery", e);
                }
            }
        }
    }
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) NetworkOffering(com.cloud.offering.NetworkOffering) IPAddressVO(com.cloud.network.dao.IPAddressVO) AccountLimitException(com.cloud.exception.AccountLimitException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) DB(com.cloud.utils.db.DB)

Example 10 with ResourceAllocationException

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

the class IpAddressManagerImpl method assignSystemIp.

@Override
public IpAddress assignSystemIp(long networkId, Account owner, boolean forElasticLb, boolean forElasticIp) throws InsufficientAddressCapacityException {
    Network guestNetwork = _networksDao.findById(networkId);
    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 (ResourceAllocationException ex) {
            throw new CloudRuntimeException("Failed to allocate system ip due to ", ex);
        } catch (ConcurrentOperationException ex) {
            throw new CloudRuntimeException("Failed to allocate system lb ip due to ", ex);
        } catch (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.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException)

Aggregations

ResourceAllocationException (com.cloud.exception.ResourceAllocationException)58 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)40 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)40 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)37 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)26 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)21 ServerApiException (org.apache.cloudstack.api.ServerApiException)19 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)17 Account (com.cloud.user.Account)14 DB (com.cloud.utils.db.DB)14 ArrayList (java.util.ArrayList)13 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)12 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)11 ConfigurationException (javax.naming.ConfigurationException)10 TransactionStatus (com.cloud.utils.db.TransactionStatus)9 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)8 DataCenter (com.cloud.dc.DataCenter)7 StorageNetworkIpRange (com.cloud.dc.StorageNetworkIpRange)6 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)6 Date (java.util.Date)6