Search in sources :

Example 6 with AccountVlanMapVO

use of com.cloud.dc.AccountVlanMapVO in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method deleteVlanAndPublicIpRange.

@Override
@DB
public boolean deleteVlanAndPublicIpRange(final long userId, final long vlanDbId, final Account caller) {
    VlanVO vlanRange = _vlanDao.findById(vlanDbId);
    if (vlanRange == null) {
        throw new InvalidParameterValueException("Please specify a valid IP range id.");
    }
    boolean isAccountSpecific = false;
    final List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanRange.getId());
    // account_vlan_map.
    if (acctVln != null && !acctVln.isEmpty()) {
        isAccountSpecific = true;
    }
    final List<DomainVlanMapVO> domainVln = _domainVlanMapDao.listDomainVlanMapsByVlan(vlanRange.getId());
    // Check for domain wide pool. It will have an entry for domain_vlan_map.
    if (domainVln != null && !domainVln.isEmpty()) {
    }
    // Check if the VLAN has any allocated public IPs
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    if (isAccountSpecific) {
        int resourceCountToBeDecrement = 0;
        try {
            vlanRange = _vlanDao.acquireInLockTable(vlanDbId, 30);
            if (vlanRange == null) {
                throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId);
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("lock vlan " + vlanDbId + " is acquired");
            }
            for (final IPAddressVO ip : ips) {
                boolean success = true;
                if (ip.isOneToOneNat()) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first");
                }
                if (ip.isSourceNat()) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal");
                }
                if (_firewallDao.countRulesByIpId(ip.getId()) > 0) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range has firewall rules applied. Cleanup the rules first");
                }
                if (ip.getAllocatedTime() != null) {
                    // This means IP is allocated
                    // release public ip address here
                    success = _ipAddrMgr.disassociatePublicIpAddress(ip.getId(), userId, caller);
                }
                if (!success) {
                    s_logger.warn("Some ip addresses failed to be released as a part of vlan " + vlanDbId + " removal");
                } else {
                    resourceCountToBeDecrement++;
                }
            }
        } finally {
            _vlanDao.releaseFromLockTable(vlanDbId);
            if (resourceCountToBeDecrement > 0) {
                // Making sure to decrement the count of only success operations above. For any reaason if disassociation fails then this
                // number will vary from original range length.
                _resourceLimitMgr.decrementResourceCount(acctVln.get(0).getAccountId(), ResourceType.public_ip, new Long(resourceCountToBeDecrement));
            }
        }
    } else {
        // !isAccountSpecific
        final long allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
        if (allocIpCount > 0) {
            throw new InvalidParameterValueException(allocIpCount + "  Ips are in use. Cannot delete this vlan");
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            _publicIpAddressDao.deletePublicIPRange(vlanDbId);
            _vlanDao.remove(vlanDbId);
        }
    });
    return true;
}
Also used : AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 7 with AccountVlanMapVO

use of com.cloud.dc.AccountVlanMapVO 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);
            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 8 with AccountVlanMapVO

use of com.cloud.dc.AccountVlanMapVO in project cloudstack by apache.

the class ConfigurationManagerImpl method releasePublicIpRange.

@DB
public boolean releasePublicIpRange(final long vlanDbId, final long userId, final Account caller) {
    VlanVO vlan = _vlanDao.findById(vlanDbId);
    if (vlan == null) {
        // Nothing to do if vlan can't be found
        s_logger.warn(String.format("Skipping the process for releasing public IP range as could not find a VLAN with ID '%s' for Account '%s' and User '%s'.", vlanDbId, caller, userId));
        return true;
    }
    // Verify range is dedicated
    boolean isAccountSpecific = false;
    final List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanDbId);
    // Verify range is dedicated
    if (acctVln != null && !acctVln.isEmpty()) {
        isAccountSpecific = true;
    }
    boolean isDomainSpecific = false;
    final List<DomainVlanMapVO> domainVlan = _domainVlanMapDao.listDomainVlanMapsByVlan(vlanDbId);
    // Check for domain wide pool. It will have an entry for domain_vlan_map.
    if (domainVlan != null && !domainVlan.isEmpty()) {
        isDomainSpecific = true;
    }
    if (!isAccountSpecific && !isDomainSpecific) {
        throw new InvalidParameterValueException("Can't release Public IP range " + vlanDbId + " as it not dedicated to any domain and any account");
    }
    // Check if range has any allocated public IPs
    final long allocIpCount = _publicIpAddressDao.countIPs(vlan.getDataCenterId(), vlanDbId, true);
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    boolean success = true;
    final List<IPAddressVO> ipsInUse = new ArrayList<IPAddressVO>();
    if (allocIpCount > 0) {
        try {
            vlan = _vlanDao.acquireInLockTable(vlanDbId, 30);
            if (vlan == null) {
                throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId);
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("lock vlan " + vlanDbId + " is acquired");
            }
            for (final IPAddressVO ip : ips) {
                // Disassociate allocated IP's that are not in use
                if (!ip.isOneToOneNat() && !ip.isSourceNat() && !(_firewallDao.countRulesByIpId(ip.getId()) > 0)) {
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Releasing Public IP addresses" + ip + " of vlan " + vlanDbId + " as part of Public IP" + " range release to the system pool");
                    }
                    success = success && _ipAddrMgr.disassociatePublicIpAddress(ip.getId(), userId, caller);
                } else {
                    ipsInUse.add(ip);
                }
            }
            if (!success) {
                s_logger.warn("Some Public IP addresses that were not in use failed to be released as a part of" + " vlan " + vlanDbId + "release to the system pool");
            }
        } finally {
            _vlanDao.releaseFromLockTable(vlanDbId);
        }
    }
    // A Public IP range can only be dedicated to one account at a time
    if (isAccountSpecific && _accountVlanMapDao.remove(acctVln.get(0).getId())) {
        // generate usage events to remove dedication for every ip in the range that has been disassociated
        for (final IPAddressVO ip : ips) {
            if (!ipsInUse.contains(ip)) {
                final boolean usageHidden = _ipAddrMgr.isUsageHidden(ip);
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getAccountId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), usageHidden, ip.getClass().getName(), ip.getUuid());
            }
        }
        // decrement resource count for dedicated public ip's
        _resourceLimitMgr.decrementResourceCount(acctVln.get(0).getAccountId(), ResourceType.public_ip, new Long(ips.size()));
        success = true;
    } else if (isDomainSpecific && _domainVlanMapDao.remove(domainVlan.get(0).getId())) {
        s_logger.debug("Remove the vlan from domain_vlan_map successfully.");
        success = true;
    } else {
        success = false;
    }
    return success;
}
Also used : AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) ArrayList(java.util.ArrayList) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 9 with AccountVlanMapVO

use of com.cloud.dc.AccountVlanMapVO in project cloudstack by apache.

the class ConfigurationManagerTest method setup.

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(configurationMgr._accountMgr.getAccount(anyLong())).thenReturn(account);
    when(configurationMgr._accountDao.findActiveAccount(anyString(), anyLong())).thenReturn(account);
    when(configurationMgr._accountMgr.getActiveAccountById(anyLong())).thenReturn(account);
    UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    when(configurationMgr._publicIpAddressDao.countIPs(anyLong(), anyLong(), anyBoolean())).thenReturn(1);
    doNothing().when(configurationMgr._resourceLimitMgr).checkResourceLimit(any(Account.class), any(ResourceType.class), anyLong());
    when(configurationMgr._accountVlanMapDao.persist(any(AccountVlanMapVO.class))).thenReturn(new AccountVlanMapVO());
    when(configurationMgr._vlanDao.acquireInLockTable(anyLong(), anyInt())).thenReturn(vlan);
    Field dedicateIdField = _dedicatePublicIpRangeClass.getDeclaredField("id");
    dedicateIdField.setAccessible(true);
    dedicateIdField.set(dedicatePublicIpRangesCmd, 1L);
    Field accountNameField = _dedicatePublicIpRangeClass.getDeclaredField("accountName");
    accountNameField.setAccessible(true);
    accountNameField.set(dedicatePublicIpRangesCmd, "accountname");
    Field projectIdField = _dedicatePublicIpRangeClass.getDeclaredField("projectId");
    projectIdField.setAccessible(true);
    projectIdField.set(dedicatePublicIpRangesCmd, null);
    Field domainIdField = _dedicatePublicIpRangeClass.getDeclaredField("domainId");
    domainIdField.setAccessible(true);
    domainIdField.set(dedicatePublicIpRangesCmd, 1L);
    Field releaseIdField = _releasePublicIpRangeClass.getDeclaredField("id");
    releaseIdField.setAccessible(true);
    releaseIdField.set(releasePublicIpRangesCmd, 1L);
}
Also used : Account(com.cloud.user.Account) Field(java.lang.reflect.Field) UserVO(com.cloud.user.UserVO) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) ResourceType(com.cloud.configuration.Resource.ResourceType) AccountVO(com.cloud.user.AccountVO) Before(org.junit.Before)

Example 10 with AccountVlanMapVO

use of com.cloud.dc.AccountVlanMapVO in project cloudstack by apache.

the class IpAddressManagerImpl method listAvailablePublicIps.

@Override
public List<IPAddressVO> listAvailablePublicIps(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 boolean allocate, final String requestedIp, final String requestedGateway, final boolean isSystem, final Long vpcId, final Boolean displayIp, final boolean forSystemVms, final boolean lockOneRow) throws InsufficientAddressCapacityException {
    return Transaction.execute(new TransactionCallbackWithException<List<IPAddressVO>, InsufficientAddressCapacityException>() {

        @Override
        public List<IPAddressVO> doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
            StringBuilder errorMessage = new StringBuilder("Unable to get ip address 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 (vlanUse == VlanType.VirtualNetwork) {
                if (!dedicatedVlanDbIds.isEmpty()) {
                    fetchFromDedicatedRange = true;
                    sc.setParameters("vlanId", dedicatedVlanDbIds.toArray());
                    errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray()));
                } else if (!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);
            }
            if (requestedGateway != null) {
                sc.setJoinParameters("vlan", "vlanGateway", requestedGateway);
                errorMessage.append(", requested gateway=" + requestedGateway);
            }
            sc.setJoinParameters("vlan", "type", vlanUse);
            String routerIpAddress = null;
            if (network != null) {
                NetworkDetailVO routerIpDetail = _networkDetailsDao.findDetail(network.getId(), ApiConstants.ROUTER_IP);
                routerIpAddress = routerIpDetail != null ? routerIpDetail.getValue() : null;
            }
            if (requestedIp != null) {
                sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp);
                errorMessage.append(": requested ip " + requestedIp + " is not available");
            } else if (routerIpAddress != null) {
                sc.addAnd("address", Op.NEQ, routerIpAddress);
            }
            boolean ascOrder = !forSystemVms;
            Filter filter = new Filter(IPAddressVO.class, "forSystemVms", ascOrder, 0l, 1l);
            if (SystemVmPublicIpReservationModeStrictness.value()) {
                sc.setParameters("forSystemVms", forSystemVms);
            }
            filter.addOrderBy(IPAddressVO.class, "vlanId", true);
            List<IPAddressVO> addrs;
            if (lockOneRow) {
                addrs = _ipAddressDao.lockRows(sc, filter, true);
            } else {
                addrs = new ArrayList<>(_ipAddressDao.search(sc, null));
            }
            // If all the dedicated IPs of the owner are in use fetch an IP from the system pool
            if ((!lockOneRow || (lockOneRow && addrs.size() == 0)) && fetchFromDedicatedRange && vlanUse == VlanType.VirtualNetwork) {
                // Verify if account is allowed to acquire IPs from the system
                boolean useSystemIps = UseSystemPublicIps.valueIn(owner.getId());
                if (useSystemIps && !nonDedicatedVlanDbIds.isEmpty()) {
                    fetchFromDedicatedRange = false;
                    sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
                    errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
                    if (lockOneRow) {
                        addrs = _ipAddressDao.lockRows(sc, filter, true);
                    } else {
                        addrs.addAll(_ipAddressDao.search(sc, null));
                    }
                }
            }
            if (lockOneRow && 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;
            }
            if (lockOneRow) {
                assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size();
            }
            if (assign) {
                assignAndAllocateIpAddressEntry(owner, vlanUse, guestNetworkId, sourceNat, allocate, isSystem, vpcId, displayIp, fetchFromDedicatedRange, addrs);
            }
            return addrs;
        }
    });
}
Also used : Pod(com.cloud.dc.Pod) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) SearchCriteria(com.cloud.utils.db.SearchCriteria) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) DataCenter(com.cloud.dc.DataCenter) Filter(com.cloud.utils.db.Filter) ArrayList(java.util.ArrayList) List(java.util.List) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) NetworkDetailVO(com.cloud.network.dao.NetworkDetailVO)

Aggregations

AccountVlanMapVO (com.cloud.dc.AccountVlanMapVO)23 ArrayList (java.util.ArrayList)16 VlanVO (com.cloud.dc.VlanVO)15 IPAddressVO (com.cloud.network.dao.IPAddressVO)13 DomainVlanMapVO (com.cloud.dc.DomainVlanMapVO)12 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)12 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)8 Account (com.cloud.user.Account)8 DB (com.cloud.utils.db.DB)8 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)7 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)6 TransactionStatus (com.cloud.utils.db.TransactionStatus)6 List (java.util.List)6 DataCenterVO (com.cloud.dc.DataCenterVO)4 PodVlanMapVO (com.cloud.dc.PodVlanMapVO)4 Project (com.cloud.projects.Project)4 Filter (com.cloud.utils.db.Filter)4 Ip (com.cloud.utils.net.Ip)4 ActionEvent (com.cloud.event.ActionEvent)3 SearchCriteria (com.cloud.utils.db.SearchCriteria)3