use of com.cloud.network.addr.PublicIp in project cloudstack by apache.
the class IpAddressManagerImpl method allocatePublicIpForGuestNic.
@Override
public String allocatePublicIpForGuestNic(Network network, Long podId, Account owner, String requestedIp) throws InsufficientAddressCapacityException {
PublicIp ip = assignPublicIpAddress(network.getDataCenterId(), podId, owner, VlanType.DirectAttached, network.getId(), requestedIp, false);
if (ip == null) {
s_logger.debug("There is no free public ip address");
return null;
}
Ip ipAddr = ip.getAddress();
return ipAddr.addr();
}
use of com.cloud.network.addr.PublicIp in project cloudstack by apache.
the class ExternalLoadBalancerDeviceManagerImpl method allocateLoadBalancerForNetwork.
@DB
protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException {
boolean retry = true;
boolean tryLbProvisioning = false;
ExternalLoadBalancerDeviceVO lbDevice = null;
long physicalNetworkId = guestConfig.getPhysicalNetworkId();
NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId());
String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb);
while (retry) {
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
try {
if (deviceMapLock.lock(120)) {
try {
// does network offering supports a dedicated load balancer?
final boolean dedicatedLB = offering.getDedicatedLB();
try {
lbDevice = Transaction.execute(new TransactionCallbackWithException<ExternalLoadBalancerDeviceVO, InsufficientCapacityException>() {
@Override
public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException {
// FIXME: should the device allocation be done during network implement phase or do a
// lazy allocation when first rule for the network is configured??
// find a load balancer device for this network as per the network offering
ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB);
long lbDeviceId = lbDevice.getId();
// persist the load balancer device id that will be used for this network. Once a network
// is implemented on a LB device then later on all rules will be programmed on to same device
NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId);
_networkExternalLBDao.persist(networkLB);
// mark device to be either dedicated or shared use
lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared);
_externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice);
return lbDevice;
}
});
// allocated load balancer for the network, so skip retry
tryLbProvisioning = false;
retry = false;
} catch (InsufficientCapacityException exception) {
// if already attempted to provision load balancer then throw out of capacity exception,
if (tryLbProvisioning) {
retry = false;
// TODO: throwing warning instead of error for now as its possible another provider can service this network
s_logger.warn("There are no load balancer device with the capacity for implementing this network");
throw exception;
} else {
// if possible provision a LB appliance in to the physical network
tryLbProvisioning = true;
}
}
} finally {
deviceMapLock.unlock();
}
}
} finally {
deviceMapLock.releaseRef();
}
// there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance
if (tryLbProvisioning) {
// check if LB appliance can be dynamically provisioned
List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider);
if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) {
for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) {
if (lbProviderDevice.getState() == LBDeviceState.Enabled) {
// acquire a private IP from the data center which will be used as management IP of provisioned LB appliance,
DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid());
if (dcPrivateIp == null) {
throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId());
}
Pod pod = _podDao.findById(dcPrivateIp.getPodId());
String lbIP = dcPrivateIp.getIpAddress();
String netmask = NetUtils.getCidrNetmask(pod.getCidrSize());
String gateway = pod.getGateway();
// send CreateLoadBalancerApplianceCommand to the host capable of provisioning
CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway);
CreateLoadBalancerApplianceAnswer createLbAnswer = null;
try {
createLbAnswer = (CreateLoadBalancerApplianceAnswer) _agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd);
if (createLbAnswer == null || !createLbAnswer.getResult()) {
s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId());
continue;
}
} catch (Exception agentException) {
s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage());
continue;
}
String username = createLbAnswer.getUsername();
String password = createLbAnswer.getPassword();
String publicIf = createLbAnswer.getPublicInterface();
String privateIf = createLbAnswer.getPrivateInterface();
// we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer
String dedicatedLb = offering.getDedicatedLB() ? "true" : "false";
String capacity = Long.toString(lbProviderDevice.getCapacity());
// acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network)
PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false);
String publicIPNetmask = publicIp.getVlanNetmask();
String publicIPgateway = publicIp.getVlanGateway();
String publicIP = publicIp.getAddress().toString();
String publicIPVlanTag = "";
try {
publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag());
} catch (URISyntaxException e) {
s_logger.error("Failed to parse public ip vlan tag" + e.getMessage());
}
String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway;
ExternalLoadBalancerDeviceVO lbAppliance = null;
try {
lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null);
} catch (Exception e) {
s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed.");
}
if (lbAppliance != null) {
// mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned
ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId());
managedLb.setIsManagedDevice(true);
managedLb.setParentHostId(lbProviderDevice.getHostId());
_externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb);
} else {
// failed to add the provisioned load balancer into cloudstack so destroy the appliance
DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP);
DestroyLoadBalancerApplianceAnswer answer = null;
try {
answer = (DestroyLoadBalancerApplianceAnswer) _agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd);
if (answer == null || !answer.getResult()) {
s_logger.warn("Failed to destroy load balancer appliance created");
} else {
// release the public & private IP back to dc pool, as the load balancer appliance is now destroyed
_dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null);
_ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount());
}
} catch (Exception e) {
s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage());
}
}
}
}
}
}
}
return lbDevice;
}
use of com.cloud.network.addr.PublicIp in project cloudstack by apache.
the class IpAddressManagerImpl method assignSourceNatIpAddressToGuestNetwork.
@Override
public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException {
assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network " + "can't participate in source nat. What do you have to say for yourself?";
long dcId = guestNetwork.getDataCenterId();
IPAddressVO sourceNatIp = getExistingSourceNatInNetwork(owner.getId(), guestNetwork.getId());
PublicIp ipToReturn = null;
if (sourceNatIp != null) {
ipToReturn = PublicIp.createFromAddrAndVlan(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()));
} else {
ipToReturn = assignDedicateIpAddress(owner, guestNetwork.getId(), null, dcId, true);
}
return ipToReturn;
}
use of com.cloud.network.addr.PublicIp in project cloudstack by apache.
the class LoadBalanceRuleHandler method handleCreateLoadBalancerRuleWithLock.
private LoadBalancer handleCreateLoadBalancerRuleWithLock(final CreateLoadBalancerRuleCmd lb, final Account account, final long networkId) throws InsufficientAddressCapacityException, NetworkRuleConflictException {
Long ipId = null;
boolean newIp = false;
List<LoadBalancerVO> existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), lb.getSourcePortStart());
if (existingLbs == null) {
existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), null);
if (existingLbs == null) {
if (lb.getSourceIpAddressId() != null) {
throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(lb);
} else {
s_logger.debug("Could not find any existing frontend ips for this account for this LB rule, acquiring a new frontent IP for ELB");
final PublicIp ip = allocDirectIp(account, networkId);
ipId = ip.getId();
newIp = true;
}
} else {
ipId = existingLbs.get(0).getSourceIpAddressId();
s_logger.debug("ELB: Found existing frontend ip for this account for this LB rule " + ipId);
}
} else {
s_logger.warn("ELB: Found existing load balancers matching requested new LB");
throw new NetworkRuleConflictException("ELB: Found existing load balancers matching requested new LB");
}
final IPAddressVO ipAddr = _ipAddressDao.findById(ipId);
LoadBalancer result = null;
try {
lb.setSourceIpAddressId(ipId);
result = _lbMgr.createPublicLoadBalancer(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourcePortStart(), lb.getDefaultPortStart(), ipId.longValue(), lb.getProtocol(), lb.getAlgorithm(), false, CallContext.current(), lb.getLbProtocol(), true);
} catch (final NetworkRuleConflictException e) {
s_logger.warn("Failed to create LB rule, not continuing with ELB deployment");
if (newIp) {
releaseIp(ipId, CallContext.current().getCallingUserId(), account);
}
throw e;
}
DomainRouterVO elbVm = null;
if (existingLbs == null) {
elbVm = findElbVmWithCapacity(ipAddr);
if (elbVm == null) {
elbVm = deployLoadBalancerVM(networkId, ipAddr);
if (elbVm == null) {
final Network network = _networkModel.getNetwork(networkId);
s_logger.warn("Failed to deploy a new ELB vm for ip " + ipAddr + " in network " + network + "lb name=" + lb.getName());
if (newIp) {
releaseIp(ipId, CallContext.current().getCallingUserId(), account);
}
}
}
} else {
final ElasticLbVmMapVO elbVmMap = _elbVmMapDao.findOneByIp(ipId);
if (elbVmMap != null) {
elbVm = _routerDao.findById(elbVmMap.getElbVmId());
}
}
if (elbVm == null) {
s_logger.warn("No ELB VM can be found or deployed");
s_logger.warn("Deleting LB since we failed to deploy ELB VM");
_lbDao.remove(result.getId());
return null;
}
final ElasticLbVmMapVO mapping = new ElasticLbVmMapVO(ipId, elbVm.getId(), result.getId());
_elbVmMapDao.persist(mapping);
return result;
}
use of com.cloud.network.addr.PublicIp in project cloudstack by apache.
the class NiciraNvpElementTest method implementIsolatedNetworkTest.
@Test
public void implementIsolatedNetworkTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, URISyntaxException {
final Network network = mock(Network.class);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa"));
when(network.getId()).thenReturn(NETWORK_ID);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
when(network.getGuestType()).thenReturn(GuestType.Isolated);
when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true);
when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true);
final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device }));
when(device.getId()).thenReturn(1L);
when(device.getHostId()).thenReturn(NICIRA_NVP_HOST_ID);
HostVO niciraNvpHost = mock(HostVO.class);
when(niciraNvpHost.getId()).thenReturn(NICIRA_NVP_HOST_ID);
when(hostDao.findById(NICIRA_NVP_HOST_ID)).thenReturn(niciraNvpHost);
final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated);
final DeployDestination dest = mock(DeployDestination.class);
final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain");
final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname");
final ReservationContext context = mock(ReservationContext.class);
when(context.getDomain()).thenReturn(dom);
when(context.getAccount()).thenReturn(acc);
//ISOLATED NETWORK
when(networkModel.isProviderSupportServiceInNetwork(NETWORK_ID, Service.SourceNat, Provider.NiciraNvp)).thenReturn(true);
PublicIp sourceNatIp = mock(PublicIp.class);
Ip ip = mock(Ip.class);
when(ip.addr()).thenReturn("10.0.0.0");
when(sourceNatIp.getAddress()).thenReturn(ip);
when(sourceNatIp.getVlanNetmask()).thenReturn("255.255.255.0");
when(sourceNatIp.getVlanTag()).thenReturn("111");
when(ipAddressManager.assignSourceNatIpAddressToGuestNetwork(acc, network)).thenReturn(sourceNatIp);
when(network.getGateway()).thenReturn(NETWORK_GATEWAY);
when(network.getCidr()).thenReturn(NETWORK_CIDR);
final CreateLogicalRouterAnswer answer = mock(CreateLogicalRouterAnswer.class);
when(answer.getResult()).thenReturn(true);
when(agentManager.easySend(eq(NICIRA_NVP_HOST_ID), (Command) any())).thenReturn(answer);
assertTrue(element.implement(network, offering, dest, context));
}
Aggregations