use of com.cloud.exception.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);
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()));
}
use of com.cloud.exception.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;
}
use of com.cloud.exception.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.findOne(dcId);
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;
}
use of com.cloud.exception.InsufficientAddressCapacityException in project cloudstack by apache.
the class VMwareGuru method implement.
@Override
public VirtualMachineTO implement(VirtualMachineProfile vm) {
VirtualMachineTO to = toVirtualMachineTO(vm);
to.setBootloader(BootloaderType.HVM);
Map<String, String> details = to.getDetails();
if (details == null)
details = new HashMap<String, String>();
Type vmType = vm.getType();
boolean userVm = !(vmType.equals(VirtualMachine.Type.DomainRouter) || vmType.equals(VirtualMachine.Type.ConsoleProxy) || vmType.equals(VirtualMachine.Type.SecondaryStorageVm));
String nicDeviceType = details.get(VmDetailConstants.NIC_ADAPTER);
if (!userVm) {
if (nicDeviceType == null) {
details.put(VmDetailConstants.NIC_ADAPTER, _vmwareMgr.getSystemVMDefaultNicAdapterType());
} else {
try {
VirtualEthernetCardType.valueOf(nicDeviceType);
} catch (Exception e) {
s_logger.warn("Invalid NIC device type " + nicDeviceType + " is specified in VM details, switch to default E1000");
details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString());
}
}
} else {
// for user-VM, use E1000 as default
if (nicDeviceType == null) {
details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString());
} else {
try {
VirtualEthernetCardType.valueOf(nicDeviceType);
} catch (Exception e) {
s_logger.warn("Invalid NIC device type " + nicDeviceType + " is specified in VM details, switch to default E1000");
details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString());
}
}
}
String diskDeviceType = details.get(VmDetailConstants.ROOT_DISK_CONTROLLER);
if (userVm) {
if (diskDeviceType == null) {
details.put(VmDetailConstants.ROOT_DISK_CONTROLLER, _vmwareMgr.getRootDiskController());
}
}
String diskController = details.get(VmDetailConstants.DATA_DISK_CONTROLLER);
if (userVm) {
if (diskController == null) {
details.put(VmDetailConstants.DATA_DISK_CONTROLLER, DiskControllerType.lsilogic.toString());
}
}
List<NicProfile> nicProfiles = vm.getNics();
for (NicProfile nicProfile : nicProfiles) {
if (nicProfile.getTrafficType() == TrafficType.Guest) {
if (_networkMgr.isProviderSupportServiceInNetwork(nicProfile.getNetworkId(), Service.Firewall, Provider.CiscoVnmc)) {
details.put("ConfigureVServiceInNexus", Boolean.TRUE.toString());
}
break;
}
}
long clusterId = getClusterId(vm.getId());
details.put(VmwareReserveCpu.key(), VmwareReserveCpu.valueIn(clusterId).toString());
details.put(VmwareReserveMemory.key(), VmwareReserveMemory.valueIn(clusterId).toString());
to.setDetails(details);
if (vmType.equals(VirtualMachine.Type.DomainRouter)) {
NicProfile publicNicProfile = null;
for (NicProfile nicProfile : nicProfiles) {
if (nicProfile.getTrafficType() == TrafficType.Public) {
publicNicProfile = nicProfile;
break;
}
}
if (publicNicProfile != null) {
NicTO[] nics = to.getNics();
// reserve extra NICs
NicTO[] expandedNics = new NicTO[nics.length + _vmwareMgr.getRouterExtraPublicNics()];
int i = 0;
int deviceId = -1;
for (i = 0; i < nics.length; i++) {
expandedNics[i] = nics[i];
if (nics[i].getDeviceId() > deviceId)
deviceId = nics[i].getDeviceId();
}
deviceId++;
long networkId = publicNicProfile.getNetworkId();
NetworkVO network = _networkDao.findById(networkId);
for (; i < nics.length + _vmwareMgr.getRouterExtraPublicNics(); i++) {
NicTO nicTo = new NicTO();
nicTo.setDeviceId(deviceId++);
nicTo.setBroadcastType(publicNicProfile.getBroadcastType());
nicTo.setType(publicNicProfile.getTrafficType());
nicTo.setIp("0.0.0.0");
nicTo.setNetmask("255.255.255.255");
try {
String mac = _networkMgr.getNextAvailableMacAddressInNetwork(networkId);
nicTo.setMac(mac);
} catch (InsufficientAddressCapacityException e) {
throw new CloudRuntimeException("unable to allocate mac address on network: " + networkId);
}
nicTo.setDns1(publicNicProfile.getIPv4Dns1());
nicTo.setDns2(publicNicProfile.getIPv4Dns2());
if (publicNicProfile.getIPv4Gateway() != null) {
nicTo.setGateway(publicNicProfile.getIPv4Gateway());
} else {
nicTo.setGateway(network.getGateway());
}
nicTo.setDefaultNic(false);
nicTo.setBroadcastUri(publicNicProfile.getBroadCastUri());
nicTo.setIsolationuri(publicNicProfile.getIsolationUri());
Integer networkRate = _networkMgr.getNetworkRate(network.getId(), null);
nicTo.setNetworkRateMbps(networkRate);
expandedNics[i] = nicTo;
}
to.setNics(expandedNics);
}
StringBuffer sbMacSequence = new StringBuffer();
for (NicTO nicTo : sortNicsByDeviceId(to.getNics())) {
sbMacSequence.append(nicTo.getMac()).append("|");
}
if (!sbMacSequence.toString().isEmpty()) {
sbMacSequence.deleteCharAt(sbMacSequence.length() - 1);
String bootArgs = to.getBootArgs();
to.setBootArgs(bootArgs + " nic_macs=" + sbMacSequence.toString());
}
}
// Should only be done on user machines
if (userVm) {
configureNestedVirtualization(details, to);
}
// Determine the VM's OS description
GuestOSVO guestOS = _guestOsDao.findByIdIncludingRemoved(vm.getVirtualMachine().getGuestOSId());
to.setOs(guestOS.getDisplayName());
to.setHostName(vm.getHostName());
HostVO host = _hostDao.findById(vm.getVirtualMachine().getHostId());
GuestOSHypervisorVO guestOsMapping = null;
if (host != null) {
guestOsMapping = _guestOsHypervisorDao.findByOsIdAndHypervisor(guestOS.getId(), getHypervisorType().toString(), host.getHypervisorVersion());
}
if (guestOsMapping == null || host == null) {
to.setPlatformEmulator(null);
} else {
to.setPlatformEmulator(guestOsMapping.getGuestOsName());
}
return to;
}
use of com.cloud.exception.InsufficientAddressCapacityException in project cloudstack by apache.
the class Ipv6AddressManagerImpl method assignDirectIp6Address.
@Override
public UserIpv6Address assignDirectIp6Address(long dcId, Account owner, Long networkId, String requestedIp6) throws InsufficientAddressCapacityException {
Network network = _networkDao.findById(networkId);
if (network == null) {
return null;
}
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 (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 (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!");
}
}
DataCenterVO dc = _dcDao.findById(dcId);
Long mac = dc.getMacAddress();
Long nextMac = mac + 1;
dc.setMacAddress(nextMac);
_dcDao.update(dc.getId(), dc);
String macAddress = NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(mac, NetworkModel.MACIdentifier.value()));
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;
}
Aggregations