use of com.cloud.network.PublicIpAddress in project cloudstack by apache.
the class NiciraNvpElementTest method applyIpTest.
@Test
public void applyIpTest() throws ResourceUnavailableException {
final Network network = mock(Network.class);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(network.getId()).thenReturn(NETWORK_ID);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
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 List<PublicIpAddress> ipAddresses = new ArrayList<PublicIpAddress>();
final PublicIpAddress pipReleased = mock(PublicIpAddress.class);
final PublicIpAddress pipAllocated = mock(PublicIpAddress.class);
final Ip ipReleased = new Ip("42.10.10.10");
final Ip ipAllocated = new Ip("10.10.10.10");
when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated);
when(pipAllocated.getAddress()).thenReturn(ipAllocated);
when(pipAllocated.getNetmask()).thenReturn("255.255.255.0");
when(pipReleased.getState()).thenReturn(IpAddress.State.Releasing);
when(pipReleased.getAddress()).thenReturn(ipReleased);
when(pipReleased.getNetmask()).thenReturn("255.255.255.0");
ipAddresses.add(pipAllocated);
ipAddresses.add(pipReleased);
final Set<Service> services = new HashSet<Service>();
services.add(Service.SourceNat);
services.add(Service.StaticNat);
services.add(Service.PortForwarding);
final List<NiciraNvpDeviceVO> deviceList = new ArrayList<NiciraNvpDeviceVO>();
final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class);
final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class);
when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO);
when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde");
when(nndVO.getHostId()).thenReturn(NETWORK_ID);
final HostVO hvo = mock(HostVO.class);
when(hvo.getId()).thenReturn(NETWORK_ID);
when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde");
when(hostDao.findById(NETWORK_ID)).thenReturn(hvo);
deviceList.add(nndVO);
when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList);
final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class);
when(answer.getResult()).thenReturn(true);
when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer);
assertTrue(element.applyIps(network, ipAddresses, services));
verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() {
@Override
public boolean matches(final Object argument) {
final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand) argument;
if (command.getPublicCidrs().size() == 1)
return true;
return false;
}
}));
}
use of com.cloud.network.PublicIpAddress in project cloudstack by apache.
the class CommandSetupHelper method createVpcAssociatePublicIPCommands.
public void createVpcAssociatePublicIPCommands(final VirtualRouter router, final List<? extends PublicIpAddress> ips, final Commands cmds, final Map<String, String> vlanMacAddress) {
final String ipAssocCommand = "IPAssocVpcCommand";
if (router.getIsRedundantRouter()) {
createRedundantAssociateIPCommands(router, ips, cmds, ipAssocCommand, 0);
return;
}
Pair<IpAddressTO, Long> sourceNatIpAdd = null;
Boolean addSourceNat = null;
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
for (final PublicIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getVlanTag();
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PublicIpAddress>();
}
// state
if (ipAddress.isSourceNat() && ipAddress.getState() == IpAddress.State.Releasing) {
ipAddress.setState(IpAddress.State.Allocated);
}
ipList.add(ipAddress);
vlanIpMap.put(vlanTag, ipList);
}
for (final Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
// Source nat ip address should always be sent first
Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {
@Override
public int compare(final PublicIpAddress o1, final PublicIpAddress o2) {
final boolean s1 = o1.isSourceNat();
final boolean s2 = o2.isSourceNat();
return s1 ^ s2 ? s1 ^ true ? 1 : -1 : 0;
}
});
// Get network rate - required for IpAssoc
final Integer networkRate = _networkModel.getNetworkRate(ipAddrList.get(0).getNetworkId(), router.getId());
final Network network = _networkModel.getNetwork(ipAddrList.get(0).getNetworkId());
final IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
int i = 0;
boolean firstIP = true;
for (final PublicIpAddress ipAddr : ipAddrList) {
final boolean add = ipAddr.getState() == IpAddress.State.Releasing ? false : true;
boolean sourceNat = ipAddr.isSourceNat();
/* enable sourceNAT for the first ip of the public interface
* For additional public subnet source nat rule needs to be added for vm to reach ips in that subnet
*/
if (firstIP) {
sourceNat = true;
}
final String macAddress = vlanMacAddress.get(BroadcastDomainType.getValue(BroadcastDomainType.fromString(ipAddr.getVlanTag())));
final IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, firstIP, sourceNat, BroadcastDomainType.fromString(ipAddr.getVlanTag()).toString(), ipAddr.getGateway(), ipAddr.getNetmask(), macAddress, networkRate, ipAddr.isOneToOneNat());
ip.setTrafficType(network.getTrafficType());
ip.setNetworkName(_networkModel.getNetworkTag(router.getHypervisorType(), network));
ipsToSend[i++] = ip;
if (ipAddr.isSourceNat()) {
sourceNatIpAdd = new Pair<IpAddressTO, Long>(ip, ipAddr.getNetworkId());
addSourceNat = add;
}
//want to set sourcenat to true for all ips to delete source nat rules.
if (!firstIP || add) {
firstIP = false;
}
}
final IpAssocVpcCommand cmd = new IpAssocVpcCommand(ipsToSend);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(ipAddrList.get(0).getNetworkId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(ipAssocCommand, cmd);
}
// set source nat ip
if (sourceNatIpAdd != null) {
final IpAddressTO sourceNatIp = sourceNatIpAdd.first();
final SetSourceNatCommand cmd = new SetSourceNatCommand(sourceNatIp, addSourceNat);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("SetSourceNatCommand", cmd);
}
}
use of com.cloud.network.PublicIpAddress in project cloudstack by apache.
the class CommandSetupHelper method createRedundantAssociateIPCommands.
public void createRedundantAssociateIPCommands(final VirtualRouter router, final List<? extends PublicIpAddress> ips, final Commands cmds, final String ipAssocCommand, final long vmId) {
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
for (final PublicIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getVlanTag();
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PublicIpAddress>();
}
// the state
if (ipAddress.isSourceNat() && ipAddress.getState() == IpAddress.State.Releasing) {
ipAddress.setState(IpAddress.State.Allocated);
}
ipList.add(ipAddress);
vlanIpMap.put(vlanTag, ipList);
}
final List<NicVO> nics = _nicDao.listByVmId(router.getId());
String baseMac = null;
for (final NicVO nic : nics) {
final NetworkVO nw = _networkDao.findById(nic.getNetworkId());
if (nw.getTrafficType() == TrafficType.Public) {
baseMac = nic.getMacAddress();
break;
}
}
for (final Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
// Source nat ip address should always be sent first
Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {
@Override
public int compare(final PublicIpAddress o1, final PublicIpAddress o2) {
final boolean s1 = o1.isSourceNat();
final boolean s2 = o2.isSourceNat();
return s1 ^ s2 ? s1 ^ true ? 1 : -1 : 0;
}
});
// Get network rate - required for IpAssoc
final Integer networkRate = _networkModel.getNetworkRate(ipAddrList.get(0).getNetworkId(), router.getId());
final Network network = _networkModel.getNetwork(ipAddrList.get(0).getNetworkId());
final IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
int i = 0;
boolean firstIP = true;
for (final PublicIpAddress ipAddr : ipAddrList) {
final boolean add = ipAddr.getState() == IpAddress.State.Releasing ? false : true;
boolean sourceNat = ipAddr.isSourceNat();
/* enable sourceNAT for the first ip of the public interface */
if (firstIP) {
sourceNat = true;
}
final String vlanId = ipAddr.getVlanTag();
final String vlanGateway = ipAddr.getGateway();
final String vlanNetmask = ipAddr.getNetmask();
String vifMacAddress = null;
// first ip of other nics
if (router.getVpcId() != null) {
//vifMacAddress = NetUtils.generateMacOnIncrease(baseMac, ipAddr.getVlanId());
vifMacAddress = ipAddr.getMacAddress();
} else {
if (!sourceNat && ipAddr.getVlanId() != 0) {
vifMacAddress = NetUtils.generateMacOnIncrease(baseMac, ipAddr.getVlanId());
} else {
vifMacAddress = ipAddr.getMacAddress();
}
}
final IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, firstIP, sourceNat, vlanId, vlanGateway, vlanNetmask, vifMacAddress, networkRate, ipAddr.isOneToOneNat());
ip.setTrafficType(network.getTrafficType());
ip.setNetworkName(_networkModel.getNetworkTag(router.getHypervisorType(), network));
ipsToSend[i++] = ip;
/*
* send the firstIP = true for the first Add, this is to create
* primary on interface
*/
if (!firstIP || add) {
firstIP = false;
}
}
Long associatedWithNetworkId = ipAddrList.get(0).getAssociatedWithNetworkId();
if (associatedWithNetworkId == null || associatedWithNetworkId == 0) {
associatedWithNetworkId = ipAddrList.get(0).getNetworkId();
}
// for network if the ips does not have any rules, then only last ip
List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(associatedWithNetworkId, null);
int ipsWithrules = 0;
int ipsStaticNat = 0;
for (IPAddressVO ip : userIps) {
if (_rulesDao.countRulesByIpIdAndState(ip.getId(), FirewallRule.State.Active) > 0) {
ipsWithrules++;
}
// 1 static nat rule add
if (ip.isOneToOneNat() && ip.getRuleState() == null) {
ipsStaticNat++;
}
}
final IpAssocCommand cmd = new IpAssocCommand(ipsToSend);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(associatedWithNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
// if there is 1 static nat then it will be checked for remove at the resource
if (ipsWithrules == 0 && ipsStaticNat == 0) {
// there is only one ip address for the network.
cmd.setAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP, "true");
} else {
cmd.setAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP, "false");
}
cmds.addCommand(ipAssocCommand, cmd);
}
}
use of com.cloud.network.PublicIpAddress in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method getPublicIpsToApply.
protected ArrayList<? extends PublicIpAddress> getPublicIpsToApply(final VirtualRouter router, final Provider provider, final Long guestNetworkId, final com.cloud.network.IpAddress.State... skipInStates) {
final long ownerId = router.getAccountId();
final List<? extends IpAddress> userIps;
final Network guestNetwork = _networkDao.findById(guestNetworkId);
if (guestNetwork.getGuestType() == GuestType.Shared) {
// ignore the account id for the shared network
userIps = _networkModel.listPublicIpsAssignedToGuestNtwk(guestNetworkId, null);
} else {
userIps = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, guestNetworkId, null);
}
final List<PublicIp> allPublicIps = new ArrayList<PublicIp>();
if (userIps != null && !userIps.isEmpty()) {
boolean addIp = true;
for (final IpAddress userIp : userIps) {
if (skipInStates != null) {
for (final IpAddress.State stateToSkip : skipInStates) {
if (userIp.getState() == stateToSkip) {
s_logger.debug("Skipping ip address " + userIp + " in state " + userIp.getState());
addIp = false;
break;
}
}
}
if (addIp) {
final IPAddressVO ipVO = _ipAddressDao.findById(userIp.getId());
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(ipVO, _vlanDao.findById(userIp.getVlanId()));
allPublicIps.add(publicIp);
}
}
}
// Get public Ips that should be handled by router
final Network network = _networkDao.findById(guestNetworkId);
final Map<PublicIpAddress, Set<Service>> ipToServices = _networkModel.getIpToServices(allPublicIps, false, true);
final Map<Provider, ArrayList<PublicIpAddress>> providerToIpList = _networkModel.getProviderToIpList(network, ipToServices);
// Only cover virtual router for now, if ELB use it this need to be
// modified
final ArrayList<PublicIpAddress> publicIps = providerToIpList.get(provider);
return publicIps;
}
use of com.cloud.network.PublicIpAddress in project cloudstack by apache.
the class RemoteAccessVpnManagerImpl method createRemoteAccessVpn.
@Override
@DB
public RemoteAccessVpn createRemoteAccessVpn(final long publicIpId, String ipRange, boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
CallContext ctx = CallContext.current();
final Account caller = ctx.getCallingAccount();
Long networkId = null;
// make sure ip address exists
final PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
if (ipAddr == null) {
throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId);
}
_accountMgr.checkAccess(caller, null, true, ipAddr);
if (!ipAddr.readyToUse()) {
throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress());
}
IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
networkId = ipAddress.getAssociatedWithNetworkId();
if (networkId != null) {
_networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
}
final Long vpcId = ipAddress.getVpcId();
/* IP Address used for VPC must be the source NAT IP of whole VPC */
if (vpcId != null && ipAddress.isSourceNat()) {
assert networkId == null;
// No firewall setting for VPC, it would be open internally
openFirewall = false;
}
final boolean openFirewallFinal = openFirewall;
if (networkId == null && vpcId == null) {
throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress: " + ipAddr.getAddress().addr() + " as ip is not associated with any network or VPC");
}
RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);
if (vpnVO != null) {
//if vpn is in Added state, return it to the api
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
}
if (ipRange == null) {
ipRange = RemoteAccessVpnClientIpRange.valueIn(ipAddr.getAccountId());
}
final String[] range = ipRange.split("-");
if (range.length != 2) {
throw new InvalidParameterValueException("Invalid ip range");
}
if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])) {
throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
}
if (!NetUtils.validIpRange(range[0], range[1])) {
throw new InvalidParameterValueException("Invalid ip range " + ipRange);
}
Pair<String, Integer> cidr = null;
// TODO: assumes one virtual network / domr per account per zone
if (networkId != null) {
vpnVO = _remoteAccessVpnDao.findByAccountAndNetwork(ipAddr.getAccountId(), networkId);
if (vpnVO != null) {
//if vpn is in Added state, return it to the api
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
}
//Verify that vpn service is enabled for the network
Network network = _networkMgr.getNetwork(networkId);
if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
}
cidr = NetUtils.getCidr(network.getCidr());
} else {
// Don't need to check VPC because there is only one IP(source NAT IP) available for VPN
Vpc vpc = _vpcDao.findById(vpcId);
cidr = NetUtils.getCidr(vpc.getCidr());
}
// FIXME: This check won't work for the case where the guest ip range
// changes depending on the vlan allocated.
String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
}
// TODO: check sufficient range
// TODO: check overlap with private and public ip ranges in datacenter
long startIp = NetUtils.ip2Long(range[0]);
final String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
final String sharedSecret = PasswordGenerator.generatePresharedKey(_pskLength);
return Transaction.execute(new TransactionCallbackWithException<RemoteAccessVpn, NetworkRuleConflictException>() {
@Override
public RemoteAccessVpn doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
if (vpcId == null) {
_rulesMgr.reservePorts(ipAddr, NetUtils.UDP_PROTO, Purpose.Vpn, openFirewallFinal, caller, NetUtils.VPN_PORT, NetUtils.VPN_L2TP_PORT, NetUtils.VPN_NATT_PORT);
}
RemoteAccessVpnVO vpnVO = new RemoteAccessVpnVO(ipAddr.getAccountId(), ipAddr.getDomainId(), ipAddr.getAssociatedWithNetworkId(), publicIpId, vpcId, range[0], newIpRange, sharedSecret);
if (forDisplay != null) {
vpnVO.setDisplay(forDisplay);
}
return _remoteAccessVpnDao.persist(vpnVO);
}
});
}
Aggregations