mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(ec2): support DHCP options lifecycle (#6428)
* feat(ec2): support DHCP options lifecycle * fix(ec2): validate DHCP options lifecycle edge cases * fix(ec2): reuse region-aware private DNS domain for DHCP defaults * fix(ec2): isolate DHCP options review regressions
This commit is contained in:
1 parent
781a68b6cb
commit
4a95c1bb95
8 files changed
+832
-4
No files matched your search
@@ -106,6 +106,10 @@ public class Ec2QueryHandler {
|
||||
case "DeleteVpc" -> handleDeleteVpc(params, region);
|
||||
case "ModifyVpcAttribute" -> handleModifyVpcAttribute(params, region);
|
||||
case "DescribeVpcAttribute" -> handleDescribeVpcAttribute(params, region);
|
||||
case "CreateDhcpOptions" -> handleCreateDhcpOptions(params, region);
|
||||
case "DescribeDhcpOptions" -> handleDescribeDhcpOptions(params, region);
|
||||
case "AssociateDhcpOptions" -> handleAssociateDhcpOptions(params, region);
|
||||
case "DeleteDhcpOptions" -> handleDeleteDhcpOptions(params, region);
|
||||
case "DescribeVpcEndpointServices" -> handleDescribeVpcEndpointServices(params, region);
|
||||
case "CreateVpcEndpoint" -> handleCreateVpcEndpoint(params, region);
|
||||
case "DescribeVpcEndpoints" -> handleDescribeVpcEndpoints(params, region);
|
||||
@@ -1684,6 +1688,109 @@ public class Ec2QueryHandler {
|
||||
return booleanResponse("DeleteVpc");
|
||||
}
|
||||
|
||||
private Response handleCreateDhcpOptions(MultivaluedMap<String, String> p, String region) {
|
||||
List<DhcpConfiguration> configurations = new ArrayList<>();
|
||||
for (int i : numberedIndices(p, "DhcpConfiguration.")) {
|
||||
String prefix = "DhcpConfiguration." + i;
|
||||
String key = p.getFirst(prefix + ".Key");
|
||||
if (key == null) {
|
||||
throw new AwsException("MissingParameter", prefix + ".Key is required", 400);
|
||||
}
|
||||
List<String> values = numberedIndices(p, prefix + ".Value.").stream()
|
||||
.map(index -> p.getFirst(prefix + ".Value." + index)).toList();
|
||||
configurations.add(new DhcpConfiguration(key, values));
|
||||
}
|
||||
List<Tag> tags = parseTagsForResource(p, "dhcp-options");
|
||||
DhcpOptions options = service.createDhcpOptions(region, configurations);
|
||||
try {
|
||||
applyResourceTags(tags, region, options.getDhcpOptionsId());
|
||||
} catch (RuntimeException failure) {
|
||||
try {
|
||||
service.deleteDhcpOptions(region, options.getDhcpOptionsId());
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
return xmlResponse(new XmlBuilder()
|
||||
.start("CreateDhcpOptionsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("dhcpOptions").raw(dhcpOptionsXml(region, options)).end("dhcpOptions")
|
||||
.end("CreateDhcpOptionsResponse").build());
|
||||
}
|
||||
|
||||
private SortedSet<Integer> numberedIndices(MultivaluedMap<String, String> params, String prefix) {
|
||||
SortedSet<Integer> indices = new TreeSet<>();
|
||||
for (String name : params.keySet()) {
|
||||
if (!name.startsWith(prefix)) {
|
||||
continue;
|
||||
}
|
||||
String suffix = name.substring(prefix.length());
|
||||
int dot = suffix.indexOf('.');
|
||||
String number = dot < 0 ? suffix : suffix.substring(0, dot);
|
||||
try {
|
||||
int index = Integer.parseInt(number);
|
||||
if (index < 1) {
|
||||
throw new NumberFormatException(number);
|
||||
}
|
||||
indices.add(index);
|
||||
} catch (NumberFormatException invalid) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid parameter index in " + name, 400);
|
||||
}
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
private Response handleDescribeDhcpOptions(MultivaluedMap<String, String> p, String region) {
|
||||
int maxResults = parseIntParam(p, "MaxResults", 0);
|
||||
if (p.containsKey("MaxResults") && maxResults == 0) {
|
||||
throw new AwsException("InvalidMaxResults", "MaxResults must be between 5 and 1000", 400);
|
||||
}
|
||||
PaginatedResult<DhcpOptions> result = service.describeDhcpOptions(region, getList(p, "DhcpOptionsId"),
|
||||
getFiltersList(p), maxResults, p.getFirst("NextToken"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeDhcpOptionsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("dhcpOptionsSet");
|
||||
for (DhcpOptions options : result.items()) {
|
||||
xml.start("item").raw(dhcpOptionsXml(region, options)).end("item");
|
||||
}
|
||||
xml.end("dhcpOptionsSet");
|
||||
if (result.nextToken() != null) {
|
||||
xml.elem("nextToken", result.nextToken());
|
||||
}
|
||||
return xmlResponse(xml.end("DescribeDhcpOptionsResponse").build());
|
||||
}
|
||||
|
||||
private Response handleAssociateDhcpOptions(MultivaluedMap<String, String> p, String region) {
|
||||
service.associateDhcpOptions(region, p.getFirst("DhcpOptionsId"), p.getFirst("VpcId"));
|
||||
return booleanResponse("AssociateDhcpOptions");
|
||||
}
|
||||
|
||||
private Response handleDeleteDhcpOptions(MultivaluedMap<String, String> p, String region) {
|
||||
service.deleteDhcpOptions(region, p.getFirst("DhcpOptionsId"));
|
||||
return booleanResponse("DeleteDhcpOptions");
|
||||
}
|
||||
|
||||
private String dhcpOptionsXml(String region, DhcpOptions options) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("dhcpOptionsId", options.getDhcpOptionsId())
|
||||
.elem("ownerId", options.getOwnerId())
|
||||
.start("dhcpConfigurationSet");
|
||||
for (DhcpConfiguration configuration : options.getConfigurations()) {
|
||||
xml.start("item").elem("key", configuration.getKey()).start("valueSet");
|
||||
for (String value : configuration.getValues()) {
|
||||
xml.start("item").elem("value", value).end("item");
|
||||
}
|
||||
xml.end("valueSet").end("item");
|
||||
}
|
||||
xml.end("dhcpConfigurationSet").start("tagSet");
|
||||
for (Tag tag : service.resourceTags(region, options.getDhcpOptionsId())) {
|
||||
xml.start("item").elem("key", tag.getKey()).elem("value", tag.getValue()).end("item");
|
||||
}
|
||||
return xml.end("tagSet").build();
|
||||
}
|
||||
|
||||
private Response handleModifyVpcAttribute(MultivaluedMap<String, String> p, String region) {
|
||||
String vpcId = p.getFirst("VpcId");
|
||||
if (p.containsKey("EnableDnsSupport.Value")) {
|
||||
|
||||
@@ -27,6 +27,8 @@ import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogIns
|
||||
import io.github.hectorvent.floci.services.ec2.model.Address;
|
||||
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
|
||||
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.DhcpConfiguration;
|
||||
import io.github.hectorvent.floci.services.ec2.model.DhcpOptions;
|
||||
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
|
||||
import io.github.hectorvent.floci.services.ec2.model.EgressOnlyInternetGateway;
|
||||
import io.github.hectorvent.floci.services.ec2.model.EgressOnlyInternetGatewayListResult;
|
||||
@@ -111,6 +113,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -279,6 +282,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// persistent/hybrid/wal modes; see #1297 — CloudFormation persists stacks/exports that
|
||||
// reference these EC2 ids, so the ids must survive too)
|
||||
private final StorageBackend<String, Vpc> vpcs;
|
||||
private final StorageBackend<String, DhcpOptions> dhcpOptions;
|
||||
private final StorageBackend<String, Subnet> subnets;
|
||||
private final StorageBackend<String, SecurityGroup> securityGroups;
|
||||
private final StorageBackend<String, SecurityGroupRule> securityGroupRules;
|
||||
@@ -562,7 +566,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
storageFactory.create("ec2", "ec2-transit-gateway-peering-attachments.json",
|
||||
new TypeReference<Map<String, TransitGatewayPeeringAttachment>>() {}),
|
||||
storageFactory.create("ec2", "ec2-egress-only-internet-gateways.json",
|
||||
new TypeReference<Map<String, EgressOnlyInternetGateway>>() {}));
|
||||
new TypeReference<Map<String, EgressOnlyInternetGateway>>() {}),
|
||||
storageFactory.create("ec2", "ec2-dhcp-options.json",
|
||||
new TypeReference<Map<String, DhcpOptions>>() {}));
|
||||
}
|
||||
|
||||
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
|
||||
@@ -589,13 +595,46 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
StorageBackend<String, NetworkAcl> networkAcls,
|
||||
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
|
||||
StorageBackend<String, List<Tag>> tags) {
|
||||
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
|
||||
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
|
||||
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
|
||||
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags, new InMemoryStorage<>());
|
||||
}
|
||||
|
||||
// Package-private for persistence tests that need the DHCP store to survive a service restart.
|
||||
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
Ec2PortForwardManager portForwardManager,
|
||||
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
|
||||
Ec2InstanceTypeCatalog instanceTypeCatalog,
|
||||
StorageBackend<String, Vpc> vpcs,
|
||||
StorageBackend<String, Subnet> subnets,
|
||||
StorageBackend<String, SecurityGroup> securityGroups,
|
||||
StorageBackend<String, SecurityGroupRule> securityGroupRules,
|
||||
StorageBackend<String, InternetGateway> internetGateways,
|
||||
StorageBackend<String, RouteTable> routeTables,
|
||||
StorageBackend<String, KeyPair> keyPairs,
|
||||
StorageBackend<String, Address> addresses,
|
||||
StorageBackend<String, Instance> instances,
|
||||
StorageBackend<String, Volume> volumes,
|
||||
StorageBackend<String, Image> registeredImages,
|
||||
StorageBackend<String, Snapshot> snapshots,
|
||||
StorageBackend<String, LaunchTemplate> launchTemplates,
|
||||
StorageBackend<String, VpcEndpoint> vpcEndpoints,
|
||||
StorageBackend<String, NatGateway> natGateways,
|
||||
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
|
||||
StorageBackend<String, NetworkAcl> networkAcls,
|
||||
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
|
||||
StorageBackend<String, List<Tag>> tags,
|
||||
StorageBackend<String, DhcpOptions> dhcpOptions) {
|
||||
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
|
||||
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
|
||||
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
|
||||
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), null);
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), dhcpOptions);
|
||||
}
|
||||
|
||||
// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its
|
||||
@@ -814,6 +853,56 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
StorageBackend<String, Host> hosts,
|
||||
StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments,
|
||||
StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways) {
|
||||
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
|
||||
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
|
||||
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
|
||||
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
|
||||
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
|
||||
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,
|
||||
networkInterfaces, capacityReservations, volumeModifications,
|
||||
requestContextInstance, iamService, volumeBlockDeviceManager, hosts,
|
||||
transitGatewayPeeringAttachments, egressOnlyInternetGateways, new InMemoryStorage<>());
|
||||
}
|
||||
|
||||
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
Ec2PortForwardManager portForwardManager,
|
||||
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
|
||||
Ec2InstanceTypeCatalog instanceTypeCatalog,
|
||||
StorageBackend<String, Vpc> vpcs,
|
||||
StorageBackend<String, Subnet> subnets,
|
||||
StorageBackend<String, SecurityGroup> securityGroups,
|
||||
StorageBackend<String, SecurityGroupRule> securityGroupRules,
|
||||
StorageBackend<String, InternetGateway> internetGateways,
|
||||
StorageBackend<String, RouteTable> routeTables,
|
||||
StorageBackend<String, KeyPair> keyPairs,
|
||||
StorageBackend<String, Address> addresses,
|
||||
StorageBackend<String, Instance> instances,
|
||||
StorageBackend<String, Volume> volumes,
|
||||
StorageBackend<String, Image> registeredImages,
|
||||
StorageBackend<String, Snapshot> snapshots,
|
||||
StorageBackend<String, LaunchTemplate> launchTemplates,
|
||||
StorageBackend<String, VpcEndpoint> vpcEndpoints,
|
||||
StorageBackend<String, NatGateway> natGateways,
|
||||
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
|
||||
StorageBackend<String, NetworkAcl> networkAcls,
|
||||
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
|
||||
StorageBackend<String, List<Tag>> tags,
|
||||
StorageBackend<String, TransitGateway> transitGateways,
|
||||
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
|
||||
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,
|
||||
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
|
||||
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
|
||||
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,
|
||||
StorageBackend<String, NetworkInterface> networkInterfaces,
|
||||
StorageBackend<String, CapacityReservation> capacityReservations,
|
||||
StorageBackend<String, VolumeModification> volumeModifications,
|
||||
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
|
||||
IamService iamService,
|
||||
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
|
||||
StorageBackend<String, Host> hosts,
|
||||
StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments,
|
||||
StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways,
|
||||
StorageBackend<String, DhcpOptions> dhcpOptions) {
|
||||
this.hosts = hosts;
|
||||
this.egressOnlyInternetGateways = egressOnlyInternetGateways;
|
||||
this.transitGatewayPeeringAttachments = transitGatewayPeeringAttachments;
|
||||
@@ -828,6 +917,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
this.imageCatalog = imageCatalog;
|
||||
this.instanceTypeCatalog = instanceTypeCatalog;
|
||||
this.vpcs = vpcs;
|
||||
this.dhcpOptions = dhcpOptions;
|
||||
this.subnets = subnets;
|
||||
this.securityGroups = securityGroups;
|
||||
this.securityGroupRules = securityGroupRules;
|
||||
@@ -1307,6 +1397,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (!seededAccountRegions.add(seedScope)) {
|
||||
return;
|
||||
}
|
||||
String defaultOptionsId = "dopt-default";
|
||||
if (dhcpOptions.get(key(region, defaultOptionsId)).isEmpty()) {
|
||||
DhcpOptions defaultOptions = new DhcpOptions();
|
||||
defaultOptions.setDhcpOptionsId(defaultOptionsId);
|
||||
defaultOptions.setRegion(region);
|
||||
defaultOptions.setOwnerId(ownerAccountId);
|
||||
defaultOptions.setConfigurations(List.of(
|
||||
new DhcpConfiguration("domain-name", List.of(AwsRegions.ec2PrivateDnsDomain(region))),
|
||||
new DhcpConfiguration("domain-name-servers", List.of("AmazonProvidedDNS")),
|
||||
new DhcpConfiguration("ipv6-address-preferred-lease-time", List.of("140"))));
|
||||
dhcpOptions.put(key(region, defaultOptionsId), defaultOptions);
|
||||
}
|
||||
// Already provisioned in a previous run and reloaded from persistent storage: the default
|
||||
// VPC (and everything else) is present, so don't re-seed and create duplicates (#1297).
|
||||
if (!vpcs.scan(k -> k.startsWith(region + "::")).isEmpty()) {
|
||||
@@ -5754,6 +5856,185 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
// ─── VPCs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public DhcpOptions createDhcpOptions(String region, List<DhcpConfiguration> configurations) {
|
||||
if (configurations == null || configurations.isEmpty()) {
|
||||
throw new AwsException("MissingParameter", "DhcpConfiguration is required", 400);
|
||||
}
|
||||
Set<String> keys = Set.of("domain-name", "domain-name-servers", "ntp-servers",
|
||||
"netbios-name-servers", "netbios-node-type", "ipv6-address-preferred-lease-time");
|
||||
Set<String> seen = new HashSet<>();
|
||||
List<DhcpConfiguration> validated = new ArrayList<>();
|
||||
for (DhcpConfiguration configuration : configurations) {
|
||||
if (configuration.getKey() == null || !keys.contains(configuration.getKey())
|
||||
|| !seen.add(configuration.getKey()) || configuration.getValues() == null
|
||||
|| configuration.getValues().isEmpty()
|
||||
|| configuration.getValues().stream().anyMatch(value -> value == null || value.isBlank())) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid DHCP configuration", 400);
|
||||
}
|
||||
String optionKey = configuration.getKey();
|
||||
List<String> values = configuration.getValues();
|
||||
if (Set.of("domain-name-servers", "ntp-servers", "netbios-name-servers").contains(optionKey)) {
|
||||
values = values.stream().flatMap(value -> Arrays.stream(value.split(",", -1)))
|
||||
.map(String::trim).toList();
|
||||
}
|
||||
if (!validDhcpValues(optionKey, values)) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid value for DHCP option " + optionKey, 400);
|
||||
}
|
||||
validated.add(new DhcpConfiguration(optionKey, List.copyOf(values)));
|
||||
}
|
||||
DhcpOptions options = new DhcpOptions();
|
||||
options.setDhcpOptionsId("dopt-" + randomHex(17));
|
||||
options.setRegion(region);
|
||||
options.setOwnerId(callerAccountId());
|
||||
options.setConfigurations(validated);
|
||||
dhcpOptions.put(key(region, options.getDhcpOptionsId()), options);
|
||||
return options;
|
||||
}
|
||||
|
||||
private boolean validDhcpValues(String optionKey, List<String> values) {
|
||||
if (values.isEmpty() || values.stream().anyMatch(String::isBlank)) {
|
||||
return false;
|
||||
}
|
||||
return switch (optionKey) {
|
||||
case "domain-name-servers" -> values.size() <= 4 &&
|
||||
(values.equals(List.of("AmazonProvidedDNS")) || values.stream().allMatch(this::isLiteralIp));
|
||||
case "ntp-servers" -> values.size() <= 8 && values.stream().allMatch(this::isLiteralIp)
|
||||
&& values.stream().filter(value -> !value.contains(":")).count() <= 4
|
||||
&& values.stream().filter(value -> value.contains(":")).count() <= 4;
|
||||
case "netbios-name-servers" -> values.size() <= 4 && values.stream().allMatch(this::isLiteralIp);
|
||||
case "netbios-node-type" -> values.size() == 1 && Set.of("1", "2", "4", "8").contains(values.getFirst());
|
||||
case "ipv6-address-preferred-lease-time" -> values.size() == 1 && validIpv6LeaseTime(values.getFirst());
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isLiteralIp(String value) {
|
||||
try {
|
||||
InetAddress.ofLiteral(value);
|
||||
return true;
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean validIpv6LeaseTime(String value) {
|
||||
try {
|
||||
long seconds = Long.parseLong(value);
|
||||
return seconds >= 140 && seconds <= Integer.MAX_VALUE;
|
||||
} catch (NumberFormatException invalid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public PaginatedResult<DhcpOptions> describeDhcpOptions(String region, List<String> ids,
|
||||
List<Map.Entry<String, List<String>>> filters, int maxResults, String nextToken) {
|
||||
ensureDefaultResources(region);
|
||||
requireSupportedFilters(filterNames(filters), Set.of("dhcp-options-id", "owner-id", "key", "value",
|
||||
"tag-key", "tag-value"));
|
||||
if (maxResults != 0 && (maxResults < 5 || maxResults > 1000)) {
|
||||
throw new AwsException("InvalidMaxResults", "MaxResults must be between 5 and 1000", 400);
|
||||
}
|
||||
if (maxResults != 0 && !ids.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"DhcpOptionsId cannot be used with MaxResults", 400);
|
||||
}
|
||||
String afterId = decodeDhcpOptionsToken(nextToken);
|
||||
List<DhcpOptions> all = new ArrayList<>(dhcpOptions.scan(k -> k.startsWith(region + "::")));
|
||||
all.sort(Comparator.comparing(DhcpOptions::getDhcpOptionsId));
|
||||
for (String id : ids) {
|
||||
getRequiredDhcpOptions(region, id);
|
||||
}
|
||||
List<DhcpOptions> matching = all.stream()
|
||||
.filter(options -> ids.isEmpty() || ids.contains(options.getDhcpOptionsId()))
|
||||
.filter(options -> filters.stream().allMatch(filter -> matchesDhcpOptionsFilter(region, options, filter)))
|
||||
.filter(options -> afterId == null || options.getDhcpOptionsId().compareTo(afterId) > 0)
|
||||
.toList();
|
||||
int end = maxResults == 0 ? matching.size() : Math.min(matching.size(), maxResults);
|
||||
return new PaginatedResult<>(matching.subList(0, end),
|
||||
end < matching.size() ? encodeDhcpOptionsToken(matching.get(end - 1).getDhcpOptionsId()) : null);
|
||||
}
|
||||
|
||||
private String encodeDhcpOptionsToken(String lastId) {
|
||||
return Base64.getEncoder().encodeToString(lastId.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private String decodeDhcpOptionsToken(String token) {
|
||||
if (token == null || token.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String id = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
|
||||
if (!id.matches("dopt-(default|[0-9a-f]{17})")) {
|
||||
throw new IllegalArgumentException("Invalid DHCP options cursor");
|
||||
}
|
||||
return id;
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid NextToken", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matchesDhcpOptionsFilter(String region, DhcpOptions options,
|
||||
Map.Entry<String, List<String>> filter) {
|
||||
List<String> values = filter.getValue();
|
||||
String name = filter.getKey();
|
||||
List<Tag> resourceTags = resourceTags(region, options.getDhcpOptionsId());
|
||||
if (name.startsWith("tag:")) {
|
||||
return resourceTags.stream().anyMatch(tag -> name.substring(4).equals(tag.getKey())
|
||||
&& matchesFilterValue(values, tag.getValue()));
|
||||
}
|
||||
return switch (name) {
|
||||
case "dhcp-options-id" -> matchesFilterValue(values, options.getDhcpOptionsId());
|
||||
case "owner-id" -> matchesFilterValue(values, options.getOwnerId());
|
||||
case "key" -> options.getConfigurations().stream()
|
||||
.anyMatch(configuration -> matchesFilterValue(values, configuration.getKey()));
|
||||
case "value" -> options.getConfigurations().stream()
|
||||
.flatMap(configuration -> configuration.getValues().stream())
|
||||
.anyMatch(value -> matchesFilterValue(values, value));
|
||||
case "tag-key" -> resourceTags.stream().anyMatch(tag -> matchesFilterValue(values, tag.getKey()));
|
||||
case "tag-value" -> resourceTags.stream().anyMatch(tag -> matchesFilterValue(values, tag.getValue()));
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public void associateDhcpOptions(String region, String dhcpOptionsId, String vpcId) {
|
||||
if (dhcpOptionsId == null || dhcpOptionsId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "DhcpOptionsId is required", 400);
|
||||
}
|
||||
if (vpcId == null || vpcId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "VpcId is required", 400);
|
||||
}
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
Vpc vpc = getRequiredVpc(region, vpcId);
|
||||
if (!"default".equals(dhcpOptionsId)) {
|
||||
getRequiredDhcpOptions(region, dhcpOptionsId);
|
||||
}
|
||||
vpc.setDhcpOptionsId(dhcpOptionsId);
|
||||
vpcs.put(key(region, vpcId), vpc);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteDhcpOptions(String region, String dhcpOptionsId) {
|
||||
if (dhcpOptionsId == null || dhcpOptionsId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "DhcpOptionsId is required", 400);
|
||||
}
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
getRequiredDhcpOptions(region, dhcpOptionsId);
|
||||
if (vpcs.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.anyMatch(vpc -> dhcpOptionsId.equals(vpc.getDhcpOptionsId()))) {
|
||||
throw new AwsException("DependencyViolation",
|
||||
"The DHCP options set is associated with a VPC", 400);
|
||||
}
|
||||
dhcpOptions.delete(key(region, dhcpOptionsId));
|
||||
removeTags(region, dhcpOptionsId);
|
||||
}
|
||||
}
|
||||
|
||||
private DhcpOptions getRequiredDhcpOptions(String region, String dhcpOptionsId) {
|
||||
return dhcpOptions.get(key(region, dhcpOptionsId))
|
||||
.orElseThrow(() -> new AwsException("InvalidDhcpOptionsID.NotFound",
|
||||
"The DHCP options ID '" + dhcpOptionsId + "' does not exist", 400));
|
||||
}
|
||||
|
||||
public Vpc createVpc(String region, String cidrBlock, boolean isDefault) {
|
||||
return createVpc(region, cidrBlock, isDefault, false);
|
||||
}
|
||||
@@ -9556,6 +9837,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
switch (prefix.group(1)) {
|
||||
case "i" -> getRequiredInstance(region, resourceId);
|
||||
case "vpc" -> getRequiredVpc(region, resourceId);
|
||||
case "dopt" -> getRequiredDhcpOptions(region, resourceId);
|
||||
case "subnet" -> requireSubnet(region, resourceId);
|
||||
case "sg" -> getRequiredSecurityGroup(region, resourceId);
|
||||
case "sgr" -> requireFound(!describeSecurityGroupRules(region, List.of(), List.of(resourceId)).isEmpty(),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class DhcpConfiguration {
|
||||
private String key;
|
||||
private List<String> values = new ArrayList<>();
|
||||
|
||||
public DhcpConfiguration() {}
|
||||
|
||||
public DhcpConfiguration(String key, List<String> values) {
|
||||
this.key = key;
|
||||
this.values = new ArrayList<>(values);
|
||||
}
|
||||
|
||||
public String getKey() { return key; }
|
||||
public void setKey(String key) { this.key = key; }
|
||||
public List<String> getValues() { return values; }
|
||||
public void setValues(List<String> values) { this.values = values; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class DhcpOptions {
|
||||
private String dhcpOptionsId;
|
||||
private String ownerId;
|
||||
private String region;
|
||||
private List<DhcpConfiguration> configurations = new ArrayList<>();
|
||||
|
||||
public DhcpOptions() {}
|
||||
|
||||
public String getDhcpOptionsId() { return dhcpOptionsId; }
|
||||
public void setDhcpOptionsId(String dhcpOptionsId) { this.dhcpOptionsId = dhcpOptionsId; }
|
||||
public String getOwnerId() { return ownerId; }
|
||||
public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
public List<DhcpConfiguration> getConfigurations() { return configurations; }
|
||||
public void setConfigurations(List<DhcpConfiguration> configurations) { this.configurations = configurations; }
|
||||
}
|
||||
Reference in new issue
Block a user