Search in sources :

Example 1 with InsufficientAddressCapacityException

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

the class AddIpToVmNicTest method testCreateFailure.

@Test
public void testCreateFailure() throws ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException {
    final NetworkService networkService = Mockito.mock(NetworkService.class);
    final AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class);
    Mockito.when(networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString())).thenReturn(null);
    ipTonicCmd._networkService = networkService;
    try {
        ipTonicCmd.execute();
    } catch (final InsufficientAddressCapacityException e) {
        throw new InvalidParameterValueException("Allocating guest ip for nic failed");
    }
}
Also used : AddIpToVmNicCmd(com.cloud.api.command.user.vm.AddIpToVmNicCmd) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) NetworkService(com.cloud.network.NetworkService) Test(org.junit.Test)

Example 2 with InsufficientAddressCapacityException

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

the class VirtualMachineManagerImpl method orchestrateStorageMigration.

private void orchestrateStorageMigration(final String vmUuid, final StoragePool destPool) {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    if (destPool == null) {
        throw new CloudRuntimeException("Unable to migrate vm: missing destination storage pool");
    }
    try {
        stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null);
    } catch (final NoTransitionException e) {
        s_logger.debug("Unable to migrate vm: " + e.toString());
        throw new CloudRuntimeException("Unable to migrate vm: " + e.toString());
    }
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    boolean migrationResult = false;
    try {
        migrationResult = volumeMgr.storageMigration(profile, destPool);
        if (migrationResult) {
            if (destPool.getPodId() != null && !destPool.getPodId().equals(vm.getPodIdToDeployIn())) {
                final DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null);
                final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null);
                _networkMgr.reallocate(vmProfile, plan);
            }
            // when start the vm next time, don;'t look at last_host_id, only choose the host based on volume/storage pool
            vm.setLastHostId(null);
            vm.setPodIdToDeployIn(destPool.getPodId());
        } else {
            s_logger.debug("Storage migration failed");
        }
    } catch (final ConcurrentOperationException e) {
        s_logger.debug("Failed to migration: " + e.toString());
        throw new CloudRuntimeException("Failed to migration: " + e.toString());
    } catch (final InsufficientVirtualNetworkCapacityException e) {
        s_logger.debug("Failed to migration: " + e.toString());
        throw new CloudRuntimeException("Failed to migration: " + e.toString());
    } catch (final InsufficientAddressCapacityException e) {
        s_logger.debug("Failed to migration: " + e.toString());
        throw new CloudRuntimeException("Failed to migration: " + e.toString());
    } catch (final InsufficientCapacityException e) {
        s_logger.debug("Failed to migration: " + e.toString());
        throw new CloudRuntimeException("Failed to migration: " + e.toString());
    } catch (final StorageUnavailableException e) {
        s_logger.debug("Failed to migration: " + e.toString());
        throw new CloudRuntimeException("Failed to migration: " + e.toString());
    } finally {
        try {
            stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
        } catch (final NoTransitionException e) {
            s_logger.debug("Failed to change vm state: " + e.toString());
            throw new CloudRuntimeException("Failed to change vm state: " + e.toString());
        }
    }
}
Also used : DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientVirtualNetworkCapacityException(com.cloud.legacymodel.exceptions.InsufficientVirtualNetworkCapacityException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException)

Example 3 with InsufficientAddressCapacityException

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

the class IpAddressManagerImpl method allocateIp.

@DB
@Override
public IpAddress allocateIp(final Account ipOwner, final boolean isSystem, final Account caller, final long callerUserId, final DataCenter zone, final Boolean displayIp) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException {
    final VlanType vlanType = VlanType.VirtualNetwork;
    final boolean assign = false;
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        // zone is of type DataCenter. See DataCenterVO.java.
        final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, " + "Zone is currently disabled");
        ex.addProxyObject(zone.getUuid(), "zoneId");
        throw ex;
    }
    PublicIp ip = null;
    Account accountToLock = null;
    try {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
        }
        accountToLock = _accountDao.acquireInLockTable(ipOwner.getId());
        if (accountToLock == null) {
            s_logger.warn("Unable to lock account: " + ipOwner.getId());
            throw new ConcurrentOperationException("Unable to acquire account lock");
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Associate IP address lock acquired");
        }
        ip = Transaction.execute(new TransactionCallbackWithException<PublicIp, InsufficientAddressCapacityException>() {

            @Override
            public PublicIp doInTransaction(final TransactionStatus status) throws InsufficientAddressCapacityException {
                final PublicIp ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, false, assign, null, isSystem, null, displayIp);
                if (ip == null) {
                    final InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zone.getId());
                    ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid());
                    throw ex;
                }
                CallContext.current().setEventDetails("Ip Id: " + ip.getId());
                final Ip ipAddress = ip.getAddress();
                s_logger.debug("Got " + ipAddress + " to assign for account " + ipOwner.getId() + " in zone " + zone.getId());
                return ip;
            }
        });
    } finally {
        if (accountToLock != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Releasing lock account " + ipOwner);
            }
            _accountDao.releaseFromLockTable(ipOwner.getId());
            s_logger.debug("Associate IP address lock released");
        }
    }
    return ip;
}
Also used : Account(com.cloud.legacymodel.user.Account) PublicIp(com.cloud.network.addr.PublicIp) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) Ip(com.cloud.legacymodel.network.Ip) PublicIp(com.cloud.network.addr.PublicIp) TransactionStatus(com.cloud.utils.db.TransactionStatus) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) VlanType(com.cloud.legacymodel.dc.Vlan.VlanType) DB(com.cloud.utils.db.DB)

Example 4 with InsufficientAddressCapacityException

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

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

the class Ipv6AddressManagerImpl method assignDirectIp6Address.

@Override
public UserIpv6Address assignDirectIp6Address(final long dcId, final Account owner, final Long networkId, final String requestedIp6) throws InsufficientAddressCapacityException {
    final Network network = _networkDao.findById(networkId);
    if (network == null) {
        return null;
    }
    final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(networkId);
    if (vlans == null) {
        s_logger.debug("Cannot find related vlan attached to network " + networkId);
        return null;
    }
    String ip = null;
    Vlan ipVlan = null;
    if (requestedIp6 == null) {
        if (!_networkModel.isIP6AddressAvailableInNetwork(networkId)) {
            throw new InsufficientAddressCapacityException("There is no more address available in the network " + network.getName(), DataCenter.class, network.getDataCenterId());
        }
        for (final Vlan vlan : vlans) {
            if (!_networkModel.isIP6AddressAvailableInVlan(vlan.getId())) {
                continue;
            }
            ip = NetUtils.getIp6FromRange(vlan.getIp6Range());
            int count = 0;
            while (_ipv6Dao.findByNetworkIdAndIp(networkId, ip) != null) {
                ip = NetUtils.getNextIp6InRange(ip, vlan.getIp6Range());
                count++;
                // It's an arbitrate number to prevent the infinite loop
                if (count > _ipv6RetryMax) {
                    ip = null;
                    break;
                }
            }
            if (ip != null) {
                ipVlan = vlan;
            }
        }
        if (ip == null) {
            throw new InsufficientAddressCapacityException("Cannot find a usable IP in the network " + network.getName() + " after " + _ipv6RetryMax + "(network.ipv6.search.retry.max) times retry!", DataCenter.class, network.getDataCenterId());
        }
    } else {
        for (final Vlan vlan : vlans) {
            if (NetUtils.isIp6InRange(requestedIp6, vlan.getIp6Range())) {
                ipVlan = vlan;
                break;
            }
        }
        if (ipVlan == null) {
            throw new CloudRuntimeException("Requested IPv6 is not in the predefined range!");
        }
        ip = requestedIp6;
        if (_ipv6Dao.findByNetworkIdAndIp(networkId, ip) != null) {
            throw new CloudRuntimeException("The requested IP is already taken!");
        }
    }
    final Zone zone = zoneRepository.findById(dcId).orElse(null);
    final Long mac = zone.getMacAddress();
    final Long nextMac = mac + 1;
    zone.setMacAddress(nextMac);
    zoneRepository.save(zone);
    final String macAddress = NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(mac));
    final UserIpv6AddressVO ipVO = new UserIpv6AddressVO(ip, dcId, macAddress, ipVlan.getId());
    ipVO.setPhysicalNetworkId(network.getPhysicalNetworkId());
    ipVO.setSourceNetworkId(networkId);
    ipVO.setState(UserIpv6Address.State.Allocated);
    ipVO.setDomainId(owner.getDomainId());
    ipVO.setAccountId(owner.getAccountId());
    _ipv6Dao.persist(ipVO);
    return ipVO;
}
Also used : CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Zone(com.cloud.db.model.Zone) Network(com.cloud.legacymodel.network.Network) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) Vlan(com.cloud.legacymodel.dc.Vlan) VlanVO(com.cloud.dc.VlanVO)

Aggregations

InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)19 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)8 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)7 Network (com.cloud.legacymodel.network.Network)6 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)5 Account (com.cloud.legacymodel.user.Account)5 IPAddressVO (com.cloud.network.dao.IPAddressVO)5 TransactionStatus (com.cloud.utils.db.TransactionStatus)5 Zone (com.cloud.db.model.Zone)4 DataCenter (com.cloud.legacymodel.dc.DataCenter)4 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)4 DB (com.cloud.utils.db.DB)4 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)4 ServerApiException (com.cloud.api.ServerApiException)3 Pod (com.cloud.legacymodel.dc.Pod)3 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)3 InsufficientVirtualNetworkCapacityException (com.cloud.legacymodel.exceptions.InsufficientVirtualNetworkCapacityException)3 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)3 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)3 PublicIp (com.cloud.network.addr.PublicIp)3