From a1ffb2aa384d1ef0151d19d2cabefb7e07d2abd9 Mon Sep 17 00:00:00 2001 From: Wido den Hollander Date: Tue, 15 Sep 2026 08:33:56 +0000 Subject: [PATCH 1/8] Direct Routed (L3) guest networks: route public IPv4/IPv6 directly to Instances Add a guest network type in which the hypervisor performs L3 routing for the Instance: no Virtual Router, no NAT and no DHCP. Each Instance receives a public IPv4 address as a /32 and/or an IPv6 address as a /128, with a shared, host-independent link-local gateway (169.254.0.1 and fe80::1) that every hypervisor carries. All addressing reaches the Instance via ConfigDrive/cloud-init; a routing daemon on the host (FRR, BIRD, ...) advertises the addresses to the fabric and is deliberately out of scope for CloudStack. The networks live on a dedicated physical network with the new ROUTED isolation method, so the feature can be added to existing zones without touching anything already running there. Each network carries a routed:// broadcast domain, the id allocated from the physical network's vnet range or chosen by the operator, which names the network's bridge on every host. Routed ids are validated and canonicalised: a positive integer of at most ten digits, given bare or as routed://. A routed public range may not take an id that a guest network holds or that lies inside a ROUTED physical network's vnet range. Both address families are optional and IPv6-only networks are supported. IPv4 is a subnet (cidr=..., or netmask plus start/end IP), IPv6 is an ip6cidr alone: addresses derive from the subnet and the NIC MAC with EUI-64, so no range exists. No gateways are declared or stored. createNetwork gains an optional cidr parameter (L3 only, additive); an explicit startip/endip must lie inside the given subnet. The zone-wide IPv4 overlap check for L3 ranges runs in the range-creation path that commitNetwork() uses, and the vlan overlap check treats a subnet overlap with an L3 network as a conflict, so both directions are covered. Secondary IPs on L3 NICs follow the Shared branch of allocateSecondaryGuestIP. Zone IPv6 DNS is not required for L3 networks. A DefaultL3NetworkOffering (UserData and DNS via ConfigDrive, security groups) is created on install and upgrade. General fixes the feature surfaced but that apply beyond it: auto-allocated ids are exempt from the dynamic-vlan-range check in createVlanAndPublicIpRange; canUseForDeploy() counts the real IPv4 pool and no longer hides IPv4-less networks from the deploy wizard; the zone-wide IPv6 overlap check keys on ip6_cidr rather than ip6_gateway. Implements #12210 --- .../main/java/com/cloud/network/Network.java | 4 +- .../main/java/com/cloud/network/Networks.java | 44 ++++ .../com/cloud/offering/NetworkOffering.java | 1 + .../user/network/CreateNetworkCmd.java | 14 +- .../user/network/ListNetworkOfferingsCmd.java | 2 +- .../command/user/vm/RemoveIpFromVmNicCmd.java | 12 +- .../java/com/cloud/network/NetworksTest.java | 15 ++ .../user/network/CreateNetworkCmdTest.java | 2 +- .../api/NetworkRulesVmSecondaryIpCommand.java | 16 ++ .../service/NetworkOrchestrationService.java | 2 + .../orchestration/NetworkOrchestrator.java | 59 ++++- .../ConfigurationManagerImpl.java | 161 ++++++++++--- .../cloud/network/IpAddressManagerImpl.java | 3 +- .../cloud/network/Ipv6AddressManagerImpl.java | 2 +- .../com/cloud/network/NetworkModelImpl.java | 13 +- .../com/cloud/network/NetworkServiceImpl.java | 224 ++++++++++++++++-- .../network/guru/DirectRoutedNetworkGuru.java | 192 +++++++++++++++ .../cloud/network/guru/PublicNetworkGuru.java | 62 ++++- .../security/SecurityGroupManagerImpl.java | 23 +- .../java/com/cloud/vm/UserVmManagerImpl.java | 2 +- .../spring-server-network-context.xml | 3 + .../ConfigurationManagerImplTest.java | 122 ++++++++++ .../cloud/network/NetworkModelImplTest.java | 62 +++++ .../cloud/network/NetworkServiceImplTest.java | 129 ++++++++++ .../guru/DirectRoutedNetworkGuruTest.java | 197 +++++++++++++++ .../network/guru/PublicNetworkGuruTest.java | 135 +++++++++++ .../com/cloud/vpc/MockNetworkManagerImpl.java | 5 + .../java/com/cloud/utils/net/NetUtils.java | 22 +- 28 files changed, 1438 insertions(+), 90 deletions(-) create mode 100644 server/src/main/java/com/cloud/network/guru/DirectRoutedNetworkGuru.java create mode 100644 server/src/test/java/com/cloud/network/guru/DirectRoutedNetworkGuruTest.java create mode 100644 server/src/test/java/com/cloud/network/guru/PublicNetworkGuruTest.java diff --git a/api/src/main/java/com/cloud/network/Network.java b/api/src/main/java/com/cloud/network/Network.java index 2f0bcdd5ef9a..d7b467bab5a7 100644 --- a/api/src/main/java/com/cloud/network/Network.java +++ b/api/src/main/java/com/cloud/network/Network.java @@ -43,7 +43,7 @@ public interface Network extends ControlledEntity, StateObject, InternalIdentity, Identity, Serializable, Displayable { enum GuestType { - Shared, Isolated, L2; + Shared, Isolated, L2, L3; public static GuestType fromValue(String type) { if (StringUtils.isBlank(type)) { @@ -54,6 +54,8 @@ public static GuestType fromValue(String type) { return Isolated; } else if (type.equalsIgnoreCase("L2")) { return L2; + } else if (type.equalsIgnoreCase("L3")) { + return L3; } else { throw new InvalidParameterValueException("Unexpected Guest type : " + type); } diff --git a/api/src/main/java/com/cloud/network/Networks.java b/api/src/main/java/com/cloud/network/Networks.java index 61a1c820723f..2ede10894af5 100644 --- a/api/src/main/java/com/cloud/network/Networks.java +++ b/api/src/main/java/com/cloud/network/Networks.java @@ -18,6 +18,7 @@ import java.net.URI; import java.net.URISyntaxException; +import java.util.regex.Pattern; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.commons.lang3.StringUtils; @@ -131,6 +132,23 @@ public URI toUri(T value) { } } }, + /** + * Direct Routed (L3) networks: the id is a label naming the per-network bridge on the + * hypervisor (brdr-<id>), not an encapsulation — nothing appears on the wire. + */ + Routed("routed", Long.class) { + @Override + public URI toUri(T value) { + try { + if (value.toString().contains("://")) + return new URI(value.toString()); + else + return new URI("routed://" + value.toString()); + } catch (URISyntaxException e) { + throw new CloudRuntimeException("Unable to convert to broadcast URI: " + value); + } + } + }, UnDecided(null, null), OpenDaylight("opendaylight", String.class), TUNGSTEN("tf", String.class), @@ -161,6 +179,32 @@ public Class type() { return type; } + /** + * A routed id — the value of a routed://<id> broadcast domain — names a bridge on + * every hypervisor (brdr-<id>, at most 15 characters) and derives that bridge's MAC + * address from five bytes, so it is a positive integer of at most ten digits without + * leading zeros. + */ + public static final int ROUTED_ID_MAX_DIGITS = 10; + private static final Pattern ROUTED_ID_PATTERN = Pattern.compile("^[1-9][0-9]{0," + (ROUTED_ID_MAX_DIGITS - 1) + "}$"); + + /** + * Extracts the routed id from a bare number or from a routed://<id> URI string. + * + * @return the bare id, or null when the candidate is not a valid routed id + */ + public static String getRoutedId(String candidate) { + if (StringUtils.isBlank(candidate)) { + return null; + } + String id = candidate.trim(); + String prefix = Routed.scheme() + "://"; + if (id.startsWith(prefix)) { + id = id.substring(prefix.length()); + } + return ROUTED_ID_PATTERN.matcher(id).matches() ? id : null; + } + /** * The default implementation of toUri returns an uri with the scheme and value as host * diff --git a/api/src/main/java/com/cloud/offering/NetworkOffering.java b/api/src/main/java/com/cloud/offering/NetworkOffering.java index c7bef60f5fd3..29d1b6e27885 100644 --- a/api/src/main/java/com/cloud/offering/NetworkOffering.java +++ b/api/src/main/java/com/cloud/offering/NetworkOffering.java @@ -82,6 +82,7 @@ enum RoutingMode { public final static String DefaultL2NetworkOfferingVlan = "DefaultL2NetworkOfferingVlan"; public final static String DefaultL2NetworkOfferingConfigDrive = "DefaultL2NetworkOfferingConfigDrive"; public final static String DefaultL2NetworkOfferingConfigDriveVlan = "DefaultL2NetworkOfferingConfigDriveVlan"; + public final static String DefaultL3NetworkOffering = "DefaultL3NetworkOffering"; /** * @return name for the network offering. diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java index 79fb5f6d01cf..d334043d7d55 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java @@ -87,6 +87,12 @@ public class CreateNetworkCmd extends BaseCmd implements UserCmd { + "for shared networks and isolated networks when it belongs to VPC") private String netmask; + @Parameter(name = ApiConstants.CIDR, type = CommandType.STRING, since = "24.0.0", + description = "The IPv4 subnet of the Network in CIDR notation, e.g. 192.0.2.0/24. Supported for L3 (Direct Routed) " + + "networks only, as an alternative to netmask: the IP range defaults to the subnet's usable addresses, " + + "and startip/endip may narrow it") + private String cidr; + @Parameter(name = ApiConstants.START_IP, type = CommandType.STRING, description = "The beginning IP address in the Network IP range") private String startIp; @@ -231,6 +237,10 @@ public String getNetmask() { return netmask; } + public String getCidr() { + return cidr; + } + public String getStartIp() { return startIp; } @@ -340,10 +350,10 @@ public Long getPhysicalNetworkId() { } } if (physicalNetworkId != null) { - if ((offering.getGuestType() == GuestType.Shared) || (offering.getGuestType() == GuestType.L2)) { + if ((offering.getGuestType() == GuestType.Shared) || (offering.getGuestType() == GuestType.L2) || (offering.getGuestType() == GuestType.L3)) { return physicalNetworkId; } else { - throw new InvalidParameterValueException("Physical network ID can be specified for networks of guest IP type " + GuestType.Shared + " or " + GuestType.L2 + " only."); + throw new InvalidParameterValueException(String.format("Physical network ID can be specified for networks of guest IP type %s, %s or %s only.", GuestType.Shared, GuestType.L2, GuestType.L3)); } } else { if (zoneId == null) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java index ff3b61056be3..0238219b729d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java @@ -82,7 +82,7 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { description = "The ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") private Long networkId; - @Parameter(name = ApiConstants.GUEST_IP_TYPE, type = CommandType.STRING, description = "List network offerings by guest type: shared or isolated") + @Parameter(name = ApiConstants.GUEST_IP_TYPE, type = CommandType.STRING, description = "List network offerings by guest type: Shared, Isolated, L2 or L3") private String guestIpType; @Parameter(name = ApiConstants.SUPPORTED_SERVICES, diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java index f4c4d82b30d4..f8bdfe718d1b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java @@ -124,6 +124,16 @@ public NetworkType getNetworkType() { } + /** + * A Direct Routed (L3) network needs the agent told when a secondary IP goes away, so the + * host route and neighbour entry are removed - otherwise the host keeps routing an address + * the Instance no longer owns, and the routing daemon keeps advertising it. + */ + private boolean isDirectRoutedNetwork() { + Network ntwk = _entityMgr.findById(Network.class, getNetworkId()); + return ntwk != null && Network.GuestType.L3.equals(ntwk.getGuestType()); + } + private boolean isZoneSGEnabled() { Network ntwk = _entityMgr.findById(Network.class, getNetworkId()); DataCenter dc = _entityMgr.findById(DataCenter.class, ntwk.getDataCenterId()); @@ -144,7 +154,7 @@ public void execute() throws InvalidParameterValueException { secIp = nicSecIp.getIp6Address(); } - if (isZoneSGEnabled()) { + if (isZoneSGEnabled() || isDirectRoutedNetwork()) { //remove the security group rules for this secondary ip boolean success = false; success = _securityGroupService.securityGroupRulesForVmSecIp(nicSecIp.getNicId(), secIp, false); diff --git a/api/src/test/java/com/cloud/network/NetworksTest.java b/api/src/test/java/com/cloud/network/NetworksTest.java index 6f0f3fbd1efe..871b413ec134 100644 --- a/api/src/test/java/com/cloud/network/NetworksTest.java +++ b/api/src/test/java/com/cloud/network/NetworksTest.java @@ -123,6 +123,21 @@ public void otherTypesTest() throws URISyntaxException { Assert.assertEquals("id2 should be \"2\"", "2", id); } + @Test + public void getRoutedIdAcceptsBareAndPrefixedIds() { + Assert.assertEquals("5828", BroadcastDomainType.getRoutedId("5828")); + Assert.assertEquals("5828", BroadcastDomainType.getRoutedId("routed://5828")); + Assert.assertEquals("9999999999", BroadcastDomainType.getRoutedId("9999999999")); + Assert.assertEquals("routed://5828", BroadcastDomainType.Routed.toUri(BroadcastDomainType.getRoutedId("routed://5828")).toString()); + } + + @Test + public void getRoutedIdRejectsMalformedIds() { + for (String candidate : new String[] {null, "", "0", "0534", "abc", "routed://abc", "routed://5828;x", "vlan://5828", "10000000000", "58 28"}) { + Assert.assertNull("expected " + candidate + " to be rejected", BroadcastDomainType.getRoutedId(candidate)); + } + } + @Test public void invalidTypesTest() throws URISyntaxException { String uri1 = "https://1"; diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmdTest.java index 3f5b75828025..8b1b8618094b 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmdTest.java @@ -251,7 +251,7 @@ public void testGetPhysicalNetworkIdForNonSharedNet() { try { cmd.getPhysicalNetworkId(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().startsWith("Physical network ID can be specified for networks of guest IP type Shared or L2 only.")); + Assert.assertTrue(e.getMessage().startsWith("Physical network ID can be specified for networks of guest IP type Shared, L2 or L3 only.")); } } diff --git a/core/src/main/java/com/cloud/agent/api/NetworkRulesVmSecondaryIpCommand.java b/core/src/main/java/com/cloud/agent/api/NetworkRulesVmSecondaryIpCommand.java index c0752a1e97e5..ed6949a48095 100644 --- a/core/src/main/java/com/cloud/agent/api/NetworkRulesVmSecondaryIpCommand.java +++ b/core/src/main/java/com/cloud/agent/api/NetworkRulesVmSecondaryIpCommand.java @@ -28,12 +28,28 @@ public class NetworkRulesVmSecondaryIpCommand extends Command { private String vmSecIp; private String vmMac; private String action; + private boolean directRouted; + private boolean applySecurityGroupRules = true; public NetworkRulesVmSecondaryIpCommand(String vmName, VirtualMachine.Type type) { this.vmName = vmName; this.type = type; } + public NetworkRulesVmSecondaryIpCommand(String vmName, String vmMac, String secondaryIp, boolean action, boolean directRouted, boolean applySecurityGroupRules) { + this(vmName, vmMac, secondaryIp, action); + this.directRouted = directRouted; + this.applySecurityGroupRules = applySecurityGroupRules; + } + + public boolean isDirectRouted() { + return directRouted; + } + + public boolean isApplySecurityGroupRules() { + return applySecurityGroupRules; + } + public NetworkRulesVmSecondaryIpCommand(String vmName, String vmMac, String secondaryIp, boolean action) { this.vmName = vmName; this.vmMac = vmMac; diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java b/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java index 832694c0782a..0c8b3059a3bb 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java @@ -280,6 +280,8 @@ void prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationC boolean isSharedNetworkWithoutSpecifyVlan(NetworkOffering offering); + boolean isL3NetworkWithoutSpecifyVlan(NetworkOffering offering); + boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements); boolean destroyNetwork(long networkId, ReservationContext context, boolean forced); diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java index d919b84ec86b..43a491765e0c 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -569,6 +569,15 @@ public boolean configure(final String name, final Map params) th sgProviders.add(Provider.SecurityGroupProvider); defaultSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, sgProviders); + final Map> defaultL3NetworkOfferingProviders = new HashMap<>(); + final Set configDriveProvider = new HashSet<>(); + configDriveProvider.add(Provider.ConfigDrive); + defaultL3NetworkOfferingProviders.put(Service.UserData, configDriveProvider); + defaultL3NetworkOfferingProviders.put(Service.Dns, configDriveProvider); + final Set l3SecurityGroupProvider = new HashSet<>(); + l3SecurityGroupProvider.add(Provider.SecurityGroupProvider); + defaultL3NetworkOfferingProviders.put(Service.SecurityGroup, l3SecurityGroupProvider); + tungstenProvider.add(Provider.Tungsten); final Map> defaultTungstenSharedSGEnabledNetworkOfferingProviders = new HashMap<>(); defaultTungstenSharedSGEnabledNetworkOfferingProviders.put(Service.Connectivity, tungstenProvider); @@ -632,6 +641,13 @@ public void doInTransactionWithoutResult(final TransactionStatus status) { null, true, false, false, false, false, null, null, null, true, null, null, false, null, null); } + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultL3NetworkOffering) == null) { + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultL3NetworkOffering, + "Offering for Direct Routed (L3) networks - public IPs routed directly to Instances, configuration via ConfigDrive (UserData and DNS), Security Groups enabled, no Virtual Router and no DHCP", + TrafficType.Guest, null, false, Availability.Optional, null, defaultL3NetworkOfferingProviders, true, Network.GuestType.L3, false, null, true, + null, true, false, null, false, null, true, false, false, false, false, null, null, null, true, null, null, false, null, null); + } + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DEFAULT_TUNGSTEN_SHARED_NETWORK_OFFERING_WITH_SGSERVICE) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DEFAULT_TUNGSTEN_SHARED_NETWORK_OFFERING_WITH_SGSERVICE, "Offering for Tungsten Shared Security group enabled networks", TrafficType.Guest, null, true, Availability.Optional, null, defaultTungstenSharedSGEnabledNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, @@ -3170,7 +3186,7 @@ private Network createGuestNetwork(final long networkOfferingId, final String na final boolean vlanSpecified = vlanId != null; if (vlanSpecified != ntwkOff.isSpecifyVlan()) { if (vlanSpecified) { - if (!isSharedNetworkWithoutSpecifyVlan(ntwkOff) && !isPrivateGatewayWithoutSpecifyVlan(ntwkOff)) { + if (!isSharedNetworkWithoutSpecifyVlan(ntwkOff) && !isL3NetworkWithoutSpecifyVlan(ntwkOff) && !isPrivateGatewayWithoutSpecifyVlan(ntwkOff)) { throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false"); } } else { @@ -3180,13 +3196,18 @@ private Network createGuestNetwork(final long networkOfferingId, final String na if (vlanSpecified) { URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk); + if (BroadcastDomainType.getSchemeValue(uri) == BroadcastDomainType.Routed + && _vlanDao.findByZoneAndVlanId(zoneId, uri.toString()) != null) { + throw new InvalidParameterValueException(String.format( + "The routed id %s is already used by a public IP range in zone %s", vlanId, zone.getName())); + } // Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null; - if (isSharedNetworkWithoutSpecifyVlan(ntwkOff) || isPrivateGatewayWithoutSpecifyVlan(ntwkOff)) { + if (isSharedNetworkWithoutSpecifyVlan(ntwkOff) || isL3NetworkWithoutSpecifyVlan(ntwkOff) || isPrivateGatewayWithoutSpecifyVlan(ntwkOff)) { bypassVlanOverlapCheck = true; } //don't allow to specify vlan tag used by physical network for dynamic vlan allocation - if (!(bypassVlanOverlapCheck && (ntwkOff.getGuestType() == GuestType.Shared || isPrivateNetwork)) + if (!(bypassVlanOverlapCheck && (ntwkOff.getGuestType() == GuestType.Shared || ntwkOff.getGuestType() == GuestType.L3 || isPrivateNetwork)) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) { throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName()); @@ -3327,12 +3348,12 @@ public Network doInTransaction(final TransactionStatus status) { final NetworkVO userNetwork = new NetworkVO(); userNetwork.setNetworkDomain(networkDomainFinal); - if (cidr != null && gateway != null) { + if (cidr != null && (gateway != null || ntwkOff.getGuestType() == GuestType.L3)) { userNetwork.setCidr(cidr); userNetwork.setGateway(gateway); } - if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) { + if (StringUtils.isNotBlank(ip6Cidr) && (StringUtils.isNotBlank(ip6Gateway) || ntwkOff.getGuestType() == GuestType.L3)) { userNetwork.setIp6Cidr(ip6Cidr); userNetwork.setIp6Gateway(ip6Gateway); } @@ -3391,14 +3412,17 @@ public Network doInTransaction(final TransactionStatus status) { uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk); } - if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) { + final boolean isRoutedUri = uri != null && BroadcastDomainType.getSchemeValue(uri) == BroadcastDomainType.Routed; + if (!isRoutedUri && _networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) { throw new InvalidParameterValueException(String.format( "Network with vlan %s already exists or overlaps with other network pvlans in zone %s", vlanIdFinal, zone)); } userNetwork.setBroadcastUri(uri); - if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { + if (uri != null && BroadcastDomainType.getSchemeValue(uri) == BroadcastDomainType.Routed) { + userNetwork.setBroadcastDomainType(BroadcastDomainType.Routed); + } else if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan); } else { userNetwork.setBroadcastDomainType(BroadcastDomainType.Native); @@ -3463,6 +3487,19 @@ public boolean isSharedNetworkWithoutSpecifyVlan(NetworkOffering offering) { return !offering.isSpecifyVlan(); } + /** + * An L3 (Direct Routed) network whose offering does not carry specifyVlan gets its routed id + * allocated from the physical network's vnet range at creation, the same way a Shared network + * without specifyVlan gets its VLAN — and released the same way on deletion. + */ + @Override + public boolean isL3NetworkWithoutSpecifyVlan(NetworkOffering offering) { + if (offering == null || offering.getTrafficType() != TrafficType.Guest || offering.getGuestType() != GuestType.L3) { + return false; + } + return !offering.isSpecifyVlan(); + } + private boolean isPrivateGatewayWithoutSpecifyVlan(NetworkOffering ntwkOff) { return ntwkOff.getId() == _networkOfferingDao.findByUniqueName(NetworkOffering.SystemPrivateGatewayNetworkOfferingWithoutVlan).getId(); } @@ -3480,9 +3517,13 @@ protected URI encodeVlanIdIntoBroadcastUri(String vlanId, PhysicalNetwork pNtwk) if (!pNtwk.getIsolationMethods().isEmpty() && StringUtils.isNotBlank(pNtwk.getIsolationMethods().get(0))) { String isolationMethod = pNtwk.getIsolationMethods().get(0).toLowerCase(); String vxlan = BroadcastDomainType.Vxlan.toString().toLowerCase(); + String routed = BroadcastDomainType.Routed.toString().toLowerCase(); if (isolationMethod.equals(vxlan)) { return BroadcastDomainType.encodeStringIntoBroadcastUri(vlanId, BroadcastDomainType.Vxlan); } + if (isolationMethod.equals(routed)) { + return BroadcastDomainType.encodeStringIntoBroadcastUri(vlanId, BroadcastDomainType.Routed); + } } return BroadcastDomainType.fromString(vlanId); } @@ -3911,8 +3952,8 @@ protected Pair> deleteVlansInNetwork(final NetworkVO netwo logger.debug("Deleted ip range for private network {}", network); } - // release vlans of user-shared networks without specifyvlan - if (isSharedNetworkWithoutSpecifyVlan(_networkOfferingDao.findById(network.getNetworkOfferingId()))) { + final NetworkOffering deletedNetworkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + if (isSharedNetworkWithoutSpecifyVlan(deletedNetworkOffering) || isL3NetworkWithoutSpecifyVlan(deletedNetworkOffering)) { logger.debug("Releasing vnet for the network {}", network); _dcDao.releaseVnet(BroadcastDomainType.getValue(network.getBroadcastUri()), network.getDataCenterId(), network.getPhysicalNetworkId(), network.getAccountId(), network.getReservationId()); diff --git a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java index 6b96540734d0..ca236d9ef570 100644 --- a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java @@ -5911,15 +5911,20 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, vlanId = Vlan.UNTAGGED; } + if (vlanId != null && vlanId.startsWith(BroadcastDomainType.Routed.scheme() + "://")) { + vlanId = canonicalizeRoutedRangeId(zoneId, vlanId); + } + final VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; if ((domain != null || vlanOwner != null) && zone.getNetworkType() != NetworkType.Advanced) { throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type " + NetworkType.Advanced); } + final boolean gatewaylessL3 = network.getGuestType() == GuestType.L3; if (ipv4) { // Make sure the gateway is valid - if (!NetUtils.isValidIp4(vlanGateway)) { + if (!(gatewaylessL3 && vlanGateway == null) && !NetUtils.isValidIp4(vlanGateway)) { throw new InvalidParameterValueException("Please specify a valid gateway"); } @@ -5930,7 +5935,7 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, } if (ipv6) { - if (!NetUtils.isValidIp6(vlanIp6Gateway)) { + if (!(gatewaylessL3 && vlanIp6Gateway == null) && !NetUtils.isValidIp6(vlanIp6Gateway)) { throw new InvalidParameterValueException("Please specify a valid IPv6 gateway"); } if (!NetUtils.isValidIp6Cidr(vlanIp6Cidr)) { @@ -5938,12 +5943,14 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, } } - boolean isSharedNetworkWithoutSpecifyVlan = _networkMgr.isSharedNetworkWithoutSpecifyVlan(_networkOfferingDao.findById(network.getNetworkOfferingId())); + final NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + boolean isSharedNetworkWithoutSpecifyVlan = _networkMgr.isSharedNetworkWithoutSpecifyVlan(networkOffering); + boolean isL3NetworkWithoutSpecifyVlan = _networkMgr.isL3NetworkWithoutSpecifyVlan(networkOffering); if (ipv4) { - final String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask); + final String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway != null ? vlanGateway : startIP, vlanNetmask); //Make sure start and end ips are with in the range of cidr calculated for this gateway and netmask { - if (!NetUtils.isIpWithInCidrRange(vlanGateway, newCidr) || !NetUtils.isIpWithInCidrRange(startIP, newCidr) || !NetUtils.isIpWithInCidrRange(endIP, newCidr)) { + if ((vlanGateway != null && !NetUtils.isIpWithInCidrRange(vlanGateway, newCidr)) || !NetUtils.isIpWithInCidrRange(startIP, newCidr) || !NetUtils.isIpWithInCidrRange(endIP, newCidr)) { throw new InvalidParameterValueException("Please specify a valid IP range or valid netmask or valid gateway"); } @@ -5966,6 +5973,10 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, if (!isSharedNetworkWithoutSpecifyVlan) { checkZoneVlanIpOverlap(zone, network, newCidr, vlanId, vlanGateway, vlanNetmask, startIP, endIP); } + + if (gatewaylessL3) { + checkOverlapPublicIpRange(zoneId, startIP, endIP); + } } String ipv6Range = null; @@ -5977,7 +5988,7 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, final List vlans = _vlanDao.listByZone(zone.getId()); for (final VlanVO vlan : vlans) { - if (vlan.getIp6Gateway() == null) { + if (vlan.getIp6Cidr() == null) { continue; } if ((StringUtils.isAllEmpty(ipv6Range, vlan.getIp6Range())) && @@ -5997,7 +6008,7 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, } // Check if the vlan is being used - if (isSharedNetworkWithoutSpecifyVlan) { + if (isSharedNetworkWithoutSpecifyVlan || isL3NetworkWithoutSpecifyVlan) { bypassVlanOverlapCheck = true; } if (!bypassVlanOverlapCheck && !forExternalProvider && !_zoneDao.findVnet(zoneId, physicalNetworkId, BroadcastDomainType.getValue(BroadcastDomainType.fromString(vlanId))).isEmpty()) { @@ -6020,7 +6031,7 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, if (vlan != null && network.getTrafficType() != TrafficType.Public) { if (ipv4) { - addCidrAndGatewayForIpv4(networkId, vlanGateway, vlanNetmask); + addCidrAndGatewayForIpv4(networkId, vlanGateway, vlanNetmask, startIP); } else if (ipv6) { addCidrAndGatewayForIpv6(networkId, vlanIp6Gateway, vlanIp6Cidr); } @@ -6029,10 +6040,48 @@ public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, return vlan; } - private void addCidrAndGatewayForIpv4(final long networkId, final String vlanGateway, final String vlanNetmask) { + /** + * Validates the routed id of a public IP range created with vlan=routed://<id> (SystemVMs on + * a ROUTED physical network). The id must be a well-formed routed id, must not already name a + * guest network's bridge anywhere in the zone, and must not fall inside the routed-id range + * of any ROUTED physical network, from which L3 networks without specifyVlan draw theirs: + * guest networks and public ranges share one id space, since both name a brdr-<id> bridge on + * the hosts. + * + * @return the canonical routed://<id> form + */ + protected String canonicalizeRoutedRangeId(final long zoneId, final String vlanId) { + final String routedId = BroadcastDomainType.getRoutedId(vlanId); + if (routedId == null) { + throw new InvalidParameterValueException(String.format( + "%s is not a valid routed id: expected routed:// with a positive integer of at most %d digits", vlanId, BroadcastDomainType.ROUTED_ID_MAX_DIGITS)); + } + final String canonicalVlanId = BroadcastDomainType.Routed.toUri(routedId).toString(); + if (!_networkDao.listByZoneAndUriAndGuestType(zoneId, canonicalVlanId, null).isEmpty()) { + throw new InvalidParameterValueException(String.format("The routed id %s is already used by a guest network in zone %d", routedId, zoneId)); + } + for (final PhysicalNetworkVO physicalNetwork : _physicalNetworkDao.listByZone(zoneId)) { + if (physicalNetwork.getIsolationMethods() == null || !physicalNetwork.getIsolationMethods().contains("ROUTED")) { + continue; + } + if (!_zoneDao.findVnet(zoneId, physicalNetwork.getId(), routedId).isEmpty()) { + throw new InvalidParameterValueException(String.format( + "The routed id %s lies inside the routed id range of physical network %s, from which %s networks are allocated their ids", + routedId, physicalNetwork.getName(), GuestType.L3)); + } + } + return canonicalVlanId; + } + + /** + * Appends the new range's subnet, and its gateway when the range carries one, to the network + * row. A gateway-less range (L3 networks) derives the same subnet from its start IP, and its + * absent gateway leaves the network's gateway untouched. + */ + private void addCidrAndGatewayForIpv4(final long networkId, final String vlanGateway, final String vlanNetmask, final String startIP) { final NetworkVO networkVO = _networkDao.findById(networkId); String networkCidr = networkVO.getCidr(); - String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask); + String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway != null ? vlanGateway : startIP, vlanNetmask); String newNetworkCidr = com.cloud.utils.StringUtils.updateCommaSeparatedStringWithValue(networkCidr, newCidr, true); networkVO.setCidr(newNetworkCidr); @@ -6079,6 +6128,8 @@ private String getNetworkVlanId(Network network, boolean connectivityWithoutVlan if (network.getBroadcastDomainType() != BroadcastDomainType.Vlan) { networkVlanId = networkVlanId.split("-")[0]; } + } else if (BroadcastDomainType.getSchemeValue(uri) == BroadcastDomainType.Routed) { + networkVlanId = BroadcastDomainType.getValue(uri); } } return networkVlanId; @@ -6093,10 +6144,10 @@ private void checkZoneVlanIpOverlap(DataCenterVO zone, Network network, String n final String otherVlanGateway = vlan.getVlanGateway(); final String otherVlanNetmask = vlan.getVlanNetmask(); // Continue if it's not IPv4 - if (ObjectUtils.anyNull(otherVlanGateway, otherVlanNetmask, vlan.getNetworkId())) { + if (ObjectUtils.anyNull(otherVlanNetmask, vlan.getNetworkId()) || (otherVlanGateway == null && StringUtils.isBlank(vlan.getIpRange()))) { continue; } - final String otherCidr = NetUtils.getCidrFromGatewayAndNetmask(otherVlanGateway, otherVlanNetmask); + final String otherCidr = NetUtils.getCidrFromGatewayAndNetmask(otherVlanGateway != null ? otherVlanGateway : vlan.getIpRange().split("\\-")[0], otherVlanNetmask); if( !NetUtils.isNetworksOverlap(newCidr, otherCidr)) { continue; } @@ -6115,7 +6166,7 @@ private void checkZoneVlanIpOverlap(DataCenterVO zone, Network network, String n } // extend IP range - if (!vlanGateway.equals(otherVlanGateway) || !vlanNetmask.equals(vlan.getVlanNetmask())) { + if (!Objects.equals(vlanGateway, otherVlanGateway) || !Objects.equals(vlanNetmask, vlan.getVlanNetmask())) { throw new InvalidParameterValueException("The IP range has already been added with gateway " + otherVlanGateway + " ,and netmask " + otherVlanNetmask + ", Please specify the gateway/netmask if you want to extend ip range" ); @@ -6133,7 +6184,7 @@ private void checkZoneVlanIpOverlap(DataCenterVO zone, Network network, String n final Long nwId = vlan.getNetworkId(); if (nwId != null) { final Network nw = _networkModel.getNetwork(nwId); - if (nw != null && nw.getTrafficType() == TrafficType.Public) { + if (nw != null && (nw.getTrafficType() == TrafficType.Public || nw.getGuestType() == GuestType.L3)) { overlapped = true; } } @@ -6919,12 +6970,14 @@ private void checkPublicIpRangeErrors(final long zoneId, final String vlanId, fi throw new InvalidParameterValueException("Please ensure that your start IP and end IP are in the same subnet, as per the IP range's netmask."); } - if (!NetUtils.sameSubnet(startIP, vlanGateway, vlanNetmask)) { - throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as your IP range's gateway, as per the IP range's netmask."); - } + if (vlanGateway != null) { + if (!NetUtils.sameSubnet(startIP, vlanGateway, vlanNetmask)) { + throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as your IP range's gateway, as per the IP range's netmask."); + } - if (endIP != null && !NetUtils.sameSubnet(endIP, vlanGateway, vlanNetmask)) { - throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as your IP range's gateway, as per the IP range's netmask."); + if (endIP != null && !NetUtils.sameSubnet(endIP, vlanGateway, vlanNetmask)) { + throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as your IP range's gateway, as per the IP range's netmask."); + } } // check if the gatewayip is the part of the ip range being added. // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links @@ -6932,11 +6985,13 @@ private void checkPublicIpRangeErrors(final long zoneId, final String vlanId, fi // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1 // https://tools.ietf.org/html/rfc3021 // Added by Wilder Rodrigues - final String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask); - if (!NetUtils.is31PrefixCidr(newCidr)) { - if (NetUtils.ipRangesOverlap(startIP, endIP, vlanGateway, vlanGateway)) { - throw new InvalidParameterValueException( - "The gateway ip should not be the part of the ip range being added."); + if (vlanGateway != null) { + final String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask); + if (!NetUtils.is31PrefixCidr(newCidr)) { + if (NetUtils.ipRangesOverlap(startIP, endIP, vlanGateway, vlanGateway)) { + throw new InvalidParameterValueException( + "The gateway ip should not be the part of the ip range being added."); + } } } } @@ -7294,7 +7349,7 @@ public NetworkOffering createNetworkOffering(final NetworkOfferingBaseCmd cmd) { } if (guestType == null) { - throw new InvalidParameterValueException("Invalid \"type\" parameter is given; can have Shared and Isolated values"); + throw new InvalidParameterValueException("Invalid \"type\" parameter is given; supported values are " + Arrays.toString(Network.GuestType.values())); } if (internetProtocol != null) { @@ -7353,9 +7408,8 @@ public NetworkOffering createNetworkOffering(final NetworkOfferingBaseCmd cmd) { } if (service == Service.SecurityGroup) { - // allow security group service for Shared networks only - if (guestType != GuestType.Shared) { - throw new InvalidParameterValueException("Security group service is supported for network offerings with guest ip type " + GuestType.Shared); + if (guestType != GuestType.Shared && guestType != GuestType.L3) { + throw new InvalidParameterValueException(String.format("Security group service is supported for network offerings with guest ip type %s or %s", GuestType.Shared, GuestType.L3)); } final Set sgProviders = new HashSet<>(); sgProviders.add(Provider.SecurityGroupProvider); @@ -7451,6 +7505,10 @@ public NetworkOffering createNetworkOffering(final NetworkOfferingBaseCmd cmd) { // validate providers combination here _networkModel.canProviderSupportServices(providerCombinationToVerify); + if (guestType == GuestType.L3) { + validateL3NetworkOffering(serviceProviderMap, networkMode, specifyVlan, specifyIpRanges, forVpc); + } + // validate the LB service capabilities specified in the network // offering final Map lbServiceCapabilityMap = cmd.getServiceCapabilities(Service.Lb); @@ -7555,8 +7613,8 @@ public NetworkOffering createNetworkOffering(final NetworkOfferingBaseCmd cmd) { } private void validateNetworkOfferingMultiqueueParameters(Integer publicMultiqueueNumber, Integer privateMultiqueueNumber, GuestType guestType, boolean forVpc) { - if (guestType == GuestType.L2 && ObjectUtils.anyNotNull(publicMultiqueueNumber, privateMultiqueueNumber)) { - throw new InvalidParameterValueException("Multiqueue parameters cannot be specified for L2 network offerings."); + if ((guestType == GuestType.L2 || guestType == GuestType.L3) && ObjectUtils.anyNotNull(publicMultiqueueNumber, privateMultiqueueNumber)) { + throw new InvalidParameterValueException(String.format("Multiqueue parameters cannot be specified for %s network offerings.", guestType)); } if (publicMultiqueueNumber != null && forVpc) { @@ -7567,6 +7625,49 @@ private void validateNetworkOfferingMultiqueueParameters(Integer publicMultiqueu NetworkOrchestrationService.validateMultiqueueNumberParameter(privateMultiqueueNumber, ApiConstants.PRIVATE_MULTIQUEUE_NUMBER); } + /** + * Validates a network offering for the L3 (Direct Routed) guest type. There is no Virtual + * Router and no DHCP on these networks: the Instance learns its /32 (and /128) address, + * on-link gateway and routes exclusively from ConfigDrive. UserData via ConfigDrive is + * therefore mandatory. Dns is optional (a template may carry its own resolvers) but must be + * provided by ConfigDrive when present. SecurityGroup is the only other permitted service. + * specifyVlan is a free choice: with it the operator supplies the routed id (routed://<id>, + * naming the per-network bridge) at network creation via the vlan parameter; without it + * CloudStack allocates one from the ROUTED physical network's vnet range. + */ + protected void validateL3NetworkOffering(final Map> serviceProviderMap, final NetworkOffering.NetworkMode networkMode, + final boolean specifyVlan, final boolean specifyIpRanges, final Boolean forVpc) { + if (Boolean.TRUE.equals(forVpc)) { + throw new InvalidParameterValueException(String.format("VPC is not supported for network offerings with guest type %s", GuestType.L3)); + } + if (networkMode != null) { + throw new InvalidParameterValueException(String.format("Network mode can not be specified for network offerings with guest type %s", GuestType.L3)); + } + if (!specifyIpRanges) { + throw new InvalidParameterValueException(String.format("Network offerings with guest type %s must specify IP ranges", GuestType.L3)); + } + if (serviceProviderMap.containsKey(Service.Dhcp)) { + throw new InvalidParameterValueException(String.format("DHCP is not supported (and not needed) for network offerings with guest type %s; addressing is delivered via ConfigDrive", GuestType.L3)); + } + final Set allowedL3Services = new HashSet<>(Arrays.asList(Service.UserData, Service.Dns, Service.SecurityGroup)); + for (final Service service : serviceProviderMap.keySet()) { + if (!allowedL3Services.contains(service)) { + throw new InvalidParameterValueException(String.format("Service %s is not supported for network offerings with guest type %s; supported services are %s", + service.getName(), GuestType.L3, StringUtils.join(allowedL3Services.stream().map(Service::getName).toArray(), ", "))); + } + } + final Set configDriveOnly = Collections.singleton(Provider.ConfigDrive); + final Set userDataProviders = serviceProviderMap.get(Service.UserData); + if (!configDriveOnly.equals(userDataProviders)) { + throw new InvalidParameterValueException(String.format("UserData with provider %s is mandatory for network offerings with guest type %s; it is the only channel that carries the Instance's network configuration", + Provider.ConfigDrive.getName(), GuestType.L3)); + } + final Set dnsProviders = serviceProviderMap.get(Service.Dns); + if (dnsProviders != null && !configDriveOnly.equals(dnsProviders)) { + throw new InvalidParameterValueException(String.format("DNS on network offerings with guest type %s must use provider %s", GuestType.L3, Provider.ConfigDrive.getName())); + } + } + public static NetworkOffering.RoutingMode verifyRoutingMode(String routingModeString) { NetworkOffering.RoutingMode routingMode = null; if (routingModeString != null) { diff --git a/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java b/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java index b7a6846422fb..0f4e0e9de19b 100644 --- a/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java +++ b/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java @@ -2466,8 +2466,7 @@ public void allocateDirectIp(final NicProfile nic, final DataCenter dc, final Vi @Override public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientAddressCapacityException { //This method allocates direct ip for the Shared network in Advance zones - boolean ipv4 = false; - if (network.getGateway() != null) { + if (network.getGateway() != null || (GuestType.L3 == network.getGuestType() && network.getCidr() != null)) { if (nic.getIPv4Address() == null) { PublicIp ip = null; diff --git a/server/src/main/java/com/cloud/network/Ipv6AddressManagerImpl.java b/server/src/main/java/com/cloud/network/Ipv6AddressManagerImpl.java index ae91daba1d16..8f8784bf7181 100644 --- a/server/src/main/java/com/cloud/network/Ipv6AddressManagerImpl.java +++ b/server/src/main/java/com/cloud/network/Ipv6AddressManagerImpl.java @@ -218,7 +218,7 @@ protected boolean isIp6Taken(Network network, String requestedIpv6) { */ @Override public void setNicIp6Address(final NicProfile nic, final DataCenter dc, final Network network) throws InsufficientAddressCapacityException { - if (network.getIp6Gateway() != null) { + if (network.getIp6Gateway() != null || (Network.GuestType.L3 == network.getGuestType() && network.getIp6Cidr() != null)) { if (nic.getIPv6Address() == null) { logger.debug("Found IPv6 CIDR " + network.getIp6Cidr() + " for Network " + network); nic.setIPv6Cidr(network.getIp6Cidr()); diff --git a/server/src/main/java/com/cloud/network/NetworkModelImpl.java b/server/src/main/java/com/cloud/network/NetworkModelImpl.java index 4c5641c6e9ca..95d7c2d3a27d 100644 --- a/server/src/main/java/com/cloud/network/NetworkModelImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkModelImpl.java @@ -762,6 +762,12 @@ public Network getNetwork(long id) { return _networksDao.findById(id); } + /** + * A Shared network's IPv4 presence is its gateway; a gateway-less L3 network's is its cidr — + * when either is present, a free address must remain in the network's IPv4 pool. IPv6 needs + * no free-IP check: addresses are computed with EUI-64 from the subnet and the NIC MAC, so an + * IPv6-only network never runs out. + */ @Override public boolean canUseForDeploy(Network network) { if (network.getTrafficType() != TrafficType.Guest) { @@ -771,8 +777,8 @@ public boolean canUseForDeploy(Network network) { return true; // do not check free IPs if there is no service in the network } boolean hasFreeIps = true; - if (network.getGuestType() == GuestType.Shared) { - if (network.getGateway() != null) { + if (network.getGuestType() == GuestType.Shared || network.getGuestType() == GuestType.L3) { + if (network.getGateway() != null || (network.getGuestType() == GuestType.L3 && network.getCidr() != null)) { hasFreeIps = _ipAddressDao.countFreeIPsInNetwork(network.getId()) > 0; } if (!hasFreeIps) { @@ -3152,7 +3158,8 @@ public boolean checkSecurityGroupSupportForNetwork(Account account, DataCenter z if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkId); } - if (network.getGuestType() == Network.GuestType.Shared && isSecurityGroupSupportedInNetwork(network)) { + if ((network.getGuestType() == Network.GuestType.Shared || network.getGuestType() == Network.GuestType.L3) + && isSecurityGroupSupportedInNetwork(network)) { return true; } } diff --git a/server/src/main/java/com/cloud/network/NetworkServiceImpl.java b/server/src/main/java/com/cloud/network/NetworkServiceImpl.java index 1702cac1620d..2bc708ac7576 100644 --- a/server/src/main/java/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkServiceImpl.java @@ -904,6 +904,132 @@ public boolean stop() { protected NetworkServiceImpl() { } + /** + * An L3 (Direct Routed) network has no DHCP and no password/metadata service, so nothing in + * it depends on IPv4: each address family is optional, making IPv6-only networks possible. + * Gateways play no part at all — the Instance's gateway is always the shared link-local + * address, so none needs to be declared (or burnt in the subnet). What remains mandatory is + * that a given family is complete — IPv4 is a subnet (cidr, or netmask and startip; endip + * defaults to startip), IPv6 is ip6cidr alone (no range: addresses derive from the subnet + * and the NIC MAC with EUI-64) — and that at least one family is present at all. A cidr + * parameter has already been expanded into netmask and startip when this runs. + */ + protected void validateL3AddressFamilies(String netmask, String startIP, String endIP, + String ip6Cidr, String startIPv6, String endIPv6) { + boolean anyIpv4 = !StringUtils.isAllBlank(netmask, startIP, endIP); + boolean completeIpv4 = StringUtils.isNoneBlank(netmask, startIP); + boolean anyIpv6 = !StringUtils.isAllBlank(ip6Cidr, startIPv6, endIPv6); + boolean completeIpv6 = StringUtils.isNotBlank(ip6Cidr); + if (anyIpv4 && !completeIpv4) { + throw new InvalidParameterValueException(String.format( + "IPv4 is optional for %s networks, but when any IPv4 detail is given, either cidr, or netmask and startip, is required", GuestType.L3)); + } + if (anyIpv6 && !completeIpv6) { + throw new InvalidParameterValueException(String.format( + "IPv6 is optional for %s networks, but when any IPv6 detail is given, ip6cidr is required", GuestType.L3)); + } + if (!anyIpv4 && !anyIpv6) { + throw new InvalidParameterValueException(String.format( + "A %s network needs at least one address family: IPv4 (cidr, or netmask and startip) or IPv6 (ip6cidr)", GuestType.L3)); + } + } + + /** + * Expands the cidr parameter of an L3 network — the IPv4 counterpart of ip6cidr — into the + * netmask/startip/endip triple the rest of the creation flow works with. Without startip the + * IP range defaults to the subnet's usable addresses (network and broadcast excluded; give + * startip and endip explicitly to include them). An explicit startip/endip narrows the range + * and must lie inside the subnet, which is what keeps the network's stored subnet — derived + * from startip and netmask further down the flow — equal to the requested one. cidr and + * netmask are two ways of defining the same subnet, so they are mutually exclusive. + * + * @return {netmask, startIP, endIP} + */ + protected String[] expandL3Ipv4Cidr(String requestedCidr, String netmask, String startIP, String endIP) { + if (StringUtils.isNotBlank(netmask)) { + throw new InvalidParameterValueException("Specify either cidr or netmask, not both: they both define the IPv4 subnet"); + } + if (!NetUtils.isValidIp4Cidr(requestedCidr)) { + throw new InvalidParameterValueException(String.format("Invalid cidr %s", requestedCidr)); + } + if (StringUtils.isBlank(startIP) && StringUtils.isNotBlank(endIP)) { + throw new InvalidParameterValueException("endip requires startip"); + } + final Pair parsedCidr = NetUtils.getCidr(requestedCidr); + final String derivedNetmask = NetUtils.getCidrNetmask(parsedCidr.second()); + if (StringUtils.isBlank(startIP)) { + if (parsedCidr.second() > 30) { + throw new InvalidParameterValueException(String.format( + "A /%d subnet has no derivable IP range; give startip and endip explicitly", parsedCidr.second())); + } + final String[] range = NetUtils.getIpRangeFromCidr(parsedCidr.first(), parsedCidr.second()); + startIP = range[0]; + endIP = range[1]; + } else { + for (String ip : new String[] {startIP, endIP}) { + if (StringUtils.isBlank(ip)) { + continue; + } + if (!NetUtils.isValidIp4(ip) || !NetUtils.isIpWithInCidrRange(ip, requestedCidr)) { + throw new InvalidParameterValueException(String.format("IP address %s is not within the subnet %s", ip, requestedCidr)); + } + } + } + return new String[] {derivedNetmask, startIP, endIP}; + } + + /** + * Canonicalises the routed id given for an L3 network through the vlan parameter. The id + * names the network's bridge on every hypervisor and derives that bridge's MAC address, so it + * is a positive integer without leading zeros; the routed:// scheme may be given or omitted. + * + * @return the bare id, which the orchestrator encodes into the routed://<id> broadcast URI + */ + protected String canonicalizeRoutedId(String vlanId) { + String routedId = BroadcastDomainType.getRoutedId(vlanId); + if (routedId == null) { + throw new InvalidParameterValueException(String.format( + "The vlan parameter of a %s network is its routed id, a positive integer of at most %d digits (optionally prefixed with routed://), got %s", + GuestType.L3, BroadcastDomainType.ROUTED_ID_MAX_DIGITS, vlanId)); + } + return routedId; + } + + /** + * The L3 counterpart of {@code NetworkModel.checkIp6Parameters()}: no gateway is involved, + * and the range is optional — when given it must lie inside the subnet. + */ + protected void checkL3Ip6Parameters(String startIPv6, String endIPv6, String ip6Cidr) { + if (!NetUtils.isValidIp6Cidr(ip6Cidr)) { + throw new InvalidParameterValueException("Invalid ip6cidr"); + } + for (String ip : new String[] {startIPv6, endIPv6}) { + if (StringUtils.isBlank(ip)) { + continue; + } + if (!NetUtils.isValidIp6(ip)) { + throw new InvalidParameterValueException(String.format("Invalid IPv6 address %s", ip)); + } + if (!NetUtils.isIp6InNetwork(ip, ip6Cidr)) { + throw new InvalidParameterValueException(String.format("IPv6 address %s is not within the subnet %s", ip, ip6Cidr)); + } + } + } + + /** + * Whether the NIC sits on a Direct Routed (L3) network. Such a NIC needs the agent told about + * secondary IPs regardless of the zone's security group setting: the host route and neighbour + * entry the agent installs are what make the address reachable. + */ + protected boolean isDirectRoutedNic(long nicId) { + NicVO nic = _nicDao.findById(nicId); + if (nic == null) { + return false; + } + Network network = _networksDao.findById(nic.getNetworkId()); + return network != null && GuestType.L3.equals(network.getGuestType()); + } + @Override @ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_CONFIGURE, eventDescription = "Configuring secondary IP " + "rules", async = true) public boolean configureNicSecondaryIp(NicSecondaryIp secIp, boolean isZoneSgEnabled) { @@ -913,9 +1039,9 @@ public boolean configureNicSecondaryIp(NicSecondaryIp secIp, boolean isZoneSgEna secondaryIp = secIp.getIp6Address(); } - if (isZoneSgEnabled) { + if (isZoneSgEnabled || isDirectRoutedNic(secIp.getNicId())) { success = _securityGroupService.securityGroupRulesForVmSecIp(secIp.getNicId(), secondaryIp, true); - logger.info("Associated IP address to NIC : " + secIp.getIp4Address()); + logger.info("Associated IP address to NIC : " + secondaryIp); } else { success = true; } @@ -1789,7 +1915,7 @@ public NicSecondaryIp allocateSecondaryGuestIP(final long nicId, IpAddresses req if (StringUtils.isNotBlank(ipv6Address)) { ip6addr = ipv6AddrMgr.allocateGuestIpv6(network, ipv6Address); } - } else if (network.getGuestType() == Network.GuestType.Shared) { + } else if (network.getGuestType() == Network.GuestType.Shared || network.getGuestType() == Network.GuestType.L3) { //for basic zone, need to provide the podId to ensure proper IP allocation Long podId = null; DataCenter dc = _dcDao.findById(network.getDataCenterId()); @@ -2352,6 +2478,7 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac String startIP = cmd.getStartIp(); String endIP = cmd.getEndIp(); String netmask = cmd.getNetmask(); + final String requestedCidr = cmd.getCidr(); String networkDomain = cmd.getNetworkDomain(); boolean adminCalledUs = cmd instanceof CreateNetworkCmdByAdmin; @@ -2406,6 +2533,13 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac ACLType aclType = getAclType(caller, cmd.getAclType(), ntwkOff); + if (ntwkOff.getGuestType() == GuestType.L3 + && (pNtwk.getIsolationMethods() == null || !pNtwk.getIsolationMethods().contains("ROUTED"))) { + throw new InvalidParameterValueException(String.format( + "Networks of guest type %s can only be created on a physical network with isolation method ROUTED; physical network %s carries %s", + GuestType.L3, pNtwk.getName(), pNtwk.getIsolationMethods())); + } + if (ntwkOff.getGuestType() != GuestType.Shared && (!StringUtils.isAllBlank(routerIPv4, routerIPv6))) { throw new InvalidParameterValueException("Router IP can be specified only for Shared networks"); } @@ -2429,12 +2563,37 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac } } - boolean ipv4 = false, ipv6 = false; - if (org.apache.commons.lang3.StringUtils.isNoneBlank(gateway, netmask)) { - ipv4 = true; + final boolean isL3 = ntwkOff.getGuestType() == GuestType.L3; + if (!isL3 && StringUtils.isNotBlank(requestedCidr)) { + throw new InvalidParameterValueException(String.format( + "The cidr parameter is supported for %s networks only; use gateway and netmask instead", GuestType.L3)); + } + if (isL3) { + if (StringUtils.isNotBlank(requestedCidr)) { + String[] expanded = expandL3Ipv4Cidr(requestedCidr, netmask, startIP, endIP); + netmask = expanded[0]; + startIP = expanded[1]; + endIP = expanded[2]; + } + validateL3AddressFamilies(netmask, startIP, endIP, ip6Cidr, startIPv6, endIPv6); + if (!StringUtils.isAllBlank(gateway, ip6Gateway)) { + logger.debug("Ignoring the gateway(s) given for {} network {}: instances always use the shared link-local gateway", GuestType.L3, name); + gateway = null; + ip6Gateway = null; + } } - if (StringUtils.isNoneBlank(ip6Cidr, ip6Gateway)) { - ipv6 = true; + + boolean ipv4 = false, ipv6 = false; + if (isL3) { + ipv4 = StringUtils.isNoneBlank(netmask, startIP); + ipv6 = StringUtils.isNotBlank(ip6Cidr); + } else { + if (org.apache.commons.lang3.StringUtils.isNoneBlank(gateway, netmask)) { + ipv4 = true; + } + if (StringUtils.isNoneBlank(ip6Cidr, ip6Gateway)) { + ipv6 = true; + } } if (gateway != null) { @@ -2474,11 +2633,16 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac } else if (!NetUtils.isValidIp4(endIP)) { throw new InvalidParameterValueException("Invalid format for the endIp parameter"); } - if (!(gateway != null && netmask != null)) { + if (!(netmask != null && (gateway != null || isL3))) { throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in"); } } - if (gateway != null && netmask != null) { + if (isL3 && netmask != null && startIP != null) { + if (!NetUtils.isValidIp4Netmask(netmask)) { + throw new InvalidParameterValueException("Invalid netmask"); + } + cidr = NetUtils.getCidrFromGatewayAndNetmask(startIP, netmask); + } else if (gateway != null && netmask != null) { if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) { if (logger.isDebugEnabled()) { logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP."); @@ -2502,16 +2666,24 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac if (endIPv6 == null) { endIPv6 = startIPv6; } - _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr); - if (!GuestType.Shared.equals(ntwkOff.getGuestType())) { + if (isL3) { + checkL3Ip6Parameters(startIPv6, endIPv6, ip6Cidr); + } else { + _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr); + } + if (!GuestType.Shared.equals(ntwkOff.getGuestType()) && !GuestType.L3.equals(ntwkOff.getGuestType())) { _networkModel.checkIp6CidrSizeEqualTo64(ip6Cidr); } + if (GuestType.L3.equals(ntwkOff.getGuestType()) && NetUtils.getIp6CidrSize(ip6Cidr) > 64) { + throw new InvalidParameterValueException(String.format( + "The IPv6 subnet of a %s network must be /64 or larger: addresses are derived with EUI-64 from the subnet and the NIC MAC", GuestType.L3)); + } - if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared) { - throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!"); + if (zone.getNetworkType() != NetworkType.Advanced || (ntwkOff.getGuestType() != Network.GuestType.Shared && ntwkOff.getGuestType() != Network.GuestType.L3)) { + throw new InvalidParameterValueException(String.format("Can only support create IPv6 network with advanced %s or %s network!", GuestType.Shared, GuestType.L3)); } - if(StringUtils.isAllBlank(ip6Dns1, ip6Dns2, zone.getIp6Dns1(), zone.getIp6Dns2())) { + if (!isL3 && StringUtils.isAllBlank(ip6Dns1, ip6Dns2, zone.getIp6Dns1(), zone.getIp6Dns2())) { throw new InvalidParameterValueException("Can only create IPv6 network if the zone has IPv6 DNS! Please configure the zone IPv6 DNS1 and/or IPv6 DNS2."); } @@ -2547,7 +2719,7 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac if (!_accountMgr.isRootAdmin(caller.getId())) { throw new InvalidParameterValueException("Only ROOT admin is allowed to create Private VLAN network"); } - if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() == GuestType.Isolated) { + if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() == GuestType.Isolated || ntwkOff.getGuestType() == GuestType.L3) { throw new InvalidParameterValueException("Can only support create Private VLAN network with advanced shared or L2 network!"); } if (ipv6) { @@ -2570,9 +2742,12 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac } // Ignore vlanId if it is passed but specifyvlan=false in network offering - if (ntwkOff.getGuestType() == GuestType.Shared && ! ntwkOff.isSpecifyVlan() && vlanId != null) { + if ((ntwkOff.getGuestType() == GuestType.Shared || ntwkOff.getGuestType() == GuestType.L3) && ! ntwkOff.isSpecifyVlan() && vlanId != null) { throw new InvalidParameterValueException("Cannot specify vlanId when create a network from network offering with specifyvlan=false"); } + if (isL3 && vlanId != null) { + vlanId = canonicalizeRoutedId(vlanId); + } // Don't allow to specify vlan if the caller is not ROOT admin if (!_accountMgr.isRootAdmin(caller.getId()) && (ntwkOff.isSpecifyVlan() || vlanId != null || bypassVlanOverlapCheck)) { @@ -2626,9 +2801,8 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac } } - // Vlan is created in 1 cases - works in Advance zone only: - // 1) GuestType is Shared boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && ((ntwkOff.getGuestType() == Network.GuestType.Shared) + || (ntwkOff.getGuestType() == Network.GuestType.L3) || (ntwkOff.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); if (!createVlan) { @@ -2645,9 +2819,9 @@ public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapac - if (GuestType.Shared == ntwkOff.getGuestType()) { + if (GuestType.Shared == ntwkOff.getGuestType() || GuestType.L3 == ntwkOff.getGuestType()) { if (!ntwkOff.isSpecifyIpRanges()) { - throw new CloudRuntimeException("The 'specifyipranges' parameter should be true for Shared Networks"); + throw new CloudRuntimeException(String.format("The 'specifyipranges' parameter should be true for %s Networks", ntwkOff.getGuestType())); } if (ipv4 && Objects.isNull(startIP)) { throw new CloudRuntimeException("IPv4 address range needs to be provided"); @@ -2866,7 +3040,7 @@ private static ACLType getAclType(String aclTypeStr, NetworkOffering ntwkOff) { } private ACLType getAclType(Account caller, NetworkOffering ntwkOff, ACLType aclType) { - if (ntwkOff.getGuestType() == GuestType.Isolated || ntwkOff.getGuestType() == GuestType.L2) { + if (ntwkOff.getGuestType() == GuestType.Isolated || ntwkOff.getGuestType() == GuestType.L2 || ntwkOff.getGuestType() == GuestType.L3) { aclType = ACLType.Account; } else if (ntwkOff.getGuestType() == GuestType.Shared) { if (_accountMgr.isRootAdmin(caller.getId())) { @@ -3174,15 +3348,15 @@ public Network doInTransaction(TransactionStatus status) throws InsufficientCapa } String vlanId = vlanIdFinal; - if (createVlan && vlanId == null && ntwkOff.getGuestType() == Network.GuestType.Shared && ! ntwkOff.isSpecifyVlan()) { + if (createVlan && vlanId == null && (ntwkOff.getGuestType() == Network.GuestType.Shared || ntwkOff.getGuestType() == Network.GuestType.L3) + && ! ntwkOff.isSpecifyVlan()) { if (associatedNetwork != null) { // Get vlanId from associated network vlanId = associatedNetwork.getBroadcastUri().toString(); } else { - // Allocate a vnet to shared network with specifyvlan=false vlanId = _dcDao.allocateVnet(zoneId, physicalNetworkId, owner.getAccountId(), null, GuestNetworkGuru.UseSystemGuestVlans.valueIn(owner.getAccountId())); if (vlanId == null) { - throw new InvalidParameterValueException("Cannot allocate a vnet for this Shared network"); + throw new InvalidParameterValueException(String.format("Cannot allocate a vnet for this %s network", ntwkOff.getGuestType())); } } } diff --git a/server/src/main/java/com/cloud/network/guru/DirectRoutedNetworkGuru.java b/server/src/main/java/com/cloud/network/guru/DirectRoutedNetworkGuru.java new file mode 100644 index 000000000000..d6bf8f8da209 --- /dev/null +++ b/server/src/main/java/com/cloud/network/guru/DirectRoutedNetworkGuru.java @@ -0,0 +1,192 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.guru; + +import org.apache.commons.lang3.StringUtils; + +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.State; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.Mode; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetwork.IsolationMethod; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.offering.NetworkOffering; +import com.cloud.user.Account; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachineProfile; + +/** + * Network guru for L3 (Direct Routed) guest networks: the hypervisor routes a public IPv4 + * and/or IPv6 address directly to the Instance. There is no Virtual Router, no NAT and no + * DHCP; the Instance learns its addressing exclusively from ConfigDrive. + * + * Address allocation is inherited from {@link DirectNetworkGuru}: the operator supplies a + * subnet, CloudStack assigns individual addresses out of it. What differs is the form those + * addresses take on the NIC — an IPv4 address is a /32 and an IPv6 address a /128, with the + * shared, host-independent on-link gateway (169.254.0.1 / fe80::1) that every hypervisor + * carries on the network's bridge. + * + * These networks live on a dedicated physical network whose isolation method is ROUTED — the + * network operator's explicit, zone-level opt-in. Each network carries a broadcast domain of + * type routed://<id>; the id is a label naming the per-network, uplink-less bridge on every + * host (brdr-<id>), never an encapsulation. It is chosen by the operator at network creation + * (specifyVlan offerings, via the vlan parameter) or allocated from the physical network's vnet + * range (otherwise), and is stable for the network's life. + */ +public class DirectRoutedNetworkGuru extends DirectNetworkGuru { + + public DirectRoutedNetworkGuru() { + super(); + _isolationMethods = new IsolationMethod[] {new IsolationMethod("ROUTED")}; + } + + @Override + protected boolean canHandle(NetworkOffering offering, DataCenter dc, PhysicalNetwork physnet) { + if (dc.getNetworkType() == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == GuestType.L3 + && isMyIsolationMethod(physnet)) { + return true; + } + logger.trace("We only take care of {} guest networks in zones of type {} on physical networks with isolation method ROUTED", GuestType.L3, NetworkType.Advanced); + return false; + } + + /** + * Designs the network with {@code Mode.Static} (Instances are configured via ConfigDrive, + * there is no DHCP) and a {@code BroadcastDomainType.Routed} broadcast domain: routed://<id> + * names the per-network bridge (brdr-<id>), consuming no VLAN/VXLAN and nothing on the wire. + * The routed id — operator-specified or allocated from the physical network's vnet range — + * arrives as the broadcast URI, stamped by the orchestrator before design, and never changes: + * the bridge name derives from it. The IPv4/IPv6 subnets are allocation pools routed to the + * hypervisors, not broadcast domains, and carry no gateways of their own: the Instance's + * gateway is always the shared link-local address, so a subnet gateway would only burn an + * address. + */ + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, String name, Long vpcId, Account owner) { + DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); + + if (!canHandle(offering, dc, physnet)) { + return null; + } + + if (vpcId != null) { + throw new InvalidParameterValueException(String.format("%s networks are never part of a VPC", GuestType.L3)); + } + + NetworkVO config = new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.Routed, offering.getId(), State.Allocated, + plan.getDataCenterId(), plan.getPhysicalNetworkId(), false); + + if (userSpecified != null) { + if (userSpecified.getBroadcastUri() != null) { + if (BroadcastDomainType.getSchemeValue(userSpecified.getBroadcastUri()) != BroadcastDomainType.Routed) { + throw new InvalidParameterValueException(String.format("A %s network requires a routed:// broadcast domain, got %s", + GuestType.L3, userSpecified.getBroadcastUri())); + } + config.setBroadcastUri(userSpecified.getBroadcastUri()); + config.setState(State.Setup); + } + + if (userSpecified.getCidr() != null) { + config.setCidr(userSpecified.getCidr()); + config.setGateway(userSpecified.getGateway()); + } + + if (userSpecified.getIp6Cidr() != null) { + config.setIp6Cidr(userSpecified.getIp6Cidr()); + config.setIp6Gateway(userSpecified.getIp6Gateway()); + } + + if (userSpecified.getPublicMtu() != null) { + config.setPublicMtu(userSpecified.getPublicMtu()); + } + if (userSpecified.getPrivateMtu() != null) { + config.setPrivateMtu(userSpecified.getPrivateMtu()); + } + + if (StringUtils.isNotBlank(userSpecified.getDns1())) { + config.setDns1(userSpecified.getDns1()); + } + if (StringUtils.isNotBlank(userSpecified.getDns2())) { + config.setDns2(userSpecified.getDns2()); + } + if (StringUtils.isNotBlank(userSpecified.getIp6Dns1())) { + config.setIp6Dns1(userSpecified.getIp6Dns1()); + } + if (StringUtils.isNotBlank(userSpecified.getIp6Dns2())) { + config.setIp6Dns2(userSpecified.getIp6Dns2()); + } + } + + return config; + } + + @Override + public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapacityException, + InsufficientAddressCapacityException, ConcurrentOperationException { + NicProfile profile = super.allocate(network, nic, vm); + applyDirectRoutedAddressing(profile); + return profile; + } + + @Override + public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException { + super.reserve(nic, network, vm, dest, context); + applyDirectRoutedAddressing(nic); + } + + /** + * The inherited allocation ({@code IpAddressManagerImpl.allocateDirectIp()}) sets the NIC's + * gateway and netmask from the vlan row, as a Shared network needs. Here the address is a + * host route, not a subnet membership: force the /32 (or /128) form and the shared on-link + * gateway over whatever the vlan row provided. This is also the signature by which the KVM + * agent recognises a direct routed NIC. The inherited allocation likewise labels the NIC's + * isolation URI vlan://<tag> from the vlan row; there is no VLAN here — the only + * isolation-shaped fact about this NIC is its routed://<id> broadcast domain, so that + * replaces the isolation URI as well. + */ + protected void applyDirectRoutedAddressing(NicProfile nic) { + if (nic == null) { + return; + } + if (nic.getBroadCastUri() != null && BroadcastDomainType.getSchemeValue(nic.getBroadCastUri()) == BroadcastDomainType.Routed) { + nic.setIsolationUri(nic.getBroadCastUri()); + } + if (nic.getIPv4Address() != null) { + nic.setIPv4Netmask(NetUtils.IPV4_HOST_NETMASK); + nic.setIPv4Gateway(NetUtils.getLinkLocalGateway()); + } + if (nic.getIPv6Address() != null) { + nic.setIPv6Cidr(nic.getIPv6Address() + "/" + NetUtils.IPV6_HOST_PREFIX_LENGTH); + nic.setIPv6Gateway(NetUtils.getIpv6LinkLocalGateway()); + } + } +} diff --git a/server/src/main/java/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/main/java/com/cloud/network/guru/PublicNetworkGuru.java index b7e4f334622c..9d7caef43484 100644 --- a/server/src/main/java/com/cloud/network/guru/PublicNetworkGuru.java +++ b/server/src/main/java/com/cloud/network/guru/PublicNetworkGuru.java @@ -18,6 +18,8 @@ import javax.inject.Inject; +import org.apache.commons.lang3.StringUtils; + import com.cloud.dc.dao.VlanDetailsDao; import com.cloud.network.vpc.dao.VpcDao; import com.cloud.network.vpc.dao.VpcOfferingDao; @@ -57,11 +59,13 @@ import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; import com.cloud.vm.Nic.ReservationStrategy; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; +import com.googlecode.ipv6.IPv6Address; public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { @@ -134,6 +138,14 @@ protected PublicNetworkGuru() { super(); } + /** + * On a direct routed public range (SystemVMs on a ROUTED physical network) the address is a + * host route, not a subnet membership, and the NIC takes the same form as a guest NIC on a + * direct routed network: /32 with the shared on-link gateway, and the routed://<id> + * broadcast domain that names the bridge on the host. The MAC and format are set before the + * branch on the range type, because setRoutedRangeIpv6() derives the EUI-64 address from the + * MAC and upgrades the format to DualStack. + */ protected void getIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException { if (nic.getIPv4Address() == null) { @@ -145,7 +157,17 @@ protected void getIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Ne nic.setIPv4Address(ip.getAddress().toString()); nic.setIPv4Gateway(ip.getGateway()); nic.setIPv4Netmask(ip.getNetmask()); - if (network.getBroadcastDomainType() == BroadcastDomainType.Vxlan) { + nic.setFormat(AddressFormat.Ip4); + nic.setReservationId(String.valueOf(ip.getVlanTag())); + nic.setMacAddress(ip.getMacAddress()); + if (isRoutedRange(ip)) { + nic.setIPv4Netmask(NetUtils.IPV4_HOST_NETMASK); + nic.setIPv4Gateway(NetUtils.getLinkLocalGateway()); + nic.setIsolationUri(BroadcastDomainType.Routed.toUri(ip.getVlanTag())); + nic.setBroadcastUri(BroadcastDomainType.Routed.toUri(ip.getVlanTag())); + nic.setBroadcastType(BroadcastDomainType.Routed); + setRoutedRangeIpv6(nic, dc, ip, network); + } else if (network.getBroadcastDomainType() == BroadcastDomainType.Vxlan) { nic.setIsolationUri(BroadcastDomainType.Vxlan.toUri(ip.getVlanTag())); nic.setBroadcastUri(BroadcastDomainType.Vxlan.toUri(ip.getVlanTag())); nic.setBroadcastType(BroadcastDomainType.Vxlan); @@ -154,9 +176,6 @@ protected void getIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Ne nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag())); nic.setBroadcastType(BroadcastDomainType.Vlan); } - nic.setFormat(AddressFormat.Ip4); - nic.setReservationId(String.valueOf(ip.getVlanTag())); - nic.setMacAddress(ip.getMacAddress()); } Pair dns = networkModel.getNetworkIp4Dns(network, dc); @@ -166,6 +185,41 @@ protected void getIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Ne ipv6Service.updateNicIpv6(nic, dc, network); } + /** + * A public IP range on a ROUTED physical network is created with routed:// as its "vlan"; + * the tag flowing through the vlan row is what marks the addresses it holds as direct routed. + */ + private boolean isRoutedRange(PublicIp ip) { + String vlanTag = ip.getVlanTag(); + return vlanTag != null && vlanTag.startsWith(BroadcastDomainType.Routed.scheme() + "://"); + } + + /** + * IPv6 on a direct routed public range is computed with EUI-64 from the range's subnet and + * the NIC's MAC — the same stateless model guest NICs use (no pool, no reservation, only the + * result on the NIC) — and takes host-route form: a /128 with the shared link-local gateway. + * + * Deliberately not {@code ipv6Service.updateNicIpv6()}: that path is gated on the public + * network offering's internet protocol, and its per-network placeholder reservation would + * hand every SystemVM on the shared Public network the same address. Neither the gate nor + * the reservation has anything to decide here — the MAC makes the address unique. + */ + private void setRoutedRangeIpv6(NicProfile nic, DataCenter dc, PublicIp ip, Network network) { + String ip6Cidr = ip.vlan() != null ? ip.vlan().getIp6Cidr() : null; + if (StringUtils.isBlank(ip6Cidr) || nic.getIPv6Address() != null) { + return; + } + IPv6Address ipv6Address = NetUtils.EUI64Address(ip6Cidr, nic.getMacAddress()); + logger.info("Calculated IPv6 address {} using EUI-64 for direct routed public NIC {}", ipv6Address, nic); + nic.setIPv6Address(ipv6Address.toString()); + nic.setIPv6Cidr(ipv6Address + "/" + NetUtils.IPV6_HOST_PREFIX_LENGTH); + nic.setIPv6Gateway(NetUtils.getIpv6LinkLocalGateway()); + nic.setFormat(AddressFormat.DualStack); + Pair ip6Dns = networkModel.getNetworkIp6Dns(network, dc); + nic.setIPv6Dns1(ip6Dns.first()); + nic.setIPv6Dns2(ip6Dns.second()); + } + @Override public void updateNicProfile(NicProfile profile, Network network) { DataCenter dc = _dcDao.findById(network.getDataCenterId()); diff --git a/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java index df8cb79f8723..28c41ce38689 100644 --- a/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -1451,18 +1451,26 @@ public boolean securityGroupRulesForVmSecIp(long nicId, String secondaryIp, bool // Verify permissions _accountMgr.checkAccess(caller, null, false, vm); + Network network = _networkModel.getNetwork(nic.getNetworkId()); + if (network == null) { + throw new InvalidParameterValueException(String.format("Unable to find the network of NIC %s", nic)); + } + + boolean directRouted = Network.GuestType.L3.equals(network.getGuestType()); + // Validate parameters List vmSgGrps = getSecurityGroupsForVm(vmId); + boolean applySecurityGroupRules = true; if (vmSgGrps.isEmpty()) { logger.debug("Vm is not in any Security group "); - return true; - } - - //If network does not support SG service, no need add SG rules for secondary ip - Network network = _networkModel.getNetwork(nic.getNetworkId()); - if (!_networkModel.isSecurityGroupSupportedInNetwork(network)) { + applySecurityGroupRules = false; + } else if (!_networkModel.isSecurityGroupSupportedInNetwork(network)) { logger.debug("Network " + network + " is not enabled with security group service, "+ "so not applying SG rules for secondary ip"); + applySecurityGroupRules = false; + } + + if (!applySecurityGroupRules && !directRouted) { return true; } @@ -1473,7 +1481,8 @@ public boolean securityGroupRulesForVmSecIp(long nicId, String secondaryIp, bool } //create command for the to add ip in ipset and arptables rules - NetworkRulesVmSecondaryIpCommand cmd = new NetworkRulesVmSecondaryIpCommand(vmName, vmMac, secondaryIp, ruleAction); + NetworkRulesVmSecondaryIpCommand cmd = new NetworkRulesVmSecondaryIpCommand(vmName, vmMac, secondaryIp, ruleAction, + directRouted, applySecurityGroupRules); logger.debug("Asking agent to configure rules for vm secondary ip"); Commands cmds = null; diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index b2e20256cc53..f2e49a1b26be 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -2022,7 +2022,7 @@ public void doInTransactionWithoutResult(TransactionStatus status) { return null; } } else { - throw new InvalidParameterValueException("UpdateVmNicIpCmd is not supported in L2 network"); + throw new InvalidParameterValueException(String.format("UpdateVmNicIpCmd is not supported in %s networks", network.getGuestType())); } logger.debug("Updating IPv4 address of NIC " + nicVO + " to " + ipaddr + "/" + nicVO.getIPv4Netmask() + " with gateway " + nicVO.getIPv4Gateway()); diff --git a/server/src/main/resources/META-INF/cloudstack/server-network/spring-server-network-context.xml b/server/src/main/resources/META-INF/cloudstack/server-network/spring-server-network-context.xml index 97ed36e515c7..f3d518cd185c 100644 --- a/server/src/main/resources/META-INF/cloudstack/server-network/spring-server-network-context.xml +++ b/server/src/main/resources/META-INF/cloudstack/server-network/spring-server-network-context.xml @@ -48,6 +48,9 @@ + + + diff --git a/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java b/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java index 75f44dbbef76..177b57d89a87 100644 --- a/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java +++ b/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java @@ -35,6 +35,10 @@ import com.cloud.network.Networks; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetrisProviderDao; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.dc.DataCenterVnetVO; import com.cloud.network.dao.NsxProviderDao; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.element.NsxProviderVO; @@ -170,6 +174,8 @@ public class ConfigurationManagerImplTest { @Mock PhysicalNetworkDao physicalNetworkDao; @Mock + NetworkDao networkDao; + @Mock ImageStoreDao imageStoreDao; @Mock VlanDao vlanDao; @@ -1551,4 +1557,120 @@ public void validateRouterNicMultiqueueNumberConfigValueTestRejectsInvalidValues public void validateSpecificConfigurationValuesTestValidatesRouterNicMultiqueueNumber() { configurationManagerImplSpy.validateSpecificConfigurationValues(NetworkOrchestrationService.RouterNicMultiqueueNumber.key(), "0", Integer.class); } + + private Map> validL3ServiceProviderMap() { + Map> map = new HashMap<>(); + map.put(Network.Service.UserData, Collections.singleton(Network.Provider.ConfigDrive)); + map.put(Network.Service.Dns, Collections.singleton(Network.Provider.ConfigDrive)); + map.put(Network.Service.SecurityGroup, Collections.singleton(Network.Provider.SecurityGroupProvider)); + return map; + } + + @Test + public void validateL3NetworkOfferingAcceptsUserDataDnsAndSecurityGroup() { + configurationManagerImplSpy.validateL3NetworkOffering(validL3ServiceProviderMap(), null, false, true, false); + } + + @Test + public void validateL3NetworkOfferingAcceptsOfferingWithoutDns() { + Map> map = validL3ServiceProviderMap(); + map.remove(Network.Service.Dns); + configurationManagerImplSpy.validateL3NetworkOffering(map, null, false, true, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsDhcp() { + Map> map = validL3ServiceProviderMap(); + map.put(Network.Service.Dhcp, Collections.singleton(Network.Provider.ConfigDrive)); + configurationManagerImplSpy.validateL3NetworkOffering(map, null, false, true, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsMissingUserData() { + Map> map = validL3ServiceProviderMap(); + map.remove(Network.Service.UserData); + configurationManagerImplSpy.validateL3NetworkOffering(map, null, false, true, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsUserDataWithoutProvider() { + Map> map = validL3ServiceProviderMap(); + map.put(Network.Service.UserData, Collections.emptySet()); + configurationManagerImplSpy.validateL3NetworkOffering(map, null, false, true, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsNonConfigDriveDns() { + Map> map = validL3ServiceProviderMap(); + map.put(Network.Service.Dns, Collections.singleton(Network.Provider.VirtualRouter)); + configurationManagerImplSpy.validateL3NetworkOffering(map, null, false, true, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsUnsupportedService() { + Map> map = validL3ServiceProviderMap(); + map.put(Network.Service.SourceNat, Collections.singleton(Network.Provider.VirtualRouter)); + configurationManagerImplSpy.validateL3NetworkOffering(map, null, false, true, false); + } + + private PhysicalNetworkVO routedPhysicalNetwork(long id) { + PhysicalNetworkVO physicalNetwork = Mockito.mock(PhysicalNetworkVO.class); + Mockito.when(physicalNetwork.getId()).thenReturn(id); + Mockito.when(physicalNetwork.getName()).thenReturn("routed-physnet"); + Mockito.when(physicalNetwork.getIsolationMethods()).thenReturn(List.of("ROUTED")); + return physicalNetwork; + } + + @Test + public void canonicalizeRoutedRangeIdAcceptsFreeId() { + PhysicalNetworkVO routedPhysicalNetwork = routedPhysicalNetwork(7L); + Mockito.when(networkDao.listByZoneAndUriAndGuestType(1L, "routed://5828", null)).thenReturn(Collections.emptyList()); + Mockito.when(physicalNetworkDao.listByZone(1L)).thenReturn(List.of(routedPhysicalNetwork)); + Mockito.when(zoneDao.findVnet(1L, 7L, "5828")).thenReturn(Collections.emptyList()); + + Assert.assertEquals("routed://5828", configurationManagerImplSpy.canonicalizeRoutedRangeId(1L, "routed://5828")); + } + + @Test(expected = InvalidParameterValueException.class) + public void canonicalizeRoutedRangeIdRejectsMalformedId() { + configurationManagerImplSpy.canonicalizeRoutedRangeId(1L, "routed://abc"); + } + + @Test(expected = InvalidParameterValueException.class) + public void canonicalizeRoutedRangeIdRejectsIdOfGuestNetwork() { + NetworkVO guestNetwork = Mockito.mock(NetworkVO.class); + Mockito.when(networkDao.listByZoneAndUriAndGuestType(1L, "routed://5828", null)).thenReturn(List.of(guestNetwork)); + + configurationManagerImplSpy.canonicalizeRoutedRangeId(1L, "routed://5828"); + } + + @Test(expected = InvalidParameterValueException.class) + public void canonicalizeRoutedRangeIdRejectsIdInsideRoutedPhysicalNetworkRange() { + PhysicalNetworkVO routedPhysicalNetwork = routedPhysicalNetwork(7L); + Mockito.when(networkDao.listByZoneAndUriAndGuestType(1L, "routed://5828", null)).thenReturn(Collections.emptyList()); + Mockito.when(physicalNetworkDao.listByZone(1L)).thenReturn(List.of(routedPhysicalNetwork)); + Mockito.when(zoneDao.findVnet(1L, 7L, "5828")).thenReturn(List.of(new DataCenterVnetVO("5828", 1L, 7L))); + + configurationManagerImplSpy.canonicalizeRoutedRangeId(1L, "routed://5828"); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsNetworkMode() { + configurationManagerImplSpy.validateL3NetworkOffering(validL3ServiceProviderMap(), NetworkOffering.NetworkMode.ROUTED, false, true, false); + } + + @Test + public void validateL3NetworkOfferingAcceptsSpecifyVlan() { + configurationManagerImplSpy.validateL3NetworkOffering(validL3ServiceProviderMap(), null, true, true, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsWithoutSpecifyIpRanges() { + configurationManagerImplSpy.validateL3NetworkOffering(validL3ServiceProviderMap(), null, false, false, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3NetworkOfferingRejectsVpc() { + configurationManagerImplSpy.validateL3NetworkOffering(validL3ServiceProviderMap(), null, false, true, true); + } } diff --git a/server/src/test/java/com/cloud/network/NetworkModelImplTest.java b/server/src/test/java/com/cloud/network/NetworkModelImplTest.java index 6e84253ffe7c..b393ed97f236 100644 --- a/server/src/test/java/com/cloud/network/NetworkModelImplTest.java +++ b/server/src/test/java/com/cloud/network/NetworkModelImplTest.java @@ -102,6 +102,8 @@ public class NetworkModelImplTest { @Mock private VpcDao vpcDao; @Mock + private com.cloud.network.dao.IPAddressDao _ipAddressDao; + @Mock private NetworkDao _networksDao; @Inject private NetworkOfferingServiceMapDao networkOfferingServiceMapDao; @@ -798,4 +800,64 @@ public void getNicAndIpInNetworkReturnsNullWhenVmHasNoNicInNetworkAtAll() { assertNull(networkModel.getNicAndIpInNetwork(5L, 207L)); } + + private boolean checkSecurityGroupSupportFor(Network.GuestType guestType, boolean sgSupportedInNetwork) { + DataCenter zone = mock(DataCenter.class); + when(zone.isSecurityGroupEnabled()).thenReturn(false); + NetworkVO network = mock(NetworkVO.class); + when(network.getGuestType()).thenReturn(guestType); + when(_networksDao.findById(42L)).thenReturn(network); + doReturn(sgSupportedInNetwork).when(networkModel).isSecurityGroupSupportedInNetwork(network); + return networkModel.checkSecurityGroupSupportForNetwork(mock(com.cloud.user.Account.class), zone, List.of(42L), null); + } + + private NetworkVO l3NetworkForDeploy(String cidr) { + NetworkVO network = mock(NetworkVO.class); + when(network.getTrafficType()).thenReturn(com.cloud.network.Networks.TrafficType.Guest); + when(network.getGuestType()).thenReturn(Network.GuestType.L3); + Mockito.lenient().when(network.getGateway()).thenReturn(null); + Mockito.lenient().when(network.getCidr()).thenReturn(cidr); + doReturn(List.of(Network.Service.UserData)).when(networkModel).listNetworkOfferingServices(Mockito.anyLong()); + return network; + } + + /** + * Regression: an IPv6-only L3 network has no IPv4 cidr, which the Isolated-style branch of + * canUseForDeploy() treated as unusable - hiding the network from the deploy wizard. IPv6 + * needs no free-IP check at all: addresses are EUI-64 computed and never run out. + */ + @Test + public void canUseForDeployAcceptsIpv6OnlyL3Network() { + assertTrue(networkModel.canUseForDeploy(l3NetworkForDeploy(null))); + } + + @Test + public void canUseForDeployChecksIpv4PoolOfGatewaylessL3Network() { + NetworkVO network = l3NetworkForDeploy("203.0.113.0/24"); + when(_ipAddressDao.countFreeIPsInNetwork(Mockito.anyLong())).thenReturn(0L); + assertFalse(networkModel.canUseForDeploy(network)); + when(_ipAddressDao.countFreeIPsInNetwork(Mockito.anyLong())).thenReturn(5L); + assertTrue(networkModel.canUseForDeploy(network)); + } + + @Test + public void checkSecurityGroupSupportForNetworkAcceptsSharedNetworkWithSecurityGroupService() { + assertTrue(checkSecurityGroupSupportFor(Network.GuestType.Shared, true)); + } + + /** + * Regression: deploying with securitygroupids into an L3 (Direct Routed) network failed with + * "security group feature is not enabled per zone" because the guest-type check accepted + * only Shared, while L3 offerings carry the SecurityGroup service per network. + */ + @Test + public void checkSecurityGroupSupportForNetworkAcceptsL3NetworkWithSecurityGroupService() { + assertTrue(checkSecurityGroupSupportFor(Network.GuestType.L3, true)); + } + + @Test + public void checkSecurityGroupSupportForNetworkRejectsNetworkWithoutSecurityGroupService() { + assertFalse(checkSecurityGroupSupportFor(Network.GuestType.L3, false)); + assertFalse(checkSecurityGroupSupportFor(Network.GuestType.Isolated, true)); + } } diff --git a/server/src/test/java/com/cloud/network/NetworkServiceImplTest.java b/server/src/test/java/com/cloud/network/NetworkServiceImplTest.java index 406223904b35..a3cc39b76512 100644 --- a/server/src/test/java/com/cloud/network/NetworkServiceImplTest.java +++ b/server/src/test/java/com/cloud/network/NetworkServiceImplTest.java @@ -2596,4 +2596,133 @@ public void trunkNicCommandsLogStartedAndCompletedEvents() throws NoSuchMethodEx assertAsyncActionEvent("disassociateNetworkFromNic", DisassociateNetworkFromNicCmd.class, EventTypes.EVENT_NIC_NETWORK_DISASSOCIATE); assertAsyncActionEvent("changeNicPrimaryNetwork", ChangeNicPrimaryNetworkCmd.class, EventTypes.EVENT_NIC_PRIMARY_NETWORK_CHANGE); } + + @Test + public void validateL3AddressFamiliesAcceptsDualStackWithoutGateways() { + service.validateL3AddressFamilies("255.255.255.0", "10.1.1.10", "10.1.1.20", "fd00::/64", null, null); + } + + @Test + public void validateL3AddressFamiliesAcceptsIpv4Only() { + service.validateL3AddressFamilies("255.255.255.0", "10.1.1.10", null, null, null, null); + } + + @Test + public void validateL3AddressFamiliesAcceptsIpv6CidrAlone() { + service.validateL3AddressFamilies(null, null, null, "fd00::/64", null, null); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3AddressFamiliesRejectsNetmaskWithoutStartIp() { + service.validateL3AddressFamilies("255.255.255.0", null, null, "fd00::/64", null, null); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3AddressFamiliesRejectsStartIpWithoutNetmask() { + service.validateL3AddressFamilies(null, "10.1.1.10", null, "fd00::/64", null, null); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3AddressFamiliesRejectsIpv6RangeWithoutCidr() { + service.validateL3AddressFamilies(null, null, null, null, "fd00::100", "fd00::200"); + } + + @Test + public void expandL3Ipv4CidrDerivesRangeFromSubnet() { + String[] expanded = service.expandL3Ipv4Cidr("192.0.2.0/24", null, null, null); + Assert.assertArrayEquals(new String[] {"255.255.255.0", "192.0.2.1", "192.0.2.254"}, expanded); + } + + @Test + public void expandL3Ipv4CidrKeepsExplicitRangeInsideSubnet() { + String[] expanded = service.expandL3Ipv4Cidr("192.0.2.0/24", null, "192.0.2.0", "192.0.2.255"); + Assert.assertArrayEquals(new String[] {"255.255.255.0", "192.0.2.0", "192.0.2.255"}, expanded); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsStartIpOutsideSubnet() { + service.expandL3Ipv4Cidr("192.0.2.0/24", null, "198.51.100.7", null); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsEndIpOutsideSubnet() { + service.expandL3Ipv4Cidr("192.0.2.0/24", null, "192.0.2.10", "192.0.3.10"); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsEndIpWithoutStartIp() { + service.expandL3Ipv4Cidr("192.0.2.0/24", null, null, "192.0.2.10"); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsCidrTogetherWithNetmask() { + service.expandL3Ipv4Cidr("192.0.2.0/24", "255.255.255.0", null, null); + } + + @Test + public void canonicalizeRoutedIdStripsScheme() { + Assert.assertEquals("5828", service.canonicalizeRoutedId("routed://5828")); + Assert.assertEquals("5828", service.canonicalizeRoutedId("5828")); + } + + @Test(expected = InvalidParameterValueException.class) + public void canonicalizeRoutedIdRejectsNonNumericId() { + service.canonicalizeRoutedId("routed://abc"); + } + + @Test + public void expandL3Ipv4CidrDerivesNetmaskAndUsableRange() { + String[] expanded = service.expandL3Ipv4Cidr("2.57.59.0/24", null, null, null); + Assert.assertEquals("255.255.255.0", expanded[0]); + Assert.assertEquals("2.57.59.1", expanded[1]); + Assert.assertEquals("2.57.59.254", expanded[2]); + } + + @Test + public void expandL3Ipv4CidrKeepsExplicitRange() { + String[] expanded = service.expandL3Ipv4Cidr("2.57.59.0/24", null, "2.57.59.10", "2.57.59.20"); + Assert.assertEquals("255.255.255.0", expanded[0]); + Assert.assertEquals("2.57.59.10", expanded[1]); + Assert.assertEquals("2.57.59.20", expanded[2]); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsNetmaskAlongside() { + service.expandL3Ipv4Cidr("2.57.59.0/24", "255.255.255.0", null, null); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsInvalidCidr() { + service.expandL3Ipv4Cidr("2.57.59.0/33", null, null, null); + } + + @Test(expected = InvalidParameterValueException.class) + public void expandL3Ipv4CidrRejectsTinySubnetWithoutExplicitRange() { + service.expandL3Ipv4Cidr("2.57.59.0/31", null, null, null); + } + + @Test + public void checkL3Ip6ParametersAcceptsCidrAlone() { + service.checkL3Ip6Parameters(null, null, "fd00::/64"); + } + + @Test + public void checkL3Ip6ParametersAcceptsRangeInsideCidr() { + service.checkL3Ip6Parameters("fd00::100", "fd00::200", "fd00::/64"); + } + + @Test(expected = InvalidParameterValueException.class) + public void checkL3Ip6ParametersRejectsRangeOutsideCidr() { + service.checkL3Ip6Parameters("fd00:1::100", null, "fd00::/64"); + } + + @Test(expected = InvalidParameterValueException.class) + public void checkL3Ip6ParametersRejectsInvalidCidr() { + service.checkL3Ip6Parameters(null, null, "not-a-cidr"); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateL3AddressFamiliesRejectsNoFamilyAtAll() { + service.validateL3AddressFamilies(null, null, null, null, null, null); + } } diff --git a/server/src/test/java/com/cloud/network/guru/DirectRoutedNetworkGuruTest.java b/server/src/test/java/com/cloud/network/guru/DirectRoutedNetworkGuruTest.java new file mode 100644 index 000000000000..07ab289110c2 --- /dev/null +++ b/server/src/test/java/com/cloud/network/guru/DirectRoutedNetworkGuruTest.java @@ -0,0 +1,197 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.guru; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.Mode; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.offering.NetworkOffering; +import com.cloud.user.Account; +import com.cloud.vm.NicProfile; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class DirectRoutedNetworkGuruTest { + + @InjectMocks + protected DirectRoutedNetworkGuru guru = new DirectRoutedNetworkGuru(); + + @Mock + DataCenterDao dcDao; + @Mock + PhysicalNetworkDao physicalNetworkDao; + + @Mock + NetworkOffering offering; + @Mock + DataCenterVO dc; + @Mock + PhysicalNetworkVO physicalNetwork; + @Mock + DeploymentPlan plan; + @Mock + Account owner; + + @Before + public void setUp() { + lenient().when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); + lenient().when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + lenient().when(offering.getGuestType()).thenReturn(GuestType.L3); + lenient().when(physicalNetwork.getIsolationMethods()).thenReturn(Arrays.asList("ROUTED")); + lenient().when(plan.getDataCenterId()).thenReturn(1L); + lenient().when(plan.getPhysicalNetworkId()).thenReturn(1L); + lenient().when(dcDao.findById(1L)).thenReturn(dc); + lenient().when(physicalNetworkDao.findById(1L)).thenReturn(physicalNetwork); + } + + @Test + public void canHandleAcceptsL3OnRoutedPhysicalNetwork() { + assertTrue(guru.canHandle(offering, dc, physicalNetwork)); + } + + @Test + public void canHandleRejectsBasicZone() { + when(dc.getNetworkType()).thenReturn(NetworkType.Basic); + assertFalse(guru.canHandle(offering, dc, physicalNetwork)); + } + + @Test + public void canHandleRejectsOtherGuestTypes() { + for (GuestType type : new GuestType[] {GuestType.Shared, GuestType.Isolated, GuestType.L2}) { + when(offering.getGuestType()).thenReturn(type); + assertFalse("guru must not claim guest type " + type, guru.canHandle(offering, dc, physicalNetwork)); + } + } + + @Test + public void canHandleRejectsPhysicalNetworkWithoutRoutedIsolation() { + for (List methods : Arrays.asList(Arrays.asList("VLAN"), Arrays.asList("VXLAN"), Collections.emptyList())) { + when(physicalNetwork.getIsolationMethods()).thenReturn(methods); + assertFalse("guru must not claim a physical network with isolation methods " + methods, guru.canHandle(offering, dc, physicalNetwork)); + } + } + + @Test + public void designProducesRoutedStaticNetwork() { + Network network = guru.design(offering, plan, null, "test", null, owner); + assertNotNull(network); + NetworkVO config = (NetworkVO)network; + assertEquals(BroadcastDomainType.Routed, config.getBroadcastDomainType()); + assertEquals(Mode.Static, config.getMode()); + assertNull(config.getBroadcastUri()); + } + + @Test + public void designCarriesRoutedBroadcastUri() throws URISyntaxException { + Network userSpecified = mock(Network.class); + when(userSpecified.getBroadcastUri()).thenReturn(new URI("routed://5828")); + + Network network = guru.design(offering, plan, userSpecified, "test", null, owner); + assertNotNull(network); + NetworkVO config = (NetworkVO)network; + assertEquals(BroadcastDomainType.Routed, config.getBroadcastDomainType()); + assertEquals("routed://5828", config.getBroadcastUri().toString()); + assertEquals(Network.State.Setup, config.getState()); + } + + @Test(expected = InvalidParameterValueException.class) + public void designRejectsNonRoutedBroadcastUri() throws URISyntaxException { + Network userSpecified = mock(Network.class); + when(userSpecified.getBroadcastUri()).thenReturn(new URI("vlan://5828")); + guru.design(offering, plan, userSpecified, "test", null, owner); + } + + @Test(expected = InvalidParameterValueException.class) + public void designRejectsVpc() { + guru.design(offering, plan, null, "test", 42L, owner); + } + + @Test + public void designReturnsNullForOtherGuestTypes() { + when(offering.getGuestType()).thenReturn(GuestType.Shared); + assertNull(guru.design(offering, plan, null, "test", null, owner)); + } + + @Test + public void applyDirectRoutedAddressingForcesHostRouteForm() { + NicProfile nic = new NicProfile(); + nic.setIPv4Address("203.0.113.55"); + nic.setIPv4Netmask("255.255.255.0"); + nic.setIPv4Gateway("203.0.113.1"); + nic.setIPv6Address("2001:db8:1::55"); + nic.setIPv6Cidr("2001:db8:1::/64"); + nic.setIPv6Gateway("2001:db8:1::1"); + + guru.applyDirectRoutedAddressing(nic); + + assertEquals("255.255.255.255", nic.getIPv4Netmask()); + assertEquals("169.254.0.1", nic.getIPv4Gateway()); + assertEquals("2001:db8:1::55/128", nic.getIPv6Cidr()); + assertEquals("fe80::1", nic.getIPv6Gateway()); + } + + @Test + public void applyDirectRoutedAddressingLeavesAbsentFamiliesAlone() { + NicProfile nic = new NicProfile(); + nic.setIPv4Address("203.0.113.55"); + nic.setIPv4Netmask("255.255.255.0"); + nic.setIPv4Gateway("203.0.113.1"); + + guru.applyDirectRoutedAddressing(nic); + + assertEquals("255.255.255.255", nic.getIPv4Netmask()); + assertEquals("169.254.0.1", nic.getIPv4Gateway()); + assertNull(nic.getIPv6Cidr()); + assertNull(nic.getIPv6Gateway()); + } + + @Test + public void applyDirectRoutedAddressingIsNullSafe() { + guru.applyDirectRoutedAddressing(null); + } +} diff --git a/server/src/test/java/com/cloud/network/guru/PublicNetworkGuruTest.java b/server/src/test/java/com/cloud/network/guru/PublicNetworkGuruTest.java new file mode 100644 index 000000000000..e71169faa691 --- /dev/null +++ b/server/src/test/java/com/cloud/network/guru/PublicNetworkGuruTest.java @@ -0,0 +1,135 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.guru; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.dc.DataCenter; +import com.cloud.dc.Vlan.VlanType; +import com.cloud.dc.VlanVO; +import com.cloud.network.IpAddressManager; +import com.cloud.network.Ipv6Service; +import com.cloud.network.Network; +import com.cloud.network.NetworkModel; +import com.cloud.network.Networks.AddressFormat; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.addr.PublicIp; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.user.Account; +import com.cloud.utils.Pair; +import com.cloud.utils.net.Ip; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.Nic.ReservationStrategy; +import com.cloud.vm.NicProfile; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class PublicNetworkGuruTest { + + @InjectMocks + protected PublicNetworkGuru guru = new PublicNetworkGuru(); + + @Mock + IpAddressManager ipAddrMgr; + @Mock + Ipv6Service ipv6Service; + @Mock + NetworkModel networkModel; + + @Mock + DataCenter dc; + @Mock + Network network; + @Mock + VirtualMachineProfile vm; + @Mock + Account owner; + + private static final long MAC = 0x1e003c000102L; + + @Before + public void setUp() { + lenient().when(vm.getType()).thenReturn(VirtualMachine.Type.ConsoleProxy); + lenient().when(vm.getOwner()).thenReturn(owner); + lenient().when(networkModel.getNetworkIp4Dns(network, dc)).thenReturn(new Pair<>(null, null)); + lenient().when(networkModel.getNetworkIp6Dns(network, dc)).thenReturn(new Pair<>(null, null)); + } + + private PublicIp publicIp(String vlanTag, String ip6Cidr) { + IPAddressVO addr = new IPAddressVO(new Ip("2.57.59.68"), 1L, 5L, 1L, false); + VlanVO vlan = new VlanVO(VlanType.VirtualNetwork, vlanTag, "2.57.59.65", "255.255.255.192", 1L, + "2.57.59.66-2.57.59.94", 200L, 200L, ip6Cidr == null ? null : "2a00:f10:402:2::1", ip6Cidr, null); + return new PublicIp(addr, vlan, MAC); + } + + private NicProfile allocateOn(PublicIp ip) throws Exception { + when(ipAddrMgr.assignPublicIpAddress(anyLong(), any(), any(), any(), any(), any(), anyBoolean(), anyBoolean())).thenReturn(ip); + NicProfile nic = new NicProfile(ReservationStrategy.Create, null, null, null, null); + guru.getIp(nic, dc, vm, network); + return nic; + } + + /** + * Regression: setRoutedRangeIpv6() runs inside getIp()'s routed branch and needs the NIC's + * MAC (EUI-64) — the MAC must be on the profile before that branch, not after it (NPE), and + * the DualStack format it sets must not be clobbered back to Ip4 afterwards. + */ + @Test + public void getIpOnRoutedRangeComputesEui64Ipv6FromNicMac() throws Exception { + PublicIp ip = publicIp("routed://534", "2a00:f10:402:2::/64"); + NicProfile nic = allocateOn(ip); + + assertEquals(ip.getMacAddress(), nic.getMacAddress()); + assertEquals("2.57.59.68", nic.getIPv4Address()); + assertEquals(NetUtils.IPV4_HOST_NETMASK, nic.getIPv4Netmask()); + assertEquals(NetUtils.getLinkLocalGateway(), nic.getIPv4Gateway()); + assertEquals("routed://534", nic.getBroadCastUri().toString()); + assertEquals(BroadcastDomainType.Routed, nic.getBroadcastType()); + assertEquals(NetUtils.EUI64Address("2a00:f10:402:2::/64", ip.getMacAddress()).toString(), nic.getIPv6Address()); + assertEquals(NetUtils.getIpv6LinkLocalGateway(), nic.getIPv6Gateway()); + assertEquals(AddressFormat.DualStack, nic.getFormat()); + } + + @Test + public void getIpOnVlanRangeKeepsClassicShape() throws Exception { + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); + PublicIp ip = publicIp("50", null); + NicProfile nic = allocateOn(ip); + + assertEquals(ip.getMacAddress(), nic.getMacAddress()); + assertEquals("2.57.59.68", nic.getIPv4Address()); + assertEquals("255.255.255.192", nic.getIPv4Netmask()); + assertEquals("2.57.59.65", nic.getIPv4Gateway()); + assertEquals("vlan://50", nic.getBroadCastUri().toString()); + assertNull(nic.getIPv6Address()); + assertEquals(AddressFormat.Ip4, nic.getFormat()); + } +} diff --git a/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java b/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java index 382b0876e475..84f61915dde5 100644 --- a/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java +++ b/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java @@ -1063,6 +1063,11 @@ public boolean isSharedNetworkWithoutSpecifyVlan(NetworkOffering offering) { return false; } + @Override + public boolean isL3NetworkWithoutSpecifyVlan(NetworkOffering offering) { + return false; + } + @Override public IpAddress updateIP(Long id, String customId, Boolean displayIp) { // TODO Auto-generated method stub diff --git a/utils/src/main/java/com/cloud/utils/net/NetUtils.java b/utils/src/main/java/com/cloud/utils/net/NetUtils.java index 03cc4f029e36..33d1b22770a8 100644 --- a/utils/src/main/java/com/cloud/utils/net/NetUtils.java +++ b/utils/src/main/java/com/cloud/utils/net/NetUtils.java @@ -92,6 +92,20 @@ public class NetUtils { public final static int PORT_RANGE_MIN = 0; public final static int PORT_RANGE_MAX = 65535; + /** + * The IPv4 link-local block and its first address, which KVM hosts carry on cloud0 for the + * control network and which Direct Routed (L3) guest networks use as the shared, + * host-independent gateway on every network's bridge. Defined here and nowhere else; use the + * getLinkLocal*() / getIpv6LinkLocalGateway() getters rather than these constants. The guru + * stamps the gateways on the NIC at allocation, and the agent passes the NIC's values down to + * modifybrdr.sh. + */ + private final static String IPV4_LINK_LOCAL_CIDR = "169.254.0.0/16"; + private final static String IPV4_LINK_LOCAL_GATEWAY = "169.254.0.1"; + private final static String IPV6_LINK_LOCAL_GATEWAY = "fe80::1"; + public final static String IPV4_HOST_NETMASK = "255.255.255.255"; + public final static int IPV6_HOST_PREFIX_LENGTH = 128; + public final static int DEFAULT_AUTOSCALE_EXPUNGE_VM_GRACE_PERIOD = 2 * 60; // Grace period before Vm is expunged public final static int DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME = 30; public final static int DEFAULT_AUTOSCALE_POLICY_QUIET_TIME = 5 * 60; @@ -1060,11 +1074,15 @@ public static String getLinkLocalGateway(String cidr) { } public static String getLinkLocalGateway() { - return getLinkLocalGateway(getLinkLocalCIDR()); + return IPV4_LINK_LOCAL_GATEWAY; + } + + public static String getIpv6LinkLocalGateway() { + return IPV6_LINK_LOCAL_GATEWAY; } public static String getLinkLocalCIDR() { - return "169.254.0.0/16"; + return IPV4_LINK_LOCAL_CIDR; } public static String getLinkLocalFirstAddressFromCIDR(final String cidr) { From fb9ea05f4834af59a84012e9b45a0e66a3d556c9 Mon Sep 17 00:00:00 2001 From: Wido den Hollander Date: Tue, 15 Sep 2026 08:33:56 +0000 Subject: [PATCH 2/8] SystemVMs: boot on routed public ranges Console proxies and secondary storage VMs can take their public address from a routed public range (createVlanIpRange with vlan=routed://). The management server then hands the address to the SystemVM in host-route form, a /32 or /128 with the shared link-local gateway on-link, and the SystemVM boot scripts configure it that way for IPv4 and IPv6 alike. --- .../consoleproxy/ConsoleProxyManagerImpl.java | 8 +++++++ .../SecondaryStorageManagerImpl.java | 8 +++++++ systemvm/debian/opt/cloud/bin/setup/common.sh | 21 ++++++++++++++++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index 289964f078ab..f4c65674e0f7 100644 --- a/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -1240,8 +1240,16 @@ public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, Depl buf.append(" eth").append(deviceId).append("mask=").append(nic.getIPv4Netmask()); } + if (nic.getIPv6Address() != null) { + buf.append(" eth").append(deviceId).append("ip6=").append(nic.getIPv6Address()); + buf.append(" eth").append(deviceId).append("ip6prelen=").append(NetUtils.getIp6CidrSize(nic.getIPv6Cidr())); + } + if (nic.isDefaultNic()) { buf.append(" gateway=").append(nic.getIPv4Gateway()); + if (nic.getIPv6Gateway() != null) { + buf.append(" ip6gateway=").append(nic.getIPv6Gateway()); + } } if (nic.getTrafficType() == TrafficType.Management) { diff --git a/services/secondary-storage/controller/src/main/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java b/services/secondary-storage/controller/src/main/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java index 081c89ea8f9c..0bb85fe1e70c 100644 --- a/services/secondary-storage/controller/src/main/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java +++ b/services/secondary-storage/controller/src/main/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java @@ -1195,8 +1195,16 @@ public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, Depl buf.append(" eth").append(deviceId).append("mask=").append(nic.getIPv4Netmask()); } + if (nic.getIPv6Address() != null) { + buf.append(" eth").append(deviceId).append("ip6=").append(nic.getIPv6Address()); + buf.append(" eth").append(deviceId).append("ip6prelen=").append(NetUtils.getIp6CidrSize(nic.getIPv6Cidr())); + } + if (nic.isDefaultNic()) { buf.append(" gateway=").append(nic.getIPv4Gateway()); + if (nic.getIPv6Gateway() != null) { + buf.append(" ip6gateway=").append(nic.getIPv6Gateway()); + } } if (nic.getTrafficType() == TrafficType.Management) { String mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key()); diff --git a/systemvm/debian/opt/cloud/bin/setup/common.sh b/systemvm/debian/opt/cloud/bin/setup/common.sh index 7e9245293f40..a874b80b5a8f 100755 --- a/systemvm/debian/opt/cloud/bin/setup/common.sh +++ b/systemvm/debian/opt/cloud/bin/setup/common.sh @@ -398,7 +398,26 @@ setup_common() { gwdev="eth0" fi - ip route add default via $GW dev $gwdev + onlink="" + case "$GW" in + 169.254.*) + # Direct routed public interface: the address is a /32, so the shared + # link-local gateway lies outside it and the kernel rejects the route + # unless it is marked on-link. Same rule cloud-init applies for guest + # Instances; systemvms have no cloud-init, so it is applied here. + onlink="onlink" + ;; + esac + ip route add default via $GW dev $gwdev $onlink + + # The IPv6 default route is installed statically when a gateway was passed + # down: on a direct routed bridge no router advertisement ever arrives, so + # relying on accept_ra would leave the systemvm without v6 connectivity. + # A link-local gateway (fe80::1) needs the dev and is on-link by definition. + if [ -n "$IP6GW" ] + then + ip -6 route replace default via $IP6GW dev $gwdev + fi fi # Workaround to activate vSwitch under VMware From c1dc985a9223d90343bb0e07248b72c8c5afa511 Mon Sep 17 00:00:00 2001 From: Wido den Hollander Date: Tue, 15 Sep 2026 08:33:13 +0000 Subject: [PATCH 3/8] KVM: per-network bridges and host routes for Direct Routed Instances The agent recognises a Direct Routed NIC by its routed:// broadcast domain and asks the new modifybrdr.sh for the network's bridge. The script creates one uplink-less bridge per network, named brdr-, with the gateway addresses passed in by the agent, forwarding sysctls, strict rp_filter, arp_ignore/arp_announce for the shared gateway address, and a MAC derived from the routed id so it is identical on every hypervisor and live migration never invalidates the guest's neighbour cache. The existing modifymacip.sh installs the per-address host route and static neighbour entry when a NIC is plugged, and removes them at unplug before the script may delete an empty bridge. How these bridges are named is known only to the script; the agent asks it (query) rather than parsing names itself. Every script operation prints exactly one token on stdout with diagnostics on stderr, inputs are validated, and the agent reads the last line and checks it is an interface name, so a stray warning can never end up as the bridge name in the domain XML. A missing modifymacip.sh is fatal for a Direct Routed NIC. Because the host routes for its Instances, their packets enter the host's own IP stack. Per bridge, the script inserts an INPUT rule that drops everything from the bridge that is not ICMP(v6), which gateway resolution and reachability checks need, and an ip6tables raw rpfilter rule as the IPv6 counterpart of rp_filter=1. Both are removed with the bridge. A failed VM start or migration prepare now unplugs the NICs it plugged. The security group wrapper passes --directrouted to security_group.py for these NICs, and a failed ipset update for secondary IPs is reported instead of returning success. --- .../kvm/resource/BridgeVifDriver.java | 221 +++++++++++++++- .../resource/LibvirtComputingResource.java | 72 ++++- .../wrapper/LibvirtMigrateCommandWrapper.java | 18 +- ...tworkRulesVmSecondaryIpCommandWrapper.java | 2 +- ...virtPrepareForMigrationCommandWrapper.java | 7 + ...bvirtSecurityGroupRulesCommandWrapper.java | 9 +- .../wrapper/LibvirtStartCommandWrapper.java | 6 + .../kvm/resource/BridgeVifDriverTest.java | 247 ++++++++++++++++++ .../LibvirtComputingResourceTest.java | 8 +- .../LibvirtMigrateCommandWrapperTest.java | 20 ++ ...PrepareForMigrationCommandWrapperTest.java | 50 ++++ scripts/vm/network/vnet/modifybrdr.sh | 162 ++++++++++++ scripts/vm/network/vnet/modifymacip.sh | 29 +- 13 files changed, 830 insertions(+), 21 deletions(-) create mode 100755 scripts/vm/network/vnet/modifybrdr.sh diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index b9915a91856b..3d477c24d6c8 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -58,9 +58,41 @@ public class BridgeVifDriver extends VifDriverBase { private String _modifyVlanPath; private String _modifyVxlanPath; private String _macIpScriptPath; + private boolean _macIpStaticEnabled; + private String _modifyBrdrPath; private String _controlCidr = NetUtils.getLinkLocalCIDR(); private Long libvirtVersion; + /** + * What a Linux interface name may look like; modifybrdr.sh prints exactly one such name on + * a successful add, and anything else in its output is a diagnostic. + */ + private static final Pattern BRIDGE_NAME_PATTERN = Pattern.compile("^[A-Za-z0-9_.-]{1,15}$"); + private static final String BRDR_MINE = "mine"; + private static final String BRDR_NOTMINE = "notmine"; + private static final String BRDR_KEPT = "kept"; + private static final String BRDR_DELETED = "deleted"; + + /** + * A NIC on a Direct Routed (L3) network is recognised by its broadcast domain: routed://, + * stamped by the management server. The id is a label naming the per-network bridge + * (brdr-), never an encapsulation. An earlier revision inferred this from the address + * form (/32 + link-local gateway); the explicit broadcast type supersedes that implicit + * contract, and works for guest and (systemvm) public NICs alike. + * + * The URI is checked as well as the type enum: a SystemVM's public NIC profile is rebuilt at + * start from the shared Public network, whose broadcast domain type is Vlan — only the NIC's + * own broadcast URI carries the routed:// stamp then (NicProfile copies broadcastType from + * the network, not the nic row). + */ + public static boolean isDirectRoutedNic(NicTO nic) { + if (nic == null) { + return false; + } + return nic.getBroadcastType() == Networks.BroadcastDomainType.Routed + || (nic.getBroadcastUri() != null && Networks.BroadcastDomainType.Routed.scheme().equals(nic.getBroadcastUri().getScheme())); + } + private static boolean isVxlanOrNetris(String protocol) { return protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme()) || protocol.equals(Networks.BroadcastDomainType.Netris.scheme()); } @@ -93,14 +125,17 @@ public void configure(Map params) throws ConfigurationException throw new ConfigurationException("Unable to find " + vxlanScript); } - if (Boolean.TRUE.equals(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_NETWORK_MACIP_STATIC))) { - _macIpScriptPath = Script.findScript(networkScriptsDir, "modifymacip.sh"); + _macIpScriptPath = Script.findScript(networkScriptsDir, "modifymacip.sh"); + _macIpStaticEnabled = Boolean.TRUE.equals(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_NETWORK_MACIP_STATIC)); + if (_macIpStaticEnabled) { if (_macIpScriptPath == null) { throw new ConfigurationException("Unable to find modifymacip.sh"); } logger.info("VM network MAC/IP static script configured: {}", _macIpScriptPath); } + _modifyBrdrPath = Script.findScript(networkScriptsDir, "modifybrdr.sh"); + libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; @@ -212,9 +247,15 @@ public static boolean isUntaggedBroadcast(final NicTO nic) { return nic.getBroadcastUri() != null && "untagged".equalsIgnoreCase(Networks.BroadcastDomainType.getValue(nic.getBroadcastUri())); } + /** + * Whether a NIC is placed on the host's shared VLAN-aware guest bridge rather than on a bridge + * of its own. A Direct Routed NIC never is: it sits on its per-network routed bridge whatever + * broadcast domain type it carries (a SystemVM public NIC on a routed range keeps the Public + * network's Vlan type, only its URI is routed://). + */ protected boolean usesSharedVlanAwareBridge(final NicTO nic) { return nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan && _libvirtComputingResource.hostSupportsVlanFiltering() - && !isUntaggedBroadcast(nic); + && !isUntaggedBroadcast(nic) && !isDirectRoutedNic(nic); } protected void plugTrunkVlanNic(LibvirtVMDef.InterfaceDef intf, NicTO nic, String trafficLabel, String guestOsType, String nicAdapter, @@ -457,6 +498,15 @@ protected String createStorageVnetBridgeIfNeeded(NicTO nic, String trafficLabel, return createVnetBr(vNetId, storageBrName, protocol); } + /** + * Direct Routed (L3) NICs — guest Instances and the public NICs of SystemVMs alike — go on + * the network's own uplink-less bridge, never on a shared guest/public bridge, and always get + * the MAC/IP script run: the host route and static neighbour entry it installs are what + * deliver their traffic. For every other NIC the MAC/IP script runs only when the host-wide + * vm.network.macip.static property (the EVPN use case) enables it — which is why the script + * path is resolved unconditionally in configure() but only required there when the property + * is set. + */ @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { @@ -483,7 +533,10 @@ public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicA networkRateKBps = getNetworkRateKbps(nic); } - if (nic.getType() == Networks.TrafficType.Guest) { + if ((nic.getType() == Networks.TrafficType.Guest || nic.getType() == Networks.TrafficType.Public) && isDirectRoutedNic(nic)) { + String brName = createDirectRoutedBridge(nic); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); + } else if (nic.getType() == Networks.TrafficType.Guest) { if (nic.isTrunkVlan()) { plugTrunkVlanNic(intf, nic, trafficLabel, guestOsType, nicAdapter, networkRateKBps); } else if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { @@ -538,17 +591,173 @@ public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicA } intf.setLinkStateUp(nic.isEnabled()); - executeMacIpScript(intf.getBrName(), nic.getMac(), nic.getIp(), nic.getIp6Address(), nic.getNicSecIps()); + if (_macIpStaticEnabled || isDirectRoutedNic(nic)) { + executeMacIpScript(intf.getBrName(), nic.getMac(), nic.getIp(), nic.getIp6Address(), nic.getNicSecIps()); + } return intf; } + /** + * How the bridges of Direct Routed (L3) networks are named is known only to modifybrdr.sh; + * the interface is classified at unplug by asking the script ("query"), which answers + * "notmine" when it is not such a bridge and the regular unplug handling applies. For a + * Direct Routed bridge the host route and neighbour entry of the interface are removed + * first, while the bridge they reference still exists, and only then is the script asked to + * delete the bridge should nothing else be attached to it. + */ @Override public void unplug(LibvirtVMDef.InterfaceDef iface, boolean deleteBr) { - executeMacIpScript(iface.getBrName(), iface.getMacAddress()); + boolean directRouted = isDirectRoutedBridge(iface.getBrName()); + if (_macIpStaticEnabled || directRouted) { + executeMacIpScript(iface.getBrName(), iface.getMacAddress()); + } + if (directRouted) { + deleteDirectRoutedBridge(iface.getBrName()); + return; + } deleteVnetBr(iface.getBrName(), deleteBr); } + /** + * Ensures the per-network bridge for a Direct Routed NIC exists, with the shared gateway + * addresses and sysctls applied. Idempotent and flock'd in the script itself. A failure here + * is fatal to the NIC plug: without the bridge the domain XML would reference a nonexistent + * device and the Instance would fail to start with a far less useful error. A missing + * modifymacip.sh is fatal for the same reason: without the host route and neighbour entry it + * installs the Instance would start with no connectivity at all. + * + * The routed id — the value of the network's routed://<id> broadcast domain, operator + * controlled and stable for the network's life — names the bridge, but how these bridges are + * named is known only to modifybrdr.sh: the script prints the bridge name it created, never + * the agent. The script's stderr is merged into its stdout by Script, so the last non-blank + * line is taken and must look like an interface name; anything else means the script did not + * produce a bridge. The gateway addresses passed along come from the NIC, whose values the + * management server stamped at allocation (NetUtils.getLinkLocalGateway() / + * getIpv6LinkLocalGateway()); the script has no defaults of its own, so the addresses are + * defined in exactly one place. + */ + protected String createDirectRoutedBridge(NicTO nic) throws InternalErrorException { + if (_modifyBrdrPath == null) { + throw new InternalErrorException("Unable to find modifybrdr.sh: this host cannot run Instances on Direct Routed (L3) networks"); + } + if (_macIpScriptPath == null) { + throw new InternalErrorException("Unable to find modifymacip.sh: this host cannot run Instances on Direct Routed (L3) networks"); + } + String routedId = nic.getBroadcastUri() != null ? Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()) : null; + if (StringUtils.isBlank(routedId)) { + throw new InternalErrorException("Direct Routed NIC " + nic.getMac() + " carries no routed:// broadcast URI; cannot derive its bridge"); + } + Script command = new Script(_modifyBrdrPath, _timeout, logger); + command.add("-o", "add"); + command.add("-n", routedId); + if (StringUtils.isNotBlank(nic.getGateway())) { + command.add("-4", nic.getGateway()); + } + if (StringUtils.isNotBlank(nic.getIp6Gateway())) { + command.add("-6", nic.getIp6Gateway()); + } + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = command.execute(parser); + if (result != null) { + throw new InternalErrorException("Failed to create bridge for routed id " + routedId + ": " + result); + } + String brName = lastNonBlankLine(parser.getLines()); + if (brName == null || !BRIDGE_NAME_PATTERN.matcher(brName).matches()) { + throw new InternalErrorException("modifybrdr.sh did not return a usable bridge name for routed id " + routedId + ": " + parser.getLines()); + } + return brName; + } + + /** + * Asks modifybrdr.sh whether the bridge is one of its own without changing anything. Only an + * exact "mine" counts; "notmine", a script failure or an unexpected answer all send the + * caller down the regular unplug handling. + */ + protected boolean isDirectRoutedBridge(String brName) { + if (_modifyBrdrPath == null || brName == null) { + return false; + } + String verdict = runModifyBrdrVerdict("query", brName); + if (verdict == null) { + return false; + } + if (BRDR_MINE.equals(verdict)) { + return true; + } + if (!BRDR_NOTMINE.equals(verdict)) { + logger.warn("Unexpected answer from modifybrdr.sh query for bridge {}: {}", brName, verdict); + } + return false; + } + + /** + * Asks modifybrdr.sh to remove the bridge if it is one of its own and nothing is attached to + * it any more. Returns whether the script gave one of its three answers (notmine, kept, + * deleted); anything else is a failure and is logged. Best-effort beyond that: the script + * keeps the bridge while other Instances of the network still use it, and a leftover empty + * bridge is harmless and reused on the next plug. + */ + protected boolean deleteDirectRoutedBridge(String brName) { + if (_modifyBrdrPath == null || brName == null) { + return false; + } + String verdict = runModifyBrdrVerdict("delete", brName); + if (verdict == null) { + return false; + } + if (BRDR_NOTMINE.equals(verdict) || BRDR_KEPT.equals(verdict) || BRDR_DELETED.equals(verdict)) { + logger.debug("modifybrdr.sh delete on bridge {}: {}", brName, verdict); + return true; + } + logger.warn("Unexpected answer from modifybrdr.sh delete for bridge {}: {}", brName, verdict); + return false; + } + + /** + * Runs a modifybrdr.sh operation that takes a bridge name and answers with a single token, + * returning the last non-blank line of its output, or null when the script failed. + */ + private String runModifyBrdrVerdict(String operation, String brName) { + try { + Script command = new Script(_modifyBrdrPath, _timeout, logger); + command.add("-o", operation); + command.add("-b", brName); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = command.execute(parser); + if (result != null) { + logger.warn("modifybrdr.sh {} failed for bridge {}: {}", operation, brName, result); + return null; + } + String verdict = lastNonBlankLine(parser.getLines()); + if (verdict == null) { + logger.warn("modifybrdr.sh {} gave no answer for bridge {}", operation, brName); + } + return verdict; + } catch (Exception e) { + logger.warn("Failed to run modifybrdr.sh {} for bridge {}", operation, brName, e); + return null; + } + } + + /** + * Returns the last non-blank line of a script's merged stdout/stderr output, trimmed, or + * null when there is none. The result token of modifybrdr.sh is always printed last. + */ + protected static String lastNonBlankLine(String output) { + if (output == null) { + return null; + } + String[] lines = output.split("\n"); + for (int i = lines.length - 1; i >= 0; i--) { + String line = lines[i].trim(); + if (!line.isEmpty()) { + return line; + } + } + return null; + } + @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("ip link set " + iface.getDevName() + " master " + iface.getBrName()); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index ac58581cbff4..3afcaa4895e3 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -465,6 +465,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private boolean imageServerTlsEnabled = false; private String imageServerListenAddress; private String securityGroupPath; + private String macIpPath; private String ovsPvlanDhcpHostPath; private String ovsPvlanVmPath; private String routerProxyPath; @@ -1239,6 +1240,7 @@ public boolean configure(final String name, final Map params) th } securityGroupPath = Script.findScript(networkScriptsDir, "security_group.py"); + macIpPath = Script.findScript(networkScriptsDir, "modifymacip.sh"); if (securityGroupPath == null) { throw new ConfigurationException("Unable to find the security_group.py"); } @@ -5139,7 +5141,7 @@ private DiskDef.DiskBus getGuestDiskModel(final String platformEmulator, boolean } } - private void cleanupVMNetworks(final Connect conn, final List nics) { + public void cleanupVMNetworks(final Connect conn, final List nics) { if (nics != null) { for (final InterfaceDef nic : nics) { for (final VifDriver vifDriver : getAllVifDrivers()) { @@ -5843,6 +5845,9 @@ public boolean defaultNetworkRules(final Connect conn, final String vmName, fina if (checkBeforeApply) { cmd.add("--check"); } + if (BridgeVifDriver.isDirectRoutedNic(nic)) { + cmd.add("--directrouted"); + } final String result = cmd.execute(); if (result != null) { return false; @@ -5971,7 +5976,7 @@ private Answer listLvmVolumes(String localPath, int startIndex, int pageSize) { } public boolean addNetworkRules(final String vmName, final String vmId, final String guestIP, final String guestIP6, final String sig, final String seq, final String mac, final String rules, final String vif, final String brname, - final String secIps) { + final String secIps, final boolean directRouted) { if (!canBridgeFirewall) { return false; } @@ -5981,7 +5986,9 @@ public boolean addNetworkRules(final String vmName, final String vmId, final Str cmd.add("add_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId); - cmd.add("--vmip", guestIP); + if (StringUtils.isNotBlank(guestIP)) { + cmd.add("--vmip", guestIP); + } if (StringUtils.isNotBlank(guestIP6)) { cmd.add("--vmip6", guestIP6); } @@ -5994,6 +6001,9 @@ public boolean addNetworkRules(final String vmName, final String vmId, final Str if (newRules != null && !newRules.isEmpty()) { cmd.add("--rules", newRules); } + if (directRouted) { + cmd.add("--directrouted"); + } final String result = cmd.execute(); if (result != null) { return false; @@ -6002,8 +6012,27 @@ public boolean addNetworkRules(final String vmName, final String vmId, final Str } public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String vmMac, final String secIp, final String action) { + return configureNetworkRulesVMSecondaryIP(conn, vmName, vmMac, secIp, action, false, true); + } + + /** + * On a Direct Routed network the secondary address only reaches the Instance once the host + * has a route and a neighbour entry for it. Security groups may be disabled there, so that + * is done regardless of canBridgeFirewall, and before any firewall rules. + */ + public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String vmMac, final String secIp, final String action, + final boolean directRouted, final boolean applySecurityGroupRules) { + + if (directRouted && !configureDirectRoutedSecondaryIp(conn, vmName, vmMac, secIp, action)) { + return false; + } + + if (!applySecurityGroupRules) { + return true; + } if (!canBridgeFirewall) { + LOGGER.warn("Security group rules were requested for secondary IP {} of {} but this host cannot bridge firewall; the ipset was not updated", secIp, vmName); return false; } @@ -6021,6 +6050,43 @@ public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final Stri return true; } + /** + * Adds or removes the host route and static neighbour entry for a secondary IP of an + * Instance on a Direct Routed network, so the address is reachable without restarting it. + */ + private boolean configureDirectRoutedSecondaryIp(final Connect conn, final String vmName, final String vmMac, final String secIp, final String action) { + if (macIpPath == null) { + LOGGER.warn("Unable to find modifymacip.sh, cannot configure secondary IP {} for {}", secIp, vmName); + return false; + } + if (StringUtils.isBlank(vmMac) || StringUtils.isBlank(secIp)) { + LOGGER.warn("Cannot configure secondary IP for {}: MAC '{}' or address '{}' is missing", vmName, vmMac, secIp); + return false; + } + String brName = null; + for (final InterfaceDef intf : getInterfaces(conn, vmName)) { + if (vmMac.equalsIgnoreCase(intf.getMacAddress())) { + brName = intf.getBrName(); + break; + } + } + if (brName == null) { + LOGGER.warn("Unable to find the interface of {} with MAC {}", vmName, vmMac); + return false; + } + final Script cmd = new Script(macIpPath, timeout, LOGGER); + cmd.add("-o", "-A".equals(action) ? "add" : "delete"); + cmd.add("-b", brName); + cmd.add("-m", vmMac); + cmd.add(NetUtils.isValidIp6(secIp) ? "-6" : "-4", secIp); + final String result = cmd.execute(); + if (result != null) { + LOGGER.warn("Failed to configure secondary IP {} for {}: {}", secIp, vmName, result); + return false; + } + return true; + } + public boolean setupTungstenVRouter(final String oper, final String inf, final String subnet, final String route, final String vrf) { final Script cmd = new Script(setupTungstenVrouterPath, timeout, LOGGER); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java index f15ad8e562f8..16f1bd900766 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java @@ -705,7 +705,7 @@ protected String replaceVlanTrunkInterfaces(String xmlDesc, MigrateCommand comma boolean destVlanFilteringEnabled = Boolean.TRUE.equals(command.getDestVlanFilteringEnabled()); boolean anyNicNeedsHandling = false; for (NicTO nic : nics) { - if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan && (sourceVlanFilteringEnabled || destVlanFilteringEnabled || nic.isTrunkVlan())) { + if (needsVlanTrunkHandling(nic, sourceVlanFilteringEnabled, destVlanFilteringEnabled)) { failIfBroadcastUriMissing(nic); anyNicNeedsHandling = true; } @@ -735,8 +735,7 @@ protected String replaceVlanTrunkInterfaces(String xmlDesc, MigrateCommand comma Element interfaceElement = (Element) deviceChildNode; String mac = findInterfaceMacAddress(interfaceElement); NicTO nic = mac == null ? null : findNicByMac(nics, mac); - if (nic == null || nic.getBroadcastType() != Networks.BroadcastDomainType.Vlan - || !(sourceVlanFilteringEnabled || destVlanFilteringEnabled || nic.isTrunkVlan())) { + if (nic == null || !needsVlanTrunkHandling(nic, sourceVlanFilteringEnabled, destVlanFilteringEnabled)) { continue; } replaceVlanTrunkInterface(doc, interfaceElement, nic, command); @@ -782,6 +781,19 @@ private String findInterfaceMacAddress(Element interfaceElement) { return null; } + /** + * Only Vlan-broadcast NICs that live on a shared VLAN-aware bridge on either side, or that trunk + * several VLANs, need their bridge or trunk XML rewritten. A Direct Routed NIC is never one of + * them: it sits on its per-network routed bridge on both hosts, even when it carries the Vlan + * broadcast domain type of the shared Public network with a routed:// URI (a SystemVM public NIC). + */ + private boolean needsVlanTrunkHandling(NicTO nic, boolean sourceVlanFilteringEnabled, boolean destVlanFilteringEnabled) { + if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vlan || BridgeVifDriver.isDirectRoutedNic(nic)) { + return false; + } + return sourceVlanFilteringEnabled || destVlanFilteringEnabled || nic.isTrunkVlan(); + } + private void replaceVlanTrunkInterface(Document doc, Element interfaceElement, NicTO nic, MigrateCommand command) { String destBridge = command.getNicBridgeMapping().get(nic.getMac()); Boolean destVlanFilteringEnabled = command.getDestVlanFilteringEnabled(); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java index 890558ca3651..018d3b929284 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java @@ -39,7 +39,7 @@ public Answer execute(final NetworkRulesVmSecondaryIpCommand command, final Libv final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper(); final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName()); - result = libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmMac(), command.getVmSecIp(), command.getAction()); + result = libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmMac(), command.getVmSecIp(), command.getAction(), command.isDirectRouted(), command.isApplySecurityGroupRules()); } catch (final LibvirtException e) { logger.debug("Could not configure VM secondary IP! => " + e.getLocalizedMessage()); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java index 9b766265c9dc..4595cd3d6d03 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java @@ -20,6 +20,7 @@ package com.cloud.hypervisor.kvm.resource.wrapper; import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -75,6 +76,7 @@ public Answer execute(final PrepareForMigrationCommand command, final LibvirtCom boolean skipDisconnect = false; + final List pluggedNics = new ArrayList<>(); final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr(); try { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper(); @@ -84,6 +86,9 @@ public Answer execute(final PrepareForMigrationCommand command, final LibvirtCom for (final NicTO nic : nics) { VifDriver vifDriver = libvirtComputingResource.getVifDriver(nic.getType(), nic.getName()); LibvirtVMDef.InterfaceDef interfaceDef = vifDriver.plug(nic, null, "", vm.getExtraConfig()); + if (interfaceDef != null) { + pluggedNics.add(interfaceDef); + } libvirtComputingResource.setInterfaceDefQueueSettings(vm.getDetails(), vm.getCpus(), interfaceDef, nic.getMultiqueueNumber(), vm.getType() == VirtualMachine.Type.DomainRouter); if (interfaceDef != null && interfaceDef.getNetType() == GuestNetType.VHOSTUSER) { DpdkTO to = new DpdkTO(interfaceDef.getDpdkOvsPath(), interfaceDef.getDpdkSourcePort(), interfaceDef.getInterfaceMode()); @@ -128,6 +133,7 @@ public Answer execute(final PrepareForMigrationCommand command, final LibvirtCom skipDisconnect = true; if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vm, true)) { + libvirtComputingResource.cleanupVMNetworks(conn, pluggedNics); return new PrepareForMigrationAnswer(command, "failed to connect physical disks to host"); } @@ -152,6 +158,7 @@ public Answer execute(final PrepareForMigrationCommand command, final LibvirtCom removeDpdkPort(to.getPort()); } } + libvirtComputingResource.cleanupVMNetworks(null, pluggedNics); return new PrepareForMigrationAnswer(command, e.toString()); } finally { if (!skipDisconnect) { diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java index 33164264ae80..aa6a13b416f5 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java @@ -28,6 +28,7 @@ import com.cloud.agent.api.SecurityGroupRuleAnswer; import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.hypervisor.kvm.resource.BridgeVifDriver; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; import com.cloud.resource.CommandWrapper; @@ -59,8 +60,14 @@ public Answer execute(final SecurityGroupRulesCmd command, final LibvirtComputin return new SecurityGroupRuleAnswer(command, false, e.toString()); } + boolean directRouted = false; + final VirtualMachineTO vmTO = command.getVmTO(); + if (vmTO != null && vmTO.getNics() != null && vmTO.getNics().length > 0) { + directRouted = BridgeVifDriver.isDirectRoutedNic(vmTO.getNics()[0]); + } + final boolean result = libvirtComputingResource.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getGuestIp6(), command.getSignature(), - Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString()); + Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString(), directRouted); if (!result) { logger.warn("Failed to program network rules for vm " + command.getVmName()); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java index fd771add7bea..7ada0962a083 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java @@ -172,6 +172,12 @@ public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource.handleVmStartFailure(conn, vmName, vm); } return new StartAnswer(command, e.getMessage()); + } catch (final RuntimeException e) { + logger.warn("RuntimeException while starting VM {}", vmName, e); + if (conn != null) { + libvirtComputingResource.handleVmStartFailure(conn, vmName, vm); + } + return new StartAnswer(command, e.toString()); } finally { if (state != DomainState.VIR_DOMAIN_RUNNING) { storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec); diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriverTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriverTest.java index 8a63adb5b879..2eeaf9f9208a 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriverTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriverTest.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.hypervisor.kvm.resource; +import java.io.BufferedReader; +import java.io.StringReader; +import java.lang.reflect.Field; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; @@ -29,19 +32,25 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; import com.cloud.agent.api.to.NetworkTO; import com.cloud.agent.api.to.NicTO; import com.cloud.exception.InternalErrorException; import com.cloud.network.Networks; +import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.Script; @RunWith(MockitoJUnitRunner.class) public class BridgeVifDriverTest { private static final String BRIDGE_NAME = "cloudbr1"; + private static final String MODIFY_BRDR = "/scripts/modifybrdr.sh"; + private static final String MODIFY_MACIP = "/scripts/modifymacip.sh"; @Mock private LibvirtComputingResource libvirtComputingResource; @@ -64,6 +73,49 @@ public void setup() throws InternalErrorException { Mockito.lenient().doNothing().when(driver).runBridgeVlanCommand(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()); } + private static void setField(Object target, String name, Object value) throws Exception { + Field field = BridgeVifDriver.class.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + + /** + * Feeds the given text to the OutputInterpreter a Script.execute(parser) call passes, the + * way Script does with the merged stdout/stderr of the real process, and reports success. + */ + private static Answer scriptOutput(String output) { + return invocation -> { + OutputInterpreter parser = invocation.getArgument(0); + parser.interpret(new BufferedReader(new StringReader(output))); + return null; + }; + } + + private static MockedConstruction + + diff --git a/ui/src/views/network/CreateNetwork.vue b/ui/src/views/network/CreateNetwork.vue index 46ed9d2e039f..385bb1bba98e 100644 --- a/ui/src/views/network/CreateNetwork.vue +++ b/ui/src/views/network/CreateNetwork.vue @@ -34,6 +34,13 @@ @refresh-data="refreshParent" @refresh="handleRefresh"/> + + + {{ $t('label.l2') }} + + {{ $t('label.l3') }} + {{ $t('label.shared') }} @@ -97,13 +100,15 @@ - + @@ -206,6 +211,20 @@ + + + + +
+ + + + + + +
@@ -292,7 +311,7 @@ - + @@ -352,7 +371,7 @@ - +