use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.
the class ExternalGuestNetworkGuru method implement.
@Override
public Network implement(Network config, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException {
assert (config.getState() == State.Implementing) : "Why are we implementing " + config;
if (_networkModel.areServicesSupportedInNetwork(config.getId(), Network.Service.Connectivity)) {
return null;
}
if (!_networkModel.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getId())) {
return super.implement(config, offering, dest, context);
}
DataCenter zone = dest.getDataCenter();
NetworkVO implemented = new NetworkVO(config.getTrafficType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), State.Allocated, config.getDataCenterId(), config.getPhysicalNetworkId(), offering.getRedundantRouter());
// Get a vlan tag
int vlanTag;
if (config.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(zone.getId(), config.getPhysicalNetworkId(), config.getAccountId(), context.getReservationId(), UseSystemGuestVlans.valueIn(config.getAccountId()));
try {
// when supporting more types of networks this need to become
// int vlantag = Integer.parseInt(BroadcastDomainType.getValue(vnet));
vlanTag = Integer.parseInt(vnet);
} catch (NumberFormatException e) {
throw new CloudRuntimeException("Obtained an invalid guest vlan tag. Exception: " + e.getMessage());
}
implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag));
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(), 0);
} else {
vlanTag = Integer.parseInt(BroadcastDomainType.getValue(config.getBroadcastUri()));
implemented.setBroadcastUri(config.getBroadcastUri());
}
// Determine the new gateway and CIDR
String[] oldCidr = config.getCidr().split("/");
String oldCidrAddress = oldCidr[0];
int cidrSize = Integer.parseInt(oldCidr[1]);
long newCidrAddress = (NetUtils.ip2Long(oldCidrAddress));
// if the implementing network is for vpc, no need to generate newcidr, use the cidr that came from super cidr
if (config.getVpcId() != null) {
implemented.setGateway(config.getGateway());
implemented.setCidr(config.getCidr());
implemented.setState(State.Implemented);
} else {
// Determine the offset from the lowest vlan tag
int offset = getVlanOffset(config.getPhysicalNetworkId(), vlanTag);
cidrSize = getGloballyConfiguredCidrSize();
// If the offset has more bits than there is room for, return null
long bitsInOffset = 32 - Integer.numberOfLeadingZeros(offset);
if (bitsInOffset > (cidrSize - 8)) {
throw new CloudRuntimeException("The offset " + offset + " needs " + bitsInOffset + " bits, but only have " + (cidrSize - 8) + " bits to work with.");
}
newCidrAddress = (NetUtils.ip2Long(oldCidrAddress) & 0xff000000) | (offset << (32 - cidrSize));
implemented.setGateway(NetUtils.long2Ip(newCidrAddress + 1));
implemented.setCidr(NetUtils.long2Ip(newCidrAddress) + "/" + cidrSize);
implemented.setState(State.Implemented);
}
// Mask the Ipv4 address of all nics that use this network with the new guest VLAN offset
List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(config.getId());
for (NicVO nic : nicsInNetwork) {
if (nic.getIPv4Address() != null) {
long ipMask = getIpMask(nic.getIPv4Address(), cidrSize);
nic.setIPv4Address(NetUtils.long2Ip(newCidrAddress | ipMask));
_nicDao.persist(nic);
}
}
// Mask the destination address of all port forwarding rules in this network with the new guest VLAN offset
List<PortForwardingRuleVO> pfRulesInNetwork = _pfRulesDao.listByNetwork(config.getId());
for (PortForwardingRuleVO pfRule : pfRulesInNetwork) {
if (pfRule.getDestinationIpAddress() != null) {
long ipMask = getIpMask(pfRule.getDestinationIpAddress().addr(), cidrSize);
String maskedDestinationIpAddress = NetUtils.long2Ip(newCidrAddress | ipMask);
pfRule.setDestinationIpAddress(new Ip(maskedDestinationIpAddress));
_pfRulesDao.update(pfRule.getId(), pfRule);
}
}
// Mask the destination address of all static nat rules in this network with the new guest VLAN offset
// Here the private ip of the nic get updated. When secondary ip are present the gc will not triggered
List<IPAddressVO> ipAddrsOfNw = _ipAddressDao.listStaticNatPublicIps(config.getId());
for (IPAddressVO ip : ipAddrsOfNw) {
if (ip.getVmIp() != null) {
long ipMask = getIpMask(ip.getVmIp(), cidrSize);
String maskedVmIp = NetUtils.long2Ip(newCidrAddress | ipMask);
ip.setVmIp(maskedVmIp);
_ipAddressDao.update(ip.getId(), ip);
}
}
//Egress rules cidr is subset of guest nework cidr, we need to change
List<FirewallRuleVO> fwEgressRules = _fwRulesDao.listByNetworkPurposeTrafficType(config.getId(), FirewallRule.Purpose.Firewall, FirewallRule.TrafficType.Egress);
for (FirewallRuleVO rule : fwEgressRules) {
//get the cidr list for this rule
List<FirewallRulesCidrsVO> fwRuleCidrsVo = _fwRulesCidrDao.listByFirewallRuleId(rule.getId());
for (FirewallRulesCidrsVO ruleCidrvo : fwRuleCidrsVo) {
String cidr = ruleCidrvo.getCidr();
String cidrAddr = cidr.split("/")[0];
String size = cidr.split("/")[1];
long ipMask = getIpMask(cidrAddr, cidrSize);
String newIp = NetUtils.long2Ip(newCidrAddress | ipMask);
String updatedCidr = newIp + "/" + size;
ruleCidrvo.setSourceCidrList(updatedCidr);
_fwRulesCidrDao.update(ruleCidrvo.getId(), ruleCidrvo);
}
}
return implemented;
}
use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method createPublicLoadBalancerRule.
@Override
@ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer")
public LoadBalancer createPublicLoadBalancerRule(String xId, String name, String description, int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, Long ipAddrId, String protocol, String algorithm, long networkId, long lbOwnerId, boolean openFirewall, String lbProtocol, Boolean forDisplay) throws NetworkRuleConflictException, InsufficientAddressCapacityException {
Account lbOwner = _accountMgr.getAccount(lbOwnerId);
if (srcPortStart != srcPortEnd) {
throw new InvalidParameterValueException("Port ranges are not supported by the load balancer");
}
IPAddressVO ipVO = null;
if (ipAddrId != null) {
ipVO = _ipAddressDao.findById(ipAddrId);
}
Network network = _networkModel.getNetwork(networkId);
// FIXME: breaking the dependency on ELB manager. This breaks
// functionality of ELB using virtual router
// Bug CS-15411 opened to document this
// LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb,
// lbOwner, lb.getNetworkId());
LoadBalancer result = null;
if (result == null) {
IpAddress systemIp = null;
NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
if (off.getElasticLb() && ipVO == null && network.getVpcId() == null) {
systemIp = _ipAddrMgr.assignSystemIp(networkId, lbOwner, true, false);
if (systemIp != null) {
ipVO = _ipAddressDao.findById(systemIp.getId());
}
}
// Validate ip address
if (ipVO == null) {
throw new InvalidParameterValueException("Unable to create load balance rule; can't find/allocate source IP");
} else if (ipVO.isOneToOneNat()) {
throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipVO.getAddress());
}
boolean performedIpAssoc = false;
try {
if (ipVO.getAssociatedWithNetworkId() == null) {
boolean assignToVpcNtwk = network.getVpcId() != null && ipVO.getVpcId() != null && ipVO.getVpcId().longValue() == network.getVpcId();
if (assignToVpcNtwk) {
// set networkId just for verification purposes
_networkModel.checkIpForService(ipVO, Service.Lb, networkId);
s_logger.debug("The ip is not associated with the VPC network id=" + networkId + " so assigning");
ipVO = _ipAddrMgr.associateIPToGuestNetwork(ipAddrId, networkId, false);
performedIpAssoc = true;
}
} else {
_networkModel.checkIpForService(ipVO, Service.Lb, null);
}
if (ipVO.getAssociatedWithNetworkId() == null) {
throw new InvalidParameterValueException("Ip address " + ipVO + " is not assigned to the network " + network);
}
result = createPublicLoadBalancer(xId, name, description, srcPortStart, defPortStart, ipVO.getId(), protocol, algorithm, openFirewall, CallContext.current(), lbProtocol, forDisplay);
} catch (Exception ex) {
s_logger.warn("Failed to create load balancer due to ", ex);
if (ex instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) ex;
}
if (ex instanceof InvalidParameterValueException) {
throw (InvalidParameterValueException) ex;
}
} finally {
if (result == null && systemIp != null) {
s_logger.debug("Releasing system IP address " + systemIp + " as corresponding lb rule failed to create");
_ipAddrMgr.handleSystemIpRelease(systemIp);
}
// release ip address if ipassoc was perfored
if (performedIpAssoc) {
ipVO = _ipAddressDao.findById(ipVO.getId());
_vpcMgr.unassignIPFromVpcNetwork(ipVO.getId(), networkId);
}
}
}
if (result == null) {
throw new CloudRuntimeException("Failed to create load balancer rule: " + name);
}
return result;
}
use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.
the class GlobalLoadBalancingRulesServiceImplTest method runAssignToGlobalLoadBalancerRuleTest.
void runAssignToGlobalLoadBalancerRuleTest() throws Exception {
TransactionLegacy txn = TransactionLegacy.open("runAssignToGlobalLoadBalancerRuleTest");
GlobalLoadBalancingRulesServiceImpl gslbServiceImpl = new GlobalLoadBalancingRulesServiceImpl();
gslbServiceImpl._accountMgr = Mockito.mock(AccountManager.class);
gslbServiceImpl._gslbRuleDao = Mockito.mock(GlobalLoadBalancerRuleDao.class);
gslbServiceImpl._gslbLbMapDao = Mockito.mock(GlobalLoadBalancerLbRuleMapDao.class);
gslbServiceImpl._regionDao = Mockito.mock(RegionDao.class);
gslbServiceImpl._rulesMgr = Mockito.mock(RulesManager.class);
gslbServiceImpl._lbDao = Mockito.mock(LoadBalancerDao.class);
gslbServiceImpl._networkDao = Mockito.mock(NetworkDao.class);
gslbServiceImpl._globalConfigDao = Mockito.mock(ConfigurationDao.class);
gslbServiceImpl._ipAddressDao = Mockito.mock(IPAddressDao.class);
gslbServiceImpl._agentMgr = Mockito.mock(AgentManager.class);
AssignToGlobalLoadBalancerRuleCmd assignCmd = new AssignToGlobalLoadBalancerRuleCmdExtn();
Class<?> _class = assignCmd.getClass().getSuperclass();
Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
when(gslbServiceImpl._accountMgr.getAccount(anyLong())).thenReturn(account);
Field gslbRuleId = _class.getDeclaredField("id");
gslbRuleId.setAccessible(true);
gslbRuleId.set(assignCmd, new Long(1));
GlobalLoadBalancerRuleVO gslbRule = new GlobalLoadBalancerRuleVO("test-gslb-rule", "test-gslb-rule", "test-domain", "roundrobin", "sourceip", "tcp", 1, 1, 1, GlobalLoadBalancerRule.State.Active);
when(gslbServiceImpl._gslbRuleDao.findById(new Long(1))).thenReturn(gslbRule);
LoadBalancerVO lbRule = new LoadBalancerVO();
lbRule.setState(FirewallRule.State.Active);
Field networkIdField = LoadBalancerVO.class.getSuperclass().getDeclaredField("networkId");
networkIdField.setAccessible(true);
networkIdField.set(lbRule, new Long(1));
Field sourceIpAddressId = LoadBalancerVO.class.getSuperclass().getDeclaredField("sourceIpAddressId");
sourceIpAddressId.setAccessible(true);
sourceIpAddressId.set(lbRule, new Long(1));
when(gslbServiceImpl._lbDao.findById(new Long(1))).thenReturn(lbRule);
Field lbRules = _class.getDeclaredField("loadBalancerRulesIds");
lbRules.setAccessible(true);
List<Long> lbRuleIds = new ArrayList<Long>();
lbRuleIds.add(new Long(1));
lbRules.set(assignCmd, lbRuleIds);
NetworkVO networkVo = new NetworkVO();
Field dcID = NetworkVO.class.getDeclaredField("dataCenterId");
dcID.setAccessible(true);
dcID.set(networkVo, new Long(1));
when(gslbServiceImpl._networkDao.findById(new Long(1))).thenReturn(networkVo);
IPAddressVO ip = new IPAddressVO(new Ip("10.1.1.1"), 1, 1, 1, true);
when(gslbServiceImpl._ipAddressDao.findById(new Long(1))).thenReturn(ip);
try {
gslbServiceImpl.assignToGlobalLoadBalancerRule(assignCmd);
} catch (Exception e) {
s_logger.info("exception in testing runAssignToGlobalLoadBalancerRuleTest message: " + e.toString());
}
}
use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.
the class NetworkModelImpl method getIpToServices.
@Override
public Map<PublicIpAddress, Set<Service>> getIpToServices(List<? extends PublicIpAddress> publicIps, boolean postApplyRules, boolean includingFirewall) {
Map<PublicIpAddress, Set<Service>> ipToServices = new HashMap<PublicIpAddress, Set<Service>>();
if (publicIps != null && !publicIps.isEmpty()) {
Set<Long> networkSNAT = new HashSet<Long>();
for (PublicIpAddress ip : publicIps) {
Set<Service> services = ipToServices.get(ip);
if (services == null) {
services = new HashSet<Service>();
}
if (ip.isSourceNat()) {
if (!networkSNAT.contains(ip.getAssociatedWithNetworkId())) {
services.add(Service.SourceNat);
networkSNAT.add(ip.getAssociatedWithNetworkId());
} else {
CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network");
// see the IPAddressVO.java class.
IPAddressVO ipAddr = ApiDBUtils.findIpAddressById(ip.getAssociatedWithNetworkId());
String ipAddrUuid = ip.getAssociatedWithNetworkId().toString();
if (ipAddr != null) {
ipAddrUuid = ipAddr.getUuid();
}
ex.addProxyObject(ipAddrUuid, "networkId");
throw ex;
}
}
ipToServices.put(ip, services);
// provider
if (ip.getState() == State.Allocating) {
continue;
}
// check if any active rules are applied on the public IP
Set<Purpose> purposes = getPublicIpPurposeInRules(ip, false, includingFirewall);
// Firewall rules didn't cover static NAT
if (ip.isOneToOneNat() && ip.getAssociatedWithVmId() != null) {
if (purposes == null) {
purposes = new HashSet<Purpose>();
}
purposes.add(Purpose.StaticNat);
}
if (purposes == null || purposes.isEmpty()) {
// since no active rules are there check if any rules are applied on the public IP but are in
// revoking state
purposes = getPublicIpPurposeInRules(ip, true, includingFirewall);
if (ip.isOneToOneNat()) {
if (purposes == null) {
purposes = new HashSet<Purpose>();
}
purposes.add(Purpose.StaticNat);
}
if (purposes == null || purposes.isEmpty()) {
// IP is not being used for any purpose so skip IPAssoc to network service provider
continue;
} else {
if (postApplyRules) {
// association with the provider
if (ip.isSourceNat()) {
s_logger.debug("Not releasing ip " + ip.getAddress().addr() + " as it is in use for SourceNat");
} else {
ip.setState(State.Releasing);
}
} else {
if (ip.getState() == State.Releasing) {
// rules are not revoked yet, so don't let the network service provider revoke the IP
// association
// mark IP is allocated so that IP association will not be removed from the provider
ip.setState(State.Allocated);
}
}
}
}
if (purposes.contains(Purpose.StaticNat)) {
services.add(Service.StaticNat);
}
if (purposes.contains(Purpose.LoadBalancing)) {
services.add(Service.Lb);
}
if (purposes.contains(Purpose.PortForwarding)) {
services.add(Service.PortForwarding);
}
if (purposes.contains(Purpose.Vpn)) {
services.add(Service.Vpn);
}
if (purposes.contains(Purpose.Firewall)) {
services.add(Service.Firewall);
}
if (services.isEmpty()) {
continue;
}
ipToServices.put(ip, services);
}
}
return ipToServices;
}
use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.
the class NetworkModelImpl method getSourceNatIpAddressForGuestNetwork.
@Override
public PublicIpAddress getSourceNatIpAddressForGuestNetwork(Account owner, Network guestNetwork) {
List<? extends IpAddress> addrs = listPublicIpsAssignedToGuestNtwk(owner.getId(), guestNetwork.getId(), true);
IPAddressVO sourceNatIp = null;
if (addrs.isEmpty()) {
return null;
} else {
for (IpAddress addr : addrs) {
if (addr.isSourceNat()) {
sourceNatIp = _ipAddressDao.findById(addr.getId());
return PublicIp.createFromAddrAndVlan(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()));
}
}
}
return null;
}
Aggregations