Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions api/src/main/java/com/cloud/network/Network.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ public static Routing fromValue(String type) {

String updatingInSequence = "updatingInSequence";
String hideIpAddressUsage = "hideIpAddressUsage";
// Network detail keys for an isolated network's optional custom DHCP range (guest IP allocation
// range within the CIDR). Stored as network details rather than dedicated columns.
String dhcpStartIp = "dhcpStartIp";
String dhcpEndIp = "dhcpEndIp";

class Service {
private static List<Service> supportedServices = new ArrayList<Service>();
Expand Down
1 change: 1 addition & 0 deletions api/src/main/java/com/cloud/network/NetworkProfile.java
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ public void setCidr(String cidr) {
this.cidr = cidr;
}


@Override
public String getNetworkCidr() {
return networkCidr;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd implements UserCmd {
type = CommandType.BOOLEAN, since = "4.23.0", authorized = {RoleType.Admin})
private Boolean keepMacAddressOnPublicNic;

@Parameter(name = ApiConstants.START_IP, type = CommandType.STRING, description = "The beginning of the custom DHCP range within the CIDR for a source NAT isolated network. An empty value clears the range so the whole CIDR is used.", since = "4.23.0")
private String startIp;

@Parameter(name = ApiConstants.END_IP, type = CommandType.STRING, description = "The end of the custom DHCP range within the CIDR for a source NAT isolated network. Defaults to the start IP when not set.", since = "4.23.0")
private String endIp;

/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
Expand Down Expand Up @@ -145,6 +151,14 @@ public String getGuestVmCidr() {
return guestVmCidr;
}

public String getStartIp() {
return startIp;
}

public String getEndIp() {
return endIp;
}

public Boolean getDisplayNetwork() {
return displayNetwork;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement
@Param(description = "CloudStack managed address space, all CloudStack managed Instances get IP address from CIDR")
private String cidr;

@SerializedName(ApiConstants.START_IP)
@Param(description = "the start of the custom DHCP range for an isolated network, within its CIDR", since = "4.24.0")
private String dhcpStartIp;

@SerializedName(ApiConstants.END_IP)
@Param(description = "the end of the custom DHCP range for an isolated network, within its CIDR", since = "4.24.0")
private String dhcpEndIp;

@SerializedName(ApiConstants.NETWORK_CIDR)
@Param(description = "The Network CIDR of the guest Network configured with IP reservation. It is the summation of CIDR and RESERVED_IP_RANGE")
private String networkCidr;
Expand Down Expand Up @@ -511,6 +519,14 @@ public void setCidr(String cidr) {
this.cidr = cidr;
}

public void setDhcpStartIp(String dhcpStartIp) {
this.dhcpStartIp = dhcpStartIp;
}

public void setDhcpEndIp(String dhcpEndIp) {
this.dhcpEndIp = dhcpEndIp;
}

public void setNetworkCidr(String networkCidr) {
this.networkCidr = networkCidr;
}
Expand Down
4 changes: 4 additions & 0 deletions server/src/main/java/com/cloud/api/ApiResponseHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -2632,6 +2632,10 @@ public NetworkResponse createNetworkResponse(ResponseView view, Network network)

// FIXME - either set netmask or cidr
response.setCidr(cidr);
NetworkDetailVO dhcpStartDetail = networkDetailsDao.findDetail(network.getId(), Network.dhcpStartIp);
NetworkDetailVO dhcpEndDetail = networkDetailsDao.findDetail(network.getId(), Network.dhcpEndIp);
response.setDhcpStartIp(dhcpStartDetail != null ? dhcpStartDetail.getValue() : null);
response.setDhcpEndIp(dhcpEndDetail != null ? dhcpEndDetail.getValue() : null);
if (network.getNetworkCidr() != null) {
response.setNetworkCidr((network.getNetworkCidr()));
}
Expand Down
13 changes: 13 additions & 0 deletions server/src/main/java/com/cloud/network/NetworkModelImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@
import com.cloud.network.dao.NetworkAccountDao;
import com.cloud.network.dao.NetworkAccountVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkDetailVO;
import com.cloud.network.dao.NetworkDetailsDao;
import com.cloud.network.dao.NetworkDomainDao;
import com.cloud.network.dao.NetworkDomainVO;
import com.cloud.network.dao.NetworkServiceMapDao;
Expand Down Expand Up @@ -159,6 +161,8 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel, Confi
@Inject
EntityManager _entityMgr;
@Inject
NetworkDetailsDao networkDetailsDao;
@Inject
DataCenterDao _dcDao = null;
@Inject
VlanDao _vlanDao = null;
Expand Down Expand Up @@ -2356,6 +2360,15 @@ public Set<Long> getAvailableIps(Network network, String requestedIp) {
if ((gateway != null) && (allPossibleIps.contains(NetUtils.ip2Long(gateway))))
allPossibleIps.remove(NetUtils.ip2Long(gateway));

NetworkDetailVO dhcpStartDetail = networkDetailsDao.findDetail(network.getId(), Network.dhcpStartIp);
NetworkDetailVO dhcpEndDetail = networkDetailsDao.findDetail(network.getId(), Network.dhcpEndIp);
if (dhcpStartDetail != null && dhcpEndDetail != null
&& StringUtils.isNoneBlank(dhcpStartDetail.getValue(), dhcpEndDetail.getValue())) {
long start = NetUtils.ip2Long(dhcpStartDetail.getValue());
long end = NetUtils.ip2Long(dhcpEndDetail.getValue());
allPossibleIps.removeIf(ip -> ip < start || ip > end);
Comment thread
RosiKyu marked this conversation as resolved.
Resolved
}

return allPossibleIps;
}

Expand Down
107 changes: 107 additions & 0 deletions server/src/main/java/com/cloud/network/NetworkServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -2682,10 +2682,23 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac
}
}

// For an isolated network a start/end IP defines a custom DHCP range within the CIDR that guest IPs are
// allocated from; without it the whole CIDR is used, which is the default. Validate it up front so a bad
// range is rejected before the network is persisted, rather than throwing after commit and leaving an
// orphaned network.
boolean hasIsolatedDhcpRange = StringUtils.isNotBlank(startIP) && isCustomDhcpRangeApplicable(ntwkOff);
if (hasIsolatedDhcpRange) {
validateIsolatedNetworkDhcpRange(startIP, endIP, cidr, gateway);
}
Comment on lines +2685 to +2692

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you extract this as a method with javadoc?


Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, bypassVlanOverlapCheck, name, displayText, caller, physicalNetworkId, zone.getId(),
domainId, isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, secondaryVlanId, privateVlanType, ntwkOff, pNtwk, aclType, owner, cidr, createVlan,
externalId, routerIPv4, routerIPv6, associatedNetwork, ip4Dns1, ip4Dns2, ip6Dns1, ip6Dns2, interfaceMTUs, networkCidrSize, keepMacAddressOnPublicNic);

if (hasIsolatedDhcpRange) {
storeIsolatedNetworkDhcpRange(network.getId(), startIP, endIP);
Comment thread
RosiKyu marked this conversation as resolved.
Resolved
}

// retrieve, acquire and associate the correct IP addresses
checkAndSetRouterSourceNatIp(owner, cmd, network);

Expand Down Expand Up @@ -2720,6 +2733,89 @@ private boolean isNonVpcNetworkSupportingDynamicRouting(NetworkOffering networkO
return !networkOffering.isForVpc() && NetworkOffering.RoutingMode.Dynamic == networkOffering.getRoutingMode();
}

protected void validateIsolatedNetworkDhcpRange(String startIP, String endIP, String cidr, String gateway) {
if (endIP == null) {
endIP = startIP;
}
if (!NetUtils.isIpWithInCidrRange(startIP, cidr) || !NetUtils.isIpWithInCidrRange(endIP, cidr)) {
throw new InvalidParameterValueException(String.format("The DHCP range %s-%s is not within the network CIDR %s", startIP, endIP, cidr));
}
if (NetUtils.ip2Long(startIP) > NetUtils.ip2Long(endIP)) {
throw new InvalidParameterValueException(String.format("The DHCP start IP %s is greater than the end IP %s", startIP, endIP));
}
if (gateway != null && NetUtils.ip2Long(gateway) >= NetUtils.ip2Long(startIP) && NetUtils.ip2Long(gateway) <= NetUtils.ip2Long(endIP)) {
throw new InvalidParameterValueException(String.format("The DHCP range %s-%s must not include the gateway %s", startIP, endIP, gateway));
}
}

protected void storeIsolatedNetworkDhcpRange(long networkId, String startIP, String endIP) {
NetworkVO network = _networksDao.findById(networkId);
if (endIP == null) {
endIP = startIP;
}
validateIsolatedNetworkDhcpRange(startIP, endIP, network.getCidr(), network.getGateway());
_networkDetailsDao.persist(new NetworkDetailVO(networkId, Network.dhcpStartIp, startIP, true));
_networkDetailsDao.persist(new NetworkDetailVO(networkId, Network.dhcpEndIp, endIP, true));
}

/**
* Update the custom DHCP range of an existing network. The feature applies only to a source NAT isolated
* network that is not a VPC tier, the same networks that accept it on creation. A blank start IP clears the
* range so the whole CIDR is used again. Guest IPs are handed out as static DHCP entries, so changing the
* range governs future allocation only and leaves existing leases untouched.
*/
protected void updateIsolatedNetworkDhcpRange(NetworkVO network, String startIP, String endIP) {
NetworkOffering ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (ntwkOff == null || !isCustomDhcpRangeApplicable(ntwkOff)) {
throw new InvalidParameterValueException("A custom DHCP range can only be set on a source NAT isolated network");
}
boolean setRange = StringUtils.isNotBlank(startIP);
if (setRange) {
if (StringUtils.isBlank(endIP)) {
endIP = startIP;
}
// Validate before touching the stored range so a bad range leaves the existing one in place.
validateIsolatedNetworkDhcpRange(startIP, endIP, network.getCidr(), network.getGateway());
}
_networkDetailsDao.removeDetail(network.getId(), Network.dhcpStartIp);
_networkDetailsDao.removeDetail(network.getId(), Network.dhcpEndIp);
if (setRange) {
_networkDetailsDao.addDetail(network.getId(), Network.dhcpStartIp, startIP, true);
_networkDetailsDao.addDetail(network.getId(), Network.dhcpEndIp, endIP, true);
}
}

/**
* A custom DHCP range applies to an isolated network that allocates guest IPs from its CIDR, that is an
* isolated network with SourceNat. This covers a standalone source NAT isolated network and a source NAT VPC
* tier, both of which allocate from the CIDR. A routed (non SourceNat) isolated network and a shared network
* use their start/end IP for a separate IP range, so the custom DHCP range is left to that path there.
*/
protected boolean isCustomDhcpRangeApplicable(NetworkOffering ntwkOff) {
return ntwkOff.getGuestType() == GuestType.Isolated
&& areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat);
}

/**
* Reject applying a Guest VM CIDR reservation that would leave the isolated network's custom DHCP
* range (stored as network details) partly or wholly outside the reserved CIDR, which would starve
* guest IP allocation. A network with no custom range is left untouched.
*/
protected void assertCustomDhcpRangeWithinGuestVmCidr(Network network, long startIp, long endIp, String guestVmCidr) {
NetworkDetailVO dhcpStartDetail = _networkDetailsDao.findDetail(network.getId(), Network.dhcpStartIp);
NetworkDetailVO dhcpEndDetail = _networkDetailsDao.findDetail(network.getId(), Network.dhcpEndIp);
if (dhcpStartDetail == null || dhcpEndDetail == null
|| StringUtils.isAnyBlank(dhcpStartDetail.getValue(), dhcpEndDetail.getValue())) {
return;
}
long dhcpStart = NetUtils.ip2Long(dhcpStartDetail.getValue());
long dhcpEnd = NetUtils.ip2Long(dhcpEndDetail.getValue());
if (dhcpStart < startIp || dhcpEnd > endIp) {
throw new InvalidParameterValueException(String.format("The network has a custom DHCP range %s-%s that falls outside the requested Guest VM CIDR %s. Remove or adjust the DHCP range before applying the reservation.",
dhcpStartDetail.getValue(), dhcpEndDetail.getValue(), guestVmCidr));
}
}

private void validateNetworkCreationSupported(long zoneId, String zoneName, GuestType guestType) {
NsxProviderVO nsxProviderVO = nsxProviderDao.findByZoneId(zoneId);
if (Objects.nonNull(nsxProviderVO) && GuestType.L2.equals(guestType)) {
Expand Down Expand Up @@ -4271,6 +4367,10 @@ public Network updateGuestNetwork(final UpdateNetworkCmd cmd) {
}
}

// A custom DHCP range must stay within the reserved Guest VM CIDR; reject a reservation that would
// leave the stored range partly or wholly outside it, otherwise guest IP allocation could be starved.
assertCustomDhcpRangeWithinGuestVmCidr(network, startIp, endIp, guestVmCidr);

// In some scenarios even though guesVmCidr and network CIDR do not appear similar but
// the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
if (network.getNetworkCidr() == null) {
Expand Down Expand Up @@ -4307,6 +4407,13 @@ public Network updateGuestNetwork(final UpdateNetworkCmd cmd) {
logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
}

if (cmd.getStartIp() != null) {
if (guestVmCidr != null) {
throw new InvalidParameterValueException("Cannot update the DHCP range and the Guest VM CIDR in the same request. Specify only one.");
}
updateIsolatedNetworkDhcpRange(network, cmd.getStartIp(), cmd.getEndIp());
}

Pair<Integer, Integer> mtus = validateMtuOnUpdate(network, dc.getId(), publicMtu, privateMtu);
publicMtu = mtus.first();
privateMtu = mtus.second();
Expand Down
47 changes: 47 additions & 0 deletions server/src/test/java/com/cloud/network/NetworkModelImplTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkDetailVO;
import com.cloud.network.dao.NetworkDetailsDao;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkServiceMapVO;
import com.cloud.network.dao.NetworkVO;
Expand All @@ -70,6 +72,7 @@
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.utils.Pair;
import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.Nic;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
Expand All @@ -92,6 +95,8 @@ public class NetworkModelImplTest {
private VpcDao vpcDao;
@Mock
private NetworkDao _networksDao;
@Mock
private NetworkDetailsDao networkDetailsDao;
@Inject
private NetworkOfferingServiceMapDao networkOfferingServiceMapDao;
@Mock
Expand Down Expand Up @@ -507,4 +512,46 @@ public void getNicAndIpInNetworkReturnsNullWhenVmHasNoNicInNetworkAtAll() {

assertNull(networkModel.getNicAndIpInNetwork(5L, 207L));
}

private NetworkVO networkWithDhcpRange(String cidr, String gateway, String dhcpStart, String dhcpEnd) {
NetworkVO network = mock(NetworkVO.class);
when(network.getCidr()).thenReturn(cidr);
when(network.getGateway()).thenReturn(gateway);
when(network.getId()).thenReturn(1L);
when(networkDetailsDao.findDetail(1L, Network.dhcpStartIp))
.thenReturn(dhcpStart == null ? null : new NetworkDetailVO(1L, Network.dhcpStartIp, dhcpStart, true));
when(networkDetailsDao.findDetail(1L, Network.dhcpEndIp))
.thenReturn(dhcpEnd == null ? null : new NetworkDetailVO(1L, Network.dhcpEndIp, dhcpEnd, true));
Mockito.doReturn(new ArrayList<String>()).when(networkModel).getUsedIpsInNetwork(network);
return network;
}

@Test
public void getAvailableIpsRestrictsToTheDhcpRangeWhenSet() {
NetworkVO network = networkWithDhcpRange("10.1.1.0/24", "10.1.1.1", "10.1.1.10", "10.1.1.20");

Set<Long> ips = networkModel.getAvailableIps(network, null);

long start = NetUtils.ip2Long("10.1.1.10");
long end = NetUtils.ip2Long("10.1.1.20");
for (Long ip : ips) {
assertTrue(ip >= start && ip <= end);
}
assertEquals(11, ips.size());
assertTrue(ips.contains(NetUtils.ip2Long("10.1.1.10")));
assertTrue(ips.contains(NetUtils.ip2Long("10.1.1.20")));
assertFalse(ips.contains(NetUtils.ip2Long("10.1.1.9")));
assertFalse(ips.contains(NetUtils.ip2Long("10.1.1.21")));
}

@Test
public void getAvailableIpsUsesTheWholeCidrWhenNoDhcpRangeIsSet() {
NetworkVO network = networkWithDhcpRange("10.1.1.0/24", "10.1.1.1", null, null);

Set<Long> ips = networkModel.getAvailableIps(network, null);

assertTrue(ips.contains(NetUtils.ip2Long("10.1.1.10")));
assertTrue(ips.contains(NetUtils.ip2Long("10.1.1.250")));
assertFalse(ips.contains(NetUtils.ip2Long("10.1.1.1")));
}
}
Loading