mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
Add EC2 provisioning primitives (#1252)
* feat(ec2): load AMI catalog metadata * feat(ec2): add Ubuntu 24.04 AMI metadata * feat(ec2): add launch template APIs * feat(ec2): add launch template version APIs * feat(ec2): add VPC endpoint CRUD * feat(ec2): add NAT gateways and instance offerings * fix(ec2): add t4g.medium instance offering * fix(ec2): preserve launch template version data * fix(ec2): align subnet helper references * fix(ec2): keep VPC endpoint services empty
This commit is contained in:
1 parent
6e4087b0f4
commit
f9c305b7c6
15 files changed
+1928
-90
No files matched your search
@@ -110,6 +110,7 @@ public class AwsQueryController {
|
||||
"CreateLaunchConfiguration", "DescribeLaunchConfigurations", "DeleteLaunchConfiguration",
|
||||
"CreateAutoScalingGroup", "UpdateAutoScalingGroup", "DeleteAutoScalingGroup",
|
||||
"DescribeAutoScalingGroups", "SetDesiredCapacity",
|
||||
"CreateOrUpdateTags", "DeleteTags",
|
||||
"DescribeAutoScalingInstances", "AttachInstances", "DetachInstances",
|
||||
"TerminateInstanceInAutoScalingGroup",
|
||||
"AttachLoadBalancerTargetGroups", "DetachLoadBalancerTargetGroups",
|
||||
@@ -141,7 +142,7 @@ public class AwsQueryController {
|
||||
"RunInstances", "DescribeInstances", "TerminateInstances", "StartInstances", "StopInstances",
|
||||
"RebootInstances", "DescribeInstanceStatus", "DescribeInstanceAttribute", "ModifyInstanceAttribute",
|
||||
"CreateVpc", "DescribeVpcs", "DeleteVpc", "ModifyVpcAttribute", "DescribeVpcAttribute",
|
||||
"DescribeVpcEndpointServices",
|
||||
"DescribeVpcEndpointServices", "CreateVpcEndpoint", "DescribeVpcEndpoints", "DeleteVpcEndpoints",
|
||||
"CreateDefaultVpc", "AssociateVpcCidrBlock", "DisassociateVpcCidrBlock",
|
||||
"CreateSubnet", "DescribeSubnets", "DeleteSubnet", "ModifySubnetAttribute",
|
||||
"CreateSecurityGroup", "DescribeSecurityGroups", "DeleteSecurityGroup",
|
||||
@@ -156,11 +157,14 @@ public class AwsQueryController {
|
||||
"AttachInternetGateway", "DetachInternetGateway",
|
||||
"CreateRouteTable", "DescribeRouteTables", "DeleteRouteTable",
|
||||
"AssociateRouteTable", "DisassociateRouteTable", "CreateRoute", "DeleteRoute",
|
||||
"CreateNatGateway", "DescribeNatGateways", "DeleteNatGateway",
|
||||
"AllocateAddress", "AssociateAddress", "DisassociateAddress", "ReleaseAddress", "DescribeAddresses",
|
||||
"DescribeAddressesAttribute",
|
||||
"DescribeIamInstanceProfileAssociations",
|
||||
"DescribeAvailabilityZones", "DescribeRegions", "DescribeAccountAttributes",
|
||||
"DescribeInstanceTypes",
|
||||
"DescribeInstanceTypes", "DescribeInstanceTypeOfferings",
|
||||
"CreateLaunchTemplate", "CreateLaunchTemplateVersion", "DescribeLaunchTemplates", "DescribeLaunchTemplateVersions",
|
||||
"ModifyLaunchTemplate", "DeleteLaunchTemplate",
|
||||
"DescribeNetworkInterfaces"
|
||||
);
|
||||
|
||||
|
||||
@@ -1,55 +1,43 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Resolves EC2 AMI IDs to Docker image URIs.
|
||||
*
|
||||
* Floci-local AMI IDs (e.g. "ami-amazonlinux2023") map to public Docker images.
|
||||
* Real AWS AMI IDs (e.g. "ami-0abc12345678") fall back to amazonlinux:2023.
|
||||
* Real AWS AMI IDs (e.g. "ami-0abc12345678") fall back to the catalog default.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AmiImageResolver {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AmiImageResolver.class);
|
||||
|
||||
private static final String DEFAULT_IMAGE = "public.ecr.aws/amazonlinux/amazonlinux:2023";
|
||||
private final Ec2ImageCatalog imageCatalog;
|
||||
|
||||
private static final Map<String, String> BUILTIN_MAPPINGS = Map.ofEntries(
|
||||
Map.entry("ami-amazonlinux2023", "public.ecr.aws/amazonlinux/amazonlinux:2023"),
|
||||
Map.entry("ami-amazonlinux2", "public.ecr.aws/amazonlinux/amazonlinux:2"),
|
||||
Map.entry("ami-ubuntu2204", "public.ecr.aws/docker/library/ubuntu:22.04"),
|
||||
Map.entry("ami-ubuntu2004", "public.ecr.aws/docker/library/ubuntu:20.04"),
|
||||
Map.entry("ami-debian12", "public.ecr.aws/docker/library/debian:12"),
|
||||
Map.entry("ami-alpine", "public.ecr.aws/docker/library/alpine:latest")
|
||||
);
|
||||
@Inject
|
||||
public AmiImageResolver(Ec2ImageCatalog imageCatalog) {
|
||||
this.imageCatalog = imageCatalog;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an AMI ID to a Docker image URI.
|
||||
* Falls back to Amazon Linux 2023 for unrecognised IDs.
|
||||
* Falls back to the catalog default image for unrecognised IDs.
|
||||
*/
|
||||
public String resolve(String imageId) {
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
LOG.warnv("No imageId provided; using default image {0}", DEFAULT_IMAGE);
|
||||
return DEFAULT_IMAGE;
|
||||
LOG.warnv("No imageId provided; using default image {0}", imageCatalog.defaultDockerImage());
|
||||
return imageCatalog.defaultDockerImage();
|
||||
}
|
||||
|
||||
String mapped = BUILTIN_MAPPINGS.get(imageId);
|
||||
if (mapped != null) {
|
||||
return mapped;
|
||||
}
|
||||
|
||||
LOG.warnv("Unknown AMI ID {0}; falling back to default image {1}", imageId, DEFAULT_IMAGE);
|
||||
return DEFAULT_IMAGE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the pre-seeded AMI catalogue entries for DescribeImages.
|
||||
*/
|
||||
public static Map<String, String> builtinMappings() {
|
||||
return BUILTIN_MAPPINGS;
|
||||
return imageCatalog.findByIdOrAlias(imageId)
|
||||
.map(image -> image.dockerImage)
|
||||
.orElseGet(() -> {
|
||||
LOG.warnv("Unknown AMI ID {0}; falling back to default image {1}",
|
||||
imageId, imageCatalog.defaultDockerImage());
|
||||
return imageCatalog.defaultDockerImage();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.model.Image;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
@ApplicationScoped
|
||||
public class Ec2ImageCatalog {
|
||||
|
||||
private static final String CATALOG_RESOURCE_NAME = "ec2/image-catalog.yaml";
|
||||
private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
|
||||
|
||||
private final String defaultDockerImage;
|
||||
private final List<CatalogImage> images;
|
||||
private final Map<String, CatalogImage> imagesByIdOrAlias;
|
||||
|
||||
public Ec2ImageCatalog() {
|
||||
this(readResource(CATALOG_RESOURCE_NAME, Catalog.class));
|
||||
}
|
||||
|
||||
Ec2ImageCatalog(Catalog catalog) {
|
||||
this.defaultDockerImage = require(catalog.defaultDockerImage, "defaultDockerImage");
|
||||
this.images = List.copyOf(catalog.images == null ? List.of() : catalog.images);
|
||||
if (this.images.isEmpty()) {
|
||||
throw new IllegalStateException("EC2 image catalog has no images: " + CATALOG_RESOURCE_NAME);
|
||||
}
|
||||
this.imagesByIdOrAlias = indexImages(this.images);
|
||||
}
|
||||
|
||||
public String defaultDockerImage() {
|
||||
return defaultDockerImage;
|
||||
}
|
||||
|
||||
public List<CatalogImage> images() {
|
||||
return images;
|
||||
}
|
||||
|
||||
public Optional<CatalogImage> findByIdOrAlias(String imageId) {
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(imagesByIdOrAlias.get(imageId));
|
||||
}
|
||||
|
||||
private static <T> T readResource(String resourceName, Class<T> type) {
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
try (InputStream input = loader.getResourceAsStream(resourceName)) {
|
||||
if (input == null) {
|
||||
throw new IllegalStateException("Missing EC2 image catalog resource: " + resourceName);
|
||||
}
|
||||
return YAML_MAPPER.readValue(input, type);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Failed to load EC2 image catalog resource: " + resourceName, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, CatalogImage> indexImages(List<CatalogImage> images) {
|
||||
Map<String, CatalogImage> index = new LinkedHashMap<>();
|
||||
for (CatalogImage image : images) {
|
||||
addIndexEntry(index, require(image.imageId, "imageId"), image);
|
||||
require(image.dockerImage, "dockerImage");
|
||||
require(image.name, "name");
|
||||
require(image.description, "description");
|
||||
require(image.architecture, "architecture");
|
||||
require(image.creationDate, "creationDate");
|
||||
|
||||
for (String alias : image.aliases()) {
|
||||
addIndexEntry(index, alias, image);
|
||||
}
|
||||
}
|
||||
return Map.copyOf(index);
|
||||
}
|
||||
|
||||
private static void addIndexEntry(Map<String, CatalogImage> index, String imageIdOrAlias, CatalogImage image) {
|
||||
CatalogImage previous = index.putIfAbsent(imageIdOrAlias, image);
|
||||
if (previous != null) {
|
||||
throw new IllegalStateException("Duplicate EC2 image catalog id or alias: " + imageIdOrAlias);
|
||||
}
|
||||
}
|
||||
|
||||
private static String require(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalStateException("EC2 image catalog entry is missing required field: " + field);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public static final class Catalog {
|
||||
public String defaultDockerImage;
|
||||
public List<CatalogImage> images = List.of();
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public static final class CatalogImage {
|
||||
public String imageId;
|
||||
public List<String> aliases = List.of();
|
||||
public String dockerImage;
|
||||
public String name;
|
||||
public String description;
|
||||
public String state;
|
||||
public String ownerId;
|
||||
public Boolean publicImage;
|
||||
public String architecture;
|
||||
public String rootDeviceType;
|
||||
public String rootDeviceName;
|
||||
public String virtualizationType;
|
||||
public String hypervisor;
|
||||
public String platform;
|
||||
public String imageOwnerAlias;
|
||||
public String creationDate;
|
||||
public Boolean advertised;
|
||||
|
||||
public boolean advertised() {
|
||||
return advertised == null || advertised;
|
||||
}
|
||||
|
||||
public List<String> aliases() {
|
||||
return aliases == null ? List.of() : List.copyOf(aliases);
|
||||
}
|
||||
|
||||
public List<String> idsAndAliases() {
|
||||
List<String> ids = new ArrayList<>();
|
||||
ids.add(imageId);
|
||||
ids.addAll(aliases());
|
||||
return ids;
|
||||
}
|
||||
|
||||
public boolean matchesIdOrAlias(List<String> candidates) {
|
||||
if (candidates == null || candidates.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (String id : idsAndAliases()) {
|
||||
if (candidates.contains(id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean matchesOwner(List<String> owners) {
|
||||
if (owners == null || owners.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Image image = toImage();
|
||||
return owners.contains(image.getOwnerId()) || owners.contains(image.getImageOwnerAlias());
|
||||
}
|
||||
|
||||
public Image toImage() {
|
||||
Image image = new Image();
|
||||
image.setImageId(imageId);
|
||||
image.setName(name);
|
||||
image.setDescription(description);
|
||||
if (state != null) {
|
||||
image.setState(state);
|
||||
}
|
||||
if (ownerId != null) {
|
||||
image.setOwnerId(ownerId);
|
||||
}
|
||||
if (publicImage != null) {
|
||||
image.setPublic(publicImage);
|
||||
}
|
||||
image.setArchitecture(architecture);
|
||||
if (rootDeviceType != null) {
|
||||
image.setRootDeviceType(rootDeviceType);
|
||||
}
|
||||
if (rootDeviceName != null) {
|
||||
image.setRootDeviceName(rootDeviceName);
|
||||
}
|
||||
if (virtualizationType != null) {
|
||||
image.setVirtualizationType(virtualizationType);
|
||||
}
|
||||
if (hypervisor != null) {
|
||||
image.setHypervisor(hypervisor);
|
||||
}
|
||||
image.setPlatform(platform);
|
||||
if (imageOwnerAlias != null) {
|
||||
image.setImageOwnerAlias(imageOwnerAlias);
|
||||
}
|
||||
image.setCreationDate(creationDate);
|
||||
return image;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,13 @@ import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
@ApplicationScoped
|
||||
public class Ec2QueryHandler {
|
||||
@@ -53,6 +56,9 @@ public class Ec2QueryHandler {
|
||||
case "ModifyVpcAttribute" -> handleModifyVpcAttribute(params, region);
|
||||
case "DescribeVpcAttribute" -> handleDescribeVpcAttribute(params, region);
|
||||
case "DescribeVpcEndpointServices" -> handleDescribeVpcEndpointServices(params, region);
|
||||
case "CreateVpcEndpoint" -> handleCreateVpcEndpoint(params, region);
|
||||
case "DescribeVpcEndpoints" -> handleDescribeVpcEndpoints(params, region);
|
||||
case "DeleteVpcEndpoints" -> handleDeleteVpcEndpoints(params, region);
|
||||
case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);
|
||||
case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);
|
||||
case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);
|
||||
@@ -100,6 +106,10 @@ public class Ec2QueryHandler {
|
||||
case "DisassociateRouteTable" -> handleDisassociateRouteTable(params, region);
|
||||
case "CreateRoute" -> handleCreateRoute(params, region);
|
||||
case "DeleteRoute" -> handleDeleteRoute(params, region);
|
||||
// NAT Gateways
|
||||
case "CreateNatGateway" -> handleCreateNatGateway(params, region);
|
||||
case "DescribeNatGateways" -> handleDescribeNatGateways(params, region);
|
||||
case "DeleteNatGateway" -> handleDeleteNatGateway(params, region);
|
||||
// Elastic IPs
|
||||
case "AllocateAddress" -> handleAllocateAddress(params, region);
|
||||
case "AssociateAddress" -> handleAssociateAddress(params, region);
|
||||
@@ -113,6 +123,14 @@ public class Ec2QueryHandler {
|
||||
case "DescribeAccountAttributes" -> handleDescribeAccountAttributes(params, region);
|
||||
// Instance Types
|
||||
case "DescribeInstanceTypes" -> handleDescribeInstanceTypes(params, region);
|
||||
case "DescribeInstanceTypeOfferings" -> handleDescribeInstanceTypeOfferings(params, region);
|
||||
// Launch Templates
|
||||
case "CreateLaunchTemplate" -> handleCreateLaunchTemplate(params, region);
|
||||
case "CreateLaunchTemplateVersion" -> handleCreateLaunchTemplateVersion(params, region);
|
||||
case "DescribeLaunchTemplates" -> handleDescribeLaunchTemplates(params, region);
|
||||
case "DescribeLaunchTemplateVersions" -> handleDescribeLaunchTemplateVersions(params, region);
|
||||
case "ModifyLaunchTemplate" -> handleModifyLaunchTemplate(params, region);
|
||||
case "DeleteLaunchTemplate" -> handleDeleteLaunchTemplate(params, region);
|
||||
// Network Interfaces
|
||||
case "DescribeNetworkInterfaces" -> handleDescribeNetworkInterfaces(params, region);
|
||||
// Volumes
|
||||
@@ -209,6 +227,23 @@ public class Ec2QueryHandler {
|
||||
return perms;
|
||||
}
|
||||
|
||||
private List<Tag> parseTagsForResource(MultivaluedMap<String, String> p, String resourceType) {
|
||||
List<Tag> tags = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
|
||||
if (resType == null) break;
|
||||
if (resourceType.equals(resType)) {
|
||||
for (int j = 1; ; j++) {
|
||||
String key = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
|
||||
if (key == null) break;
|
||||
String value = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
|
||||
tags.add(new Tag(key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private Response xmlResponse(String xml) {
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
@@ -239,7 +274,7 @@ public class Ec2QueryHandler {
|
||||
String userDataEncoded = p.getFirst("UserData");
|
||||
String userData = null;
|
||||
if (userDataEncoded != null && !userDataEncoded.isBlank()) {
|
||||
userData = new String(Base64.getDecoder().decode(userDataEncoded), StandardCharsets.UTF_8);
|
||||
userData = decodeUserData(userDataEncoded);
|
||||
}
|
||||
|
||||
// IamInstanceProfile
|
||||
@@ -600,12 +635,58 @@ public class Ec2QueryHandler {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeVpcEndpointServicesResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("serviceNameSet").end("serviceNameSet")
|
||||
.start("serviceDetailSet").end("serviceDetailSet")
|
||||
.start("serviceNameSet")
|
||||
.end("serviceNameSet")
|
||||
.start("serviceDetailSet")
|
||||
.end("serviceDetailSet")
|
||||
.end("DescribeVpcEndpointServicesResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleCreateVpcEndpoint(MultivaluedMap<String, String> p, String region) {
|
||||
VpcEndpoint endpoint = service.createVpcEndpoint(
|
||||
region,
|
||||
p.getFirst("VpcId"),
|
||||
p.getFirst("ServiceName"),
|
||||
p.getFirst("VpcEndpointType"),
|
||||
getList(p, "RouteTableId"),
|
||||
getList(p, "SubnetId"),
|
||||
getList(p, "SecurityGroupId"),
|
||||
parseTagsForResource(p, "vpc-endpoint"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateVpcEndpointResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("vpcEndpoint").raw(vpcEndpointXml(endpoint)).end("vpcEndpoint")
|
||||
.end("CreateVpcEndpointResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDescribeVpcEndpoints(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> endpointIds = getList(p, "VpcEndpointId");
|
||||
Map<String, List<String>> filters = getFilters(p);
|
||||
List<VpcEndpoint> endpoints = service.describeVpcEndpoints(region, endpointIds, filters);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeVpcEndpointsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("vpcEndpointSet");
|
||||
for (VpcEndpoint endpoint : endpoints) {
|
||||
xml.start("item").raw(vpcEndpointXml(endpoint)).end("item");
|
||||
}
|
||||
xml.end("vpcEndpointSet").end("DescribeVpcEndpointsResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDeleteVpcEndpoints(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> endpointIds = getList(p, "VpcEndpointId");
|
||||
service.deleteVpcEndpoints(region, endpointIds);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DeleteVpcEndpointsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("unsuccessful").end("unsuccessful")
|
||||
.end("DeleteVpcEndpointsResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleCreateDefaultVpc(MultivaluedMap<String, String> p, String region) {
|
||||
Vpc vpc = service.createDefaultVpc(region);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
@@ -883,7 +964,8 @@ public class Ec2QueryHandler {
|
||||
private Response handleDescribeImages(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> imageIds = getList(p, "ImageId");
|
||||
List<String> owners = getList(p, "Owner");
|
||||
List<Image> images = service.describeImages(region, imageIds, owners);
|
||||
Map<String, List<String>> filters = getFilters(p);
|
||||
List<Image> images = service.describeImages(region, imageIds, owners, filters);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeImagesResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
@@ -1068,6 +1150,48 @@ public class Ec2QueryHandler {
|
||||
return booleanResponse("DeleteRoute");
|
||||
}
|
||||
|
||||
// ─── NAT Gateway handlers ─────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateNatGateway(MultivaluedMap<String, String> p, String region) {
|
||||
NatGateway natGateway = service.createNatGateway(
|
||||
region,
|
||||
p.getFirst("SubnetId"),
|
||||
p.getFirst("AllocationId"),
|
||||
p.getFirst("ConnectivityType"),
|
||||
parseTagsForResource(p, "natgateway"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateNatGatewayResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("natGateway").raw(natGatewayXml(natGateway)).end("natGateway")
|
||||
.end("CreateNatGatewayResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDescribeNatGateways(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> natGatewayIds = getList(p, "NatGatewayId");
|
||||
Map<String, List<String>> filters = getFilters(p);
|
||||
List<NatGateway> natGateways = service.describeNatGateways(region, natGatewayIds, filters);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeNatGatewaysResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("natGatewaySet");
|
||||
for (NatGateway natGateway : natGateways) {
|
||||
xml.start("item").raw(natGatewayXml(natGateway)).end("item");
|
||||
}
|
||||
xml.end("natGatewaySet").end("DescribeNatGatewaysResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDeleteNatGateway(MultivaluedMap<String, String> p, String region) {
|
||||
NatGateway natGateway = service.deleteNatGateway(region, p.getFirst("NatGatewayId"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DeleteNatGatewayResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("natGateway").raw(natGatewayXml(natGateway)).end("natGateway")
|
||||
.end("DeleteNatGatewayResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
// ─── Elastic IP handlers ──────────────────────────────────────────────────
|
||||
|
||||
private Response handleAllocateAddress(MultivaluedMap<String, String> p, String region) {
|
||||
@@ -1223,6 +1347,125 @@ public class Ec2QueryHandler {
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDescribeInstanceTypeOfferings(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> typeNames = getList(p, "InstanceType");
|
||||
Map<String, List<String>> filters = getFilters(p);
|
||||
List<Map<String, String>> offerings = service.describeInstanceTypeOfferings(
|
||||
region, typeNames, p.getFirst("LocationType"), filters);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeInstanceTypeOfferingsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("instanceTypeOfferingSet");
|
||||
for (Map<String, String> offering : offerings) {
|
||||
xml.start("item")
|
||||
.elem("instanceType", offering.get("instanceType"))
|
||||
.elem("locationType", offering.get("locationType"))
|
||||
.elem("location", offering.get("location"))
|
||||
.end("item");
|
||||
}
|
||||
xml.end("instanceTypeOfferingSet").end("DescribeInstanceTypeOfferingsResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
// ─── Launch Template handlers ─────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateLaunchTemplate(MultivaluedMap<String, String> p, String region) {
|
||||
LaunchTemplate launchTemplate = service.createLaunchTemplate(
|
||||
region,
|
||||
p.getFirst("LaunchTemplateName"),
|
||||
p.getFirst("LaunchTemplateData.ImageId"),
|
||||
p.getFirst("LaunchTemplateData.InstanceType"),
|
||||
p.getFirst("LaunchTemplateData.KeyName"),
|
||||
parseLaunchTemplateSecurityGroupIds(p),
|
||||
decodeUserData(p.getFirst("LaunchTemplateData.UserData")),
|
||||
parseTagsForResource(p, "launch-template"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateLaunchTemplateResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("launchTemplate").raw(launchTemplateXml(launchTemplate)).end("launchTemplate")
|
||||
.end("CreateLaunchTemplateResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleCreateLaunchTemplateVersion(MultivaluedMap<String, String> p, String region) {
|
||||
LaunchTemplate launchTemplate = service.createLaunchTemplateVersion(
|
||||
region,
|
||||
p.getFirst("LaunchTemplateId"),
|
||||
p.getFirst("LaunchTemplateName"),
|
||||
p.getFirst("LaunchTemplateData.ImageId"),
|
||||
p.getFirst("LaunchTemplateData.InstanceType"),
|
||||
p.getFirst("LaunchTemplateData.KeyName"),
|
||||
parseLaunchTemplateSecurityGroupIds(p),
|
||||
decodeUserData(p.getFirst("LaunchTemplateData.UserData")),
|
||||
p.getFirst("SourceVersion"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateLaunchTemplateVersionResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("launchTemplateVersion").raw(launchTemplateVersionXml(launchTemplate)).end("launchTemplateVersion")
|
||||
.end("CreateLaunchTemplateVersionResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDescribeLaunchTemplates(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> ids = getList(p, "LaunchTemplateId");
|
||||
List<String> names = getList(p, "LaunchTemplateName");
|
||||
Map<String, List<String>> filters = getFilters(p);
|
||||
List<LaunchTemplate> launchTemplates = service.describeLaunchTemplates(region, ids, names, filters);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeLaunchTemplatesResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("launchTemplates");
|
||||
for (LaunchTemplate launchTemplate : launchTemplates) {
|
||||
xml.start("item").raw(launchTemplateXml(launchTemplate)).end("item");
|
||||
}
|
||||
xml.end("launchTemplates").end("DescribeLaunchTemplatesResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDescribeLaunchTemplateVersions(MultivaluedMap<String, String> p, String region) {
|
||||
String id = p.getFirst("LaunchTemplateId");
|
||||
String name = p.getFirst("LaunchTemplateName");
|
||||
List<LaunchTemplate> launchTemplates = service.describeLaunchTemplateVersions(
|
||||
region,
|
||||
id,
|
||||
name,
|
||||
getList(p, "Versions"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeLaunchTemplateVersionsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("launchTemplateVersionSet");
|
||||
for (LaunchTemplate launchTemplate : launchTemplates) {
|
||||
xml.start("item").raw(launchTemplateVersionXml(launchTemplate)).end("item");
|
||||
}
|
||||
xml.end("launchTemplateVersionSet").end("DescribeLaunchTemplateVersionsResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleModifyLaunchTemplate(MultivaluedMap<String, String> p, String region) {
|
||||
LaunchTemplate launchTemplate = service.modifyLaunchTemplate(
|
||||
region,
|
||||
p.getFirst("LaunchTemplateId"),
|
||||
p.getFirst("LaunchTemplateName"),
|
||||
p.getFirst("DefaultVersion"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ModifyLaunchTemplateResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("launchTemplate").raw(launchTemplateXml(launchTemplate)).end("launchTemplate")
|
||||
.end("ModifyLaunchTemplateResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDeleteLaunchTemplate(MultivaluedMap<String, String> p, String region) {
|
||||
LaunchTemplate launchTemplate = service.deleteLaunchTemplate(
|
||||
region, p.getFirst("LaunchTemplateId"), p.getFirst("LaunchTemplateName"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DeleteLaunchTemplateResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.start("launchTemplate").raw(launchTemplateXml(launchTemplate)).end("launchTemplate")
|
||||
.end("DeleteLaunchTemplateResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
// ─── Network Interface handlers ───────────────────────────────────────────
|
||||
|
||||
private Response handleDescribeNetworkInterfaces(MultivaluedMap<String, String> p, String region) {
|
||||
@@ -1564,6 +1807,143 @@ public class Ec2QueryHandler {
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private String natGatewayXml(NatGateway natGateway) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("natGatewayId", natGateway.getNatGatewayId())
|
||||
.elem("subnetId", natGateway.getSubnetId())
|
||||
.elem("vpcId", natGateway.getVpcId())
|
||||
.elem("state", natGateway.getState())
|
||||
.elem("connectivityType", natGateway.getConnectivityType());
|
||||
if (natGateway.getCreateTime() != null) {
|
||||
xml.elem("createTime", ISO_FMT.format(natGateway.getCreateTime()));
|
||||
}
|
||||
if (natGateway.getAllocationId() != null) {
|
||||
xml.start("natGatewayAddressSet")
|
||||
.start("item")
|
||||
.elem("allocationId", natGateway.getAllocationId())
|
||||
.end("item")
|
||||
.end("natGatewayAddressSet");
|
||||
} else {
|
||||
xml.start("natGatewayAddressSet").end("natGatewayAddressSet");
|
||||
}
|
||||
xml.raw(tagSetXml(natGateway.getTags()));
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private String launchTemplateXml(LaunchTemplate launchTemplate) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("launchTemplateId", launchTemplate.getLaunchTemplateId())
|
||||
.elem("launchTemplateName", launchTemplate.getLaunchTemplateName());
|
||||
if (launchTemplate.getCreateTime() != null) {
|
||||
xml.elem("createTime", ISO_FMT.format(launchTemplate.getCreateTime()));
|
||||
}
|
||||
xml.elem("createdBy", launchTemplate.getCreatedBy())
|
||||
.elem("defaultVersionNumber", launchTemplate.getDefaultVersionNumber())
|
||||
.elem("latestVersionNumber", launchTemplate.getLatestVersionNumber())
|
||||
.raw(tagSetXml(launchTemplate.getTags()));
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private String launchTemplateVersionXml(LaunchTemplate launchTemplate) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("launchTemplateId", launchTemplate.getLaunchTemplateId())
|
||||
.elem("launchTemplateName", launchTemplate.getLaunchTemplateName())
|
||||
.elem("versionNumber", launchTemplate.getLatestVersionNumber())
|
||||
.elem("defaultVersion", String.valueOf(Objects.equals(
|
||||
launchTemplate.getDefaultVersionNumber(), launchTemplate.getLatestVersionNumber())));
|
||||
if (launchTemplate.getCreateTime() != null) {
|
||||
xml.elem("createTime", ISO_FMT.format(launchTemplate.getCreateTime()));
|
||||
}
|
||||
xml.elem("createdBy", launchTemplate.getCreatedBy())
|
||||
.start("launchTemplateData")
|
||||
.elem("imageId", launchTemplate.getImageId())
|
||||
.elem("instanceType", launchTemplate.getInstanceType());
|
||||
if (launchTemplate.getKeyName() != null) {
|
||||
xml.elem("keyName", launchTemplate.getKeyName());
|
||||
}
|
||||
if (launchTemplate.getUserData() != null) {
|
||||
xml.elem("userData", launchTemplate.getUserData());
|
||||
}
|
||||
xml.start("securityGroupIdSet");
|
||||
for (String securityGroupId : launchTemplate.getSecurityGroupIds()) {
|
||||
xml.elem("item", securityGroupId);
|
||||
}
|
||||
xml.end("securityGroupIdSet")
|
||||
.end("launchTemplateData");
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private List<String> parseLaunchTemplateSecurityGroupIds(MultivaluedMap<String, String> p) {
|
||||
LinkedHashSet<String> groups = new LinkedHashSet<>(getList(p, "LaunchTemplateData.SecurityGroupId"));
|
||||
for (int i = 1; ; i++) {
|
||||
boolean sawInterface = false;
|
||||
for (String prefix : List.of(
|
||||
"LaunchTemplateData.NetworkInterface." + i + ".Groups",
|
||||
"LaunchTemplateData.NetworkInterface." + i + ".GroupId",
|
||||
"LaunchTemplateData.NetworkInterface." + i + ".SecurityGroupId")) {
|
||||
List<String> values = getList(p, prefix);
|
||||
if (!values.isEmpty()) {
|
||||
sawInterface = true;
|
||||
groups.addAll(values);
|
||||
}
|
||||
}
|
||||
if (!sawInterface && p.getFirst("LaunchTemplateData.NetworkInterface." + i + ".DeviceIndex") == null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(groups);
|
||||
}
|
||||
|
||||
private String decodeUserData(String userDataEncoded) {
|
||||
if (userDataEncoded == null || userDataEncoded.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getDecoder().decode(userDataEncoded);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData is not valid base64 content.", 400);
|
||||
}
|
||||
if (decoded.length >= 2 && (decoded[0] & 0xff) == 0x1f && (decoded[1] & 0xff) == 0x8b) {
|
||||
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(decoded))) {
|
||||
decoded = gzip.readAllBytes();
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData is not valid gzip content.", 400);
|
||||
}
|
||||
}
|
||||
return new String(decoded, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String vpcEndpointXml(VpcEndpoint endpoint) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("vpcEndpointId", endpoint.getVpcEndpointId())
|
||||
.elem("vpcEndpointType", endpoint.getVpcEndpointType())
|
||||
.elem("vpcId", endpoint.getVpcId())
|
||||
.elem("serviceName", endpoint.getServiceName())
|
||||
.elem("state", endpoint.getState());
|
||||
if (endpoint.getCreationTimestamp() != null) {
|
||||
xml.elem("creationTimestamp", ISO_FMT.format(endpoint.getCreationTimestamp()));
|
||||
}
|
||||
xml.start("routeTableIdSet");
|
||||
for (String routeTableId : endpoint.getRouteTableIds()) {
|
||||
xml.start("item").elem("routeTableId", routeTableId).end("item");
|
||||
}
|
||||
xml.end("routeTableIdSet")
|
||||
.start("subnetIdSet");
|
||||
for (String subnetId : endpoint.getSubnetIds()) {
|
||||
xml.start("item").elem("subnetId", subnetId).end("item");
|
||||
}
|
||||
xml.end("subnetIdSet")
|
||||
.start("groupSet");
|
||||
for (String securityGroupId : endpoint.getSecurityGroupIds()) {
|
||||
xml.start("item").elem("groupId", securityGroupId).end("item");
|
||||
}
|
||||
xml.end("groupSet")
|
||||
.raw(tagSetXml(endpoint.getTags()));
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private String addressXml(Address addr) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("publicIp", addr.getPublicIp())
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -40,6 +41,9 @@ import io.github.hectorvent.floci.services.ec2.model.InternetGatewayAttachment;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpPermission;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpRange;
|
||||
import io.github.hectorvent.floci.services.ec2.model.KeyPair;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Placement;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Route;
|
||||
@@ -53,6 +57,7 @@ import io.github.hectorvent.floci.services.ec2.model.Volume;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VpcCidrBlockAssociation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -67,6 +72,7 @@ public class Ec2Service {
|
||||
private final EmulatorConfig config;
|
||||
private final Ec2ContainerManager containerManager;
|
||||
private final AmiImageResolver amiImageResolver;
|
||||
private final Ec2ImageCatalog imageCatalog;
|
||||
|
||||
// region::id → resource
|
||||
private final Map<String, Vpc> vpcs = new ConcurrentHashMap<>();
|
||||
@@ -79,6 +85,9 @@ public class Ec2Service {
|
||||
private final Map<String, Address> addresses = new ConcurrentHashMap<>();
|
||||
private final Map<String, Instance> instances = new ConcurrentHashMap<>();
|
||||
private final Map<String, Volume> volumes = new ConcurrentHashMap<>();
|
||||
private final Map<String, LaunchTemplate> launchTemplates = new ConcurrentHashMap<>();
|
||||
private final Map<String, VpcEndpoint> vpcEndpoints = new ConcurrentHashMap<>();
|
||||
private final Map<String, NatGateway> natGateways = new ConcurrentHashMap<>();
|
||||
// resourceId → List<Tag>
|
||||
private final Map<String, List<Tag>> tags = new ConcurrentHashMap<>();
|
||||
private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
|
||||
@@ -87,11 +96,12 @@ public class Ec2Service {
|
||||
|
||||
@Inject
|
||||
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
AmiImageResolver amiImageResolver) {
|
||||
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog) {
|
||||
this.accountId = config.defaultAccountId();
|
||||
this.config = config;
|
||||
this.containerManager = containerManager;
|
||||
this.amiImageResolver = amiImageResolver;
|
||||
this.imageCatalog = imageCatalog;
|
||||
}
|
||||
|
||||
// ─── Default resource seeding ──────────────────────────────────────────────
|
||||
@@ -628,6 +638,78 @@ public class Ec2Service {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── VPC Endpoints ────────────────────────────────────────────────────────
|
||||
|
||||
public VpcEndpoint createVpcEndpoint(String region, String vpcId, String serviceName, String endpointType,
|
||||
List<String> routeTableIds, List<String> subnetIds,
|
||||
List<String> securityGroupIds, List<Tag> endpointTags) {
|
||||
ensureDefaultResources(region);
|
||||
getRequiredVpc(region, vpcId);
|
||||
for (String routeTableId : routeTableIds) {
|
||||
getRequiredRouteTable(region, routeTableId);
|
||||
}
|
||||
for (String subnetId : subnetIds) {
|
||||
requireSubnet(region, subnetId);
|
||||
}
|
||||
for (String securityGroupId : securityGroupIds) {
|
||||
getRequiredSecurityGroup(region, securityGroupId);
|
||||
}
|
||||
|
||||
VpcEndpoint endpoint = new VpcEndpoint();
|
||||
endpoint.setVpcEndpointId("vpce-" + randomHex(17));
|
||||
endpoint.setVpcId(vpcId);
|
||||
endpoint.setServiceName(serviceName);
|
||||
endpoint.setVpcEndpointType(endpointType != null && !endpointType.isBlank() ? endpointType : "Gateway");
|
||||
endpoint.setCreationTimestamp(Instant.now());
|
||||
endpoint.setRegion(region);
|
||||
endpoint.setRouteTableIds(new ArrayList<>(routeTableIds));
|
||||
endpoint.setSubnetIds(new ArrayList<>(subnetIds));
|
||||
endpoint.setSecurityGroupIds(new ArrayList<>(securityGroupIds));
|
||||
if (endpointTags != null && !endpointTags.isEmpty()) {
|
||||
endpoint.setTags(new ArrayList<>(endpointTags));
|
||||
tags.put(endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags));
|
||||
}
|
||||
vpcEndpoints.put(key(region, endpoint.getVpcEndpointId()), endpoint);
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public List<VpcEndpoint> describeVpcEndpoints(String region, List<String> endpointIds,
|
||||
Map<String, List<String>> filters) {
|
||||
ensureDefaultResources(region);
|
||||
if (!endpointIds.isEmpty()) {
|
||||
for (String endpointId : endpointIds) {
|
||||
getRequiredVpcEndpoint(region, endpointId);
|
||||
}
|
||||
}
|
||||
return vpcEndpoints.values().stream()
|
||||
.filter(endpoint -> endpoint.getRegion().equals(region))
|
||||
.filter(endpoint -> endpointIds.isEmpty() || endpointIds.contains(endpoint.getVpcEndpointId()))
|
||||
.filter(endpoint -> matchesFilters(endpoint, filters, region))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<VpcEndpoint> deleteVpcEndpoints(String region, List<String> endpointIds) {
|
||||
ensureDefaultResources(region);
|
||||
List<VpcEndpoint> deleted = new ArrayList<>();
|
||||
for (String endpointId : endpointIds) {
|
||||
VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId);
|
||||
endpoint.setState("deleted");
|
||||
vpcEndpoints.remove(key(region, endpointId));
|
||||
tags.remove(endpointId);
|
||||
deleted.add(endpoint);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
private VpcEndpoint getRequiredVpcEndpoint(String region, String endpointId) {
|
||||
VpcEndpoint endpoint = vpcEndpoints.get(key(region, endpointId));
|
||||
if (endpoint == null) {
|
||||
throw new AwsException("InvalidVpcEndpointId.NotFound",
|
||||
"The vpcEndpoint ID '" + endpointId + "' does not exist", 400);
|
||||
}
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
// ─── Subnets ───────────────────────────────────────────────────────────────
|
||||
|
||||
public Subnet createSubnet(String region, String vpcId, String cidrBlock, String availabilityZone) {
|
||||
@@ -923,46 +1005,284 @@ public class Ec2Service {
|
||||
// ─── AMIs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public List<Image> describeImages(String region, List<String> imageIds, List<String> owners) {
|
||||
List<Image> staticImages = new ArrayList<>();
|
||||
return describeImages(region, imageIds, owners, Map.of());
|
||||
}
|
||||
|
||||
Image al2 = new Image();
|
||||
al2.setImageId("ami-0abcdef1234567890");
|
||||
al2.setName("amzn2-ami-hvm-2.0.20230404.0-x86_64-gp2");
|
||||
al2.setDescription("Amazon Linux 2 AMI");
|
||||
al2.setArchitecture("x86_64");
|
||||
al2.setCreationDate("2023-04-04T00:00:00.000Z");
|
||||
staticImages.add(al2);
|
||||
|
||||
Image al2023 = new Image();
|
||||
al2023.setImageId("ami-0abcdef1234567891");
|
||||
al2023.setName("al2023-ami-2023.0.20230315.0-kernel-6.1-x86_64");
|
||||
al2023.setDescription("Amazon Linux 2023 AMI");
|
||||
al2023.setArchitecture("x86_64");
|
||||
al2023.setCreationDate("2023-03-15T00:00:00.000Z");
|
||||
staticImages.add(al2023);
|
||||
|
||||
Image ubuntu = new Image();
|
||||
ubuntu.setImageId("ami-0abcdef1234567892");
|
||||
ubuntu.setName("ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-20230324");
|
||||
ubuntu.setDescription("Canonical, Ubuntu, 20.04 LTS");
|
||||
ubuntu.setArchitecture("x86_64");
|
||||
ubuntu.setCreationDate("2023-03-24T00:00:00.000Z");
|
||||
staticImages.add(ubuntu);
|
||||
|
||||
Image windows = new Image();
|
||||
windows.setImageId("ami-0abcdef1234567893");
|
||||
windows.setName("Windows_Server-2022-English-Full-Base-2023.04.12");
|
||||
windows.setDescription("Microsoft Windows Server 2022 Full Locale English AMI");
|
||||
windows.setArchitecture("x86_64");
|
||||
windows.setPlatform("windows");
|
||||
windows.setCreationDate("2023-04-12T00:00:00.000Z");
|
||||
staticImages.add(windows);
|
||||
|
||||
return staticImages.stream()
|
||||
.filter(img -> imageIds.isEmpty() || imageIds.contains(img.getImageId()))
|
||||
public List<Image> describeImages(String region, List<String> imageIds, List<String> owners, Map<String, List<String>> filters) {
|
||||
return imageCatalog.images().stream()
|
||||
.filter(Ec2ImageCatalog.CatalogImage::advertised)
|
||||
.filter(img -> img.matchesIdOrAlias(imageIds))
|
||||
.filter(img -> img.matchesOwner(owners))
|
||||
.filter(img -> matchesImageFilters(img, filters))
|
||||
.map(Ec2ImageCatalog.CatalogImage::toImage)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// ─── Launch Templates ─────────────────────────────────────────────────────
|
||||
|
||||
public LaunchTemplate createLaunchTemplate(String region, String name, String imageId,
|
||||
String instanceType, String keyName,
|
||||
List<String> securityGroupIds, String userData,
|
||||
List<Tag> launchTemplateTags) {
|
||||
ensureDefaultResources(region);
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter LaunchTemplateName", 400);
|
||||
}
|
||||
boolean exists = launchTemplates.values().stream()
|
||||
.anyMatch(lt -> lt.getRegion().equals(region) && name.equals(lt.getLaunchTemplateName()));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidLaunchTemplateName.AlreadyExistsException",
|
||||
"Launch template name already in use.", 400);
|
||||
}
|
||||
|
||||
LaunchTemplate launchTemplate = new LaunchTemplate();
|
||||
launchTemplate.setLaunchTemplateId("lt-" + randomHex(17));
|
||||
launchTemplate.setLaunchTemplateName(name);
|
||||
launchTemplate.setCreateTime(Instant.now());
|
||||
launchTemplate.setCreatedBy("arn:aws:iam::" + accountId + ":root");
|
||||
launchTemplate.setRegion(region);
|
||||
launchTemplate.setImageId(imageId);
|
||||
launchTemplate.setInstanceType(instanceType);
|
||||
launchTemplate.setKeyName(keyName);
|
||||
launchTemplate.setUserData(userData);
|
||||
if (securityGroupIds != null) {
|
||||
launchTemplate.setSecurityGroupIds(new ArrayList<>(securityGroupIds));
|
||||
}
|
||||
if (launchTemplateTags != null && !launchTemplateTags.isEmpty()) {
|
||||
launchTemplate.setTags(new ArrayList<>(launchTemplateTags));
|
||||
tags.put(launchTemplate.getLaunchTemplateId(), new ArrayList<>(launchTemplateTags));
|
||||
}
|
||||
launchTemplate.getVersions().put("1", dataFrom(launchTemplate));
|
||||
launchTemplates.put(key(region, launchTemplate.getLaunchTemplateId()), launchTemplate);
|
||||
return launchTemplate;
|
||||
}
|
||||
|
||||
public LaunchTemplate createLaunchTemplateVersion(String region, String id, String name,
|
||||
String imageId, String instanceType, String keyName,
|
||||
List<String> securityGroupIds, String userData,
|
||||
String sourceVersion) {
|
||||
ensureDefaultResources(region);
|
||||
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
|
||||
int latestVersion = parseLaunchTemplateVersion(launchTemplate.getLatestVersionNumber()) + 1;
|
||||
LaunchTemplateData data = new LaunchTemplateData(versionData(launchTemplate,
|
||||
resolveLaunchTemplateVersion(launchTemplate, sourceVersion, launchTemplate.getLatestVersionNumber())));
|
||||
launchTemplate.setLatestVersionNumber(String.valueOf(latestVersion));
|
||||
if (imageId != null && !imageId.isBlank()) {
|
||||
data.setImageId(imageId);
|
||||
}
|
||||
if (instanceType != null && !instanceType.isBlank()) {
|
||||
data.setInstanceType(instanceType);
|
||||
}
|
||||
if (keyName != null && !keyName.isBlank()) {
|
||||
data.setKeyName(keyName);
|
||||
}
|
||||
if (userData != null && !userData.isBlank()) {
|
||||
data.setUserData(userData);
|
||||
}
|
||||
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
|
||||
data.setSecurityGroupIds(securityGroupIds);
|
||||
}
|
||||
launchTemplate.getVersions().put(String.valueOf(latestVersion), data);
|
||||
applyData(launchTemplate, data);
|
||||
return launchTemplate;
|
||||
}
|
||||
|
||||
public List<LaunchTemplate> describeLaunchTemplateVersions(String region, String id, String name,
|
||||
List<String> requestedVersions) {
|
||||
List<LaunchTemplate> templates = describeLaunchTemplates(
|
||||
region,
|
||||
id != null && !id.isBlank() ? List.of(id) : List.of(),
|
||||
name != null && !name.isBlank() ? List.of(name) : List.of(),
|
||||
Map.of());
|
||||
List<LaunchTemplate> versions = new ArrayList<>();
|
||||
for (LaunchTemplate launchTemplate : templates) {
|
||||
List<String> effectiveVersions = requestedVersions == null || requestedVersions.isEmpty()
|
||||
? List.of(launchTemplate.getLatestVersionNumber())
|
||||
: requestedVersions;
|
||||
for (String requestedVersion : effectiveVersions) {
|
||||
String resolvedVersion = resolveLaunchTemplateVersion(
|
||||
launchTemplate, requestedVersion, launchTemplate.getLatestVersionNumber());
|
||||
versions.add(copyForVersion(launchTemplate, resolvedVersion));
|
||||
}
|
||||
}
|
||||
return versions;
|
||||
}
|
||||
|
||||
public LaunchTemplate modifyLaunchTemplate(String region, String id, String name, String defaultVersion) {
|
||||
ensureDefaultResources(region);
|
||||
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
|
||||
if (defaultVersion != null && !defaultVersion.isBlank()) {
|
||||
String resolved = switch (defaultVersion) {
|
||||
case "$Latest" -> launchTemplate.getLatestVersionNumber();
|
||||
case "$Default" -> launchTemplate.getDefaultVersionNumber();
|
||||
default -> defaultVersion;
|
||||
};
|
||||
int requested = parseLaunchTemplateVersion(resolved);
|
||||
int latest = parseLaunchTemplateVersion(launchTemplate.getLatestVersionNumber());
|
||||
if (requested < 1 || requested > latest) {
|
||||
throw new AwsException("InvalidLaunchTemplateVersion.NotFound",
|
||||
"The specified launch template version does not exist.", 400);
|
||||
}
|
||||
launchTemplate.setDefaultVersionNumber(String.valueOf(requested));
|
||||
}
|
||||
return launchTemplate;
|
||||
}
|
||||
|
||||
public List<LaunchTemplate> describeLaunchTemplates(String region, List<String> ids,
|
||||
List<String> names, Map<String, List<String>> filters) {
|
||||
ensureDefaultResources(region);
|
||||
return launchTemplates.values().stream()
|
||||
.filter(lt -> lt.getRegion().equals(region))
|
||||
.filter(lt -> ids.isEmpty() || ids.contains(lt.getLaunchTemplateId()))
|
||||
.filter(lt -> names.isEmpty() || names.contains(lt.getLaunchTemplateName()))
|
||||
.filter(lt -> matchesFilters(lt, filters, region))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public LaunchTemplate deleteLaunchTemplate(String region, String id, String name) {
|
||||
ensureDefaultResources(region);
|
||||
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
|
||||
launchTemplates.remove(key(region, launchTemplate.getLaunchTemplateId()));
|
||||
tags.remove(launchTemplate.getLaunchTemplateId());
|
||||
return launchTemplate;
|
||||
}
|
||||
|
||||
private LaunchTemplate findLaunchTemplate(String region, String id, String name) {
|
||||
if (id != null && !id.isBlank()) {
|
||||
LaunchTemplate launchTemplate = launchTemplates.get(key(region, id));
|
||||
if (launchTemplate != null) {
|
||||
return launchTemplate;
|
||||
}
|
||||
} else if (name != null && !name.isBlank()) {
|
||||
return launchTemplates.values().stream()
|
||||
.filter(lt -> lt.getRegion().equals(region) && name.equals(lt.getLaunchTemplateName()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("InvalidLaunchTemplateName.NotFoundException",
|
||||
"The specified launch template does not exist.", 400));
|
||||
}
|
||||
throw new AwsException("InvalidLaunchTemplateId.NotFoundException",
|
||||
"The specified launch template does not exist.", 400);
|
||||
}
|
||||
|
||||
private int parseLaunchTemplateVersion(String version) {
|
||||
try {
|
||||
return Integer.parseInt(version);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("InvalidLaunchTemplateVersion.Malformed",
|
||||
"The specified launch template version is not valid.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveLaunchTemplateVersion(LaunchTemplate launchTemplate, String requestedVersion,
|
||||
String defaultWhenMissing) {
|
||||
if (launchTemplate.getVersions().isEmpty()) {
|
||||
launchTemplate.getVersions().put(launchTemplate.getLatestVersionNumber(), dataFrom(launchTemplate));
|
||||
}
|
||||
String candidate = requestedVersion == null || requestedVersion.isBlank() ? defaultWhenMissing : requestedVersion;
|
||||
String resolved = switch (candidate) {
|
||||
case "$Latest" -> launchTemplate.getLatestVersionNumber();
|
||||
case "$Default" -> launchTemplate.getDefaultVersionNumber();
|
||||
default -> candidate;
|
||||
};
|
||||
int requested = parseLaunchTemplateVersion(resolved);
|
||||
int latest = parseLaunchTemplateVersion(launchTemplate.getLatestVersionNumber());
|
||||
if (requested < 1 || requested > latest || !launchTemplate.getVersions().containsKey(resolved)) {
|
||||
throw new AwsException("InvalidLaunchTemplateVersion.NotFound",
|
||||
"The specified launch template version does not exist.", 400);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private LaunchTemplateData versionData(LaunchTemplate launchTemplate, String version) {
|
||||
return launchTemplate.getVersions().get(version);
|
||||
}
|
||||
|
||||
private LaunchTemplateData dataFrom(LaunchTemplate launchTemplate) {
|
||||
LaunchTemplateData data = new LaunchTemplateData();
|
||||
data.setImageId(launchTemplate.getImageId());
|
||||
data.setInstanceType(launchTemplate.getInstanceType());
|
||||
data.setKeyName(launchTemplate.getKeyName());
|
||||
data.setUserData(launchTemplate.getUserData());
|
||||
data.setSecurityGroupIds(launchTemplate.getSecurityGroupIds());
|
||||
return data;
|
||||
}
|
||||
|
||||
private void applyData(LaunchTemplate launchTemplate, LaunchTemplateData data) {
|
||||
launchTemplate.setImageId(data.getImageId());
|
||||
launchTemplate.setInstanceType(data.getInstanceType());
|
||||
launchTemplate.setKeyName(data.getKeyName());
|
||||
launchTemplate.setUserData(data.getUserData());
|
||||
launchTemplate.setSecurityGroupIds(new ArrayList<>(data.getSecurityGroupIds()));
|
||||
}
|
||||
|
||||
private LaunchTemplate copyForVersion(LaunchTemplate source, String versionNumber) {
|
||||
LaunchTemplate copy = new LaunchTemplate();
|
||||
copy.setLaunchTemplateId(source.getLaunchTemplateId());
|
||||
copy.setLaunchTemplateName(source.getLaunchTemplateName());
|
||||
copy.setDefaultVersionNumber(source.getDefaultVersionNumber());
|
||||
copy.setLatestVersionNumber(versionNumber);
|
||||
copy.setCreateTime(source.getCreateTime());
|
||||
copy.setCreatedBy(source.getCreatedBy());
|
||||
copy.setRegion(source.getRegion());
|
||||
copy.setTags(source.getTags());
|
||||
applyData(copy, versionData(source, versionNumber));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private boolean matchesImageFilters(Ec2ImageCatalog.CatalogImage image, Map<String, List<String>> filters) {
|
||||
if (filters == null || filters.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
|
||||
if (!matchesImageFilter(image, filter.getKey(), filter.getValue())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean matchesImageFilter(Ec2ImageCatalog.CatalogImage catalogImage, String name, List<String> values) {
|
||||
Image image = catalogImage.toImage();
|
||||
return switch (name) {
|
||||
case "architecture" -> matchesFilterValue(values, image.getArchitecture());
|
||||
case "hypervisor" -> matchesFilterValue(values, image.getHypervisor());
|
||||
case "image-id" -> catalogImage.idsAndAliases().stream().anyMatch(id -> matchesFilterValue(values, id));
|
||||
case "image-type" -> matchesFilterValue(values, "machine");
|
||||
case "is-public" -> matchesFilterValue(values, String.valueOf(image.isPublic()));
|
||||
case "name" -> matchesFilterValue(values, image.getName());
|
||||
case "owner-alias" -> matchesFilterValue(values, image.getImageOwnerAlias());
|
||||
case "owner-id" -> matchesFilterValue(values, image.getOwnerId());
|
||||
case "root-device-name" -> matchesFilterValue(values, image.getRootDeviceName());
|
||||
case "root-device-type" -> matchesFilterValue(values, image.getRootDeviceType());
|
||||
case "state" -> matchesFilterValue(values, image.getState());
|
||||
case "virtualization-type" -> matchesFilterValue(values, image.getVirtualizationType());
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean matchesFilterValue(List<String> patterns, String value) {
|
||||
if (patterns == null || patterns.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
if (value == null) {
|
||||
return false;
|
||||
}
|
||||
return patterns.stream().anyMatch(pattern -> wildcardMatches(pattern, value));
|
||||
}
|
||||
|
||||
private boolean wildcardMatches(String pattern, String value) {
|
||||
if (pattern == null) {
|
||||
return false;
|
||||
}
|
||||
if (!pattern.contains("*")) {
|
||||
return pattern.equals(value);
|
||||
}
|
||||
String regex = pattern.chars()
|
||||
.mapToObj(ch -> ch == '*' ? ".*" : java.util.regex.Pattern.quote(String.valueOf((char) ch)))
|
||||
.collect(Collectors.joining());
|
||||
return value.matches(regex);
|
||||
}
|
||||
|
||||
// ─── Tags ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {
|
||||
@@ -1007,7 +1327,13 @@ public class Ec2Service {
|
||||
RouteTable rt = routeTables.get(key(region, resourceId));
|
||||
if (rt != null) { rt.setTags(new ArrayList<>(tagList)); return; }
|
||||
KeyPair kp = keyPairs.get(key(region, resourceId));
|
||||
if (kp != null) { kp.setTags(new ArrayList<>(tagList)); }
|
||||
if (kp != null) { kp.setTags(new ArrayList<>(tagList)); return; }
|
||||
LaunchTemplate lt = launchTemplates.get(key(region, resourceId));
|
||||
if (lt != null) { lt.setTags(new ArrayList<>(tagList)); return; }
|
||||
VpcEndpoint endpoint = vpcEndpoints.get(key(region, resourceId));
|
||||
if (endpoint != null) { endpoint.setTags(new ArrayList<>(tagList)); return; }
|
||||
NatGateway natGateway = natGateways.get(key(region, resourceId));
|
||||
if (natGateway != null) { natGateway.setTags(new ArrayList<>(tagList)); }
|
||||
}
|
||||
|
||||
public List<Map<String, String>> describeTags(String region, Map<String, List<String>> filters) {
|
||||
@@ -1055,6 +1381,9 @@ public class Ec2Service {
|
||||
if (resourceId.startsWith("rtb-")) return "route-table";
|
||||
if (resourceId.startsWith("key-")) return "key-pair";
|
||||
if (resourceId.startsWith("eipalloc-")) return "elastic-ip";
|
||||
if (resourceId.startsWith("lt-")) return "launch-template";
|
||||
if (resourceId.startsWith("vpce-")) return "vpc-endpoint";
|
||||
if (resourceId.startsWith("nat-")) return "natgateway";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
@@ -1196,6 +1525,66 @@ public class Ec2Service {
|
||||
return rt;
|
||||
}
|
||||
|
||||
// ─── NAT Gateways ─────────────────────────────────────────────────────────
|
||||
|
||||
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
|
||||
String connectivityType, List<Tag> natGatewayTags) {
|
||||
ensureDefaultResources(region);
|
||||
Subnet subnet = requireSubnet(region, subnetId);
|
||||
if (allocationId != null && !allocationId.isBlank()) {
|
||||
getRequiredAddress(region, allocationId);
|
||||
}
|
||||
|
||||
NatGateway natGateway = new NatGateway();
|
||||
natGateway.setNatGatewayId("nat-" + randomHex(17));
|
||||
natGateway.setSubnetId(subnetId);
|
||||
natGateway.setVpcId(subnet.getVpcId());
|
||||
natGateway.setAllocationId(allocationId);
|
||||
natGateway.setConnectivityType(connectivityType != null && !connectivityType.isBlank() ? connectivityType : "public");
|
||||
natGateway.setCreateTime(Instant.now());
|
||||
natGateway.setRegion(region);
|
||||
if (natGatewayTags != null && !natGatewayTags.isEmpty()) {
|
||||
natGateway.setTags(new ArrayList<>(natGatewayTags));
|
||||
tags.put(natGateway.getNatGatewayId(), new ArrayList<>(natGatewayTags));
|
||||
}
|
||||
natGateways.put(key(region, natGateway.getNatGatewayId()), natGateway);
|
||||
return natGateway;
|
||||
}
|
||||
|
||||
public List<NatGateway> describeNatGateways(String region, List<String> natGatewayIds,
|
||||
Map<String, List<String>> filters) {
|
||||
ensureDefaultResources(region);
|
||||
if (!natGatewayIds.isEmpty()) {
|
||||
for (String natGatewayId : natGatewayIds) {
|
||||
getRequiredNatGateway(region, natGatewayId);
|
||||
}
|
||||
}
|
||||
return natGateways.values().stream()
|
||||
.filter(natGateway -> natGateway.getRegion().equals(region))
|
||||
.filter(natGateway -> natGatewayIds.isEmpty()
|
||||
|| natGatewayIds.contains(natGateway.getNatGatewayId()))
|
||||
.filter(natGateway -> matchesFilters(natGateway, filters, region))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public NatGateway deleteNatGateway(String region, String natGatewayId) {
|
||||
ensureDefaultResources(region);
|
||||
NatGateway natGateway = getRequiredNatGateway(region, natGatewayId);
|
||||
natGateway.setState("deleted");
|
||||
natGateways.remove(key(region, natGatewayId));
|
||||
tags.remove(natGatewayId);
|
||||
return natGateway;
|
||||
}
|
||||
|
||||
private NatGateway getRequiredNatGateway(String region, String natGatewayId) {
|
||||
NatGateway natGateway = natGateways.get(key(region, natGatewayId));
|
||||
if (natGateway == null) {
|
||||
throw new AwsException("NatGatewayNotFound",
|
||||
"NatGateway " + natGatewayId + " was not found", 400);
|
||||
}
|
||||
return natGateway;
|
||||
}
|
||||
|
||||
// ─── Elastic IPs ───────────────────────────────────────────────────────────
|
||||
|
||||
public Address allocateAddress(String region) {
|
||||
@@ -1296,6 +1685,9 @@ public class Ec2Service {
|
||||
allTypes.add(buildInstanceType("t3.small", 2, 2048));
|
||||
allTypes.add(buildInstanceType("t3.medium", 2, 4096));
|
||||
allTypes.add(buildInstanceType("m5.large", 2, 8192));
|
||||
allTypes.add(buildInstanceType("t4g.micro", 2, 1024, List.of("arm64")));
|
||||
allTypes.add(buildInstanceType("t4g.small", 2, 2048, List.of("arm64")));
|
||||
allTypes.add(buildInstanceType("t4g.medium", 2, 4096, List.of("arm64")));
|
||||
|
||||
if (instanceTypeNames.isEmpty()) {
|
||||
return allTypes;
|
||||
@@ -1306,15 +1698,55 @@ public class Ec2Service {
|
||||
}
|
||||
|
||||
private Map<String, Object> buildInstanceType(String name, int vcpu, int memMib) {
|
||||
return buildInstanceType(name, vcpu, memMib, List.of("x86_64"));
|
||||
}
|
||||
|
||||
private Map<String, Object> buildInstanceType(String name, int vcpu, int memMib,
|
||||
List<String> supportedArchitectures) {
|
||||
Map<String, Object> t = new LinkedHashMap<>();
|
||||
t.put("instanceType", name);
|
||||
t.put("vcpu", vcpu);
|
||||
t.put("memoryMib", memMib);
|
||||
t.put("supportedArchitectures", List.of("x86_64"));
|
||||
t.put("supportedArchitectures", supportedArchitectures);
|
||||
t.put("currentGeneration", true);
|
||||
return t;
|
||||
}
|
||||
|
||||
public List<Map<String, String>> describeInstanceTypeOfferings(String region, List<String> instanceTypeNames,
|
||||
String locationType,
|
||||
Map<String, List<String>> filters) {
|
||||
List<String> effectiveTypeNames = new ArrayList<>(new LinkedHashSet<>(instanceTypeNames));
|
||||
if (filters != null && filters.containsKey("instance-type")) {
|
||||
effectiveTypeNames.addAll(filters.get("instance-type"));
|
||||
effectiveTypeNames = new ArrayList<>(new LinkedHashSet<>(effectiveTypeNames));
|
||||
}
|
||||
String effectiveLocationType = locationType != null && !locationType.isBlank()
|
||||
? locationType
|
||||
: "availability-zone";
|
||||
List<String> locations = "region".equals(effectiveLocationType)
|
||||
? List.of(region)
|
||||
: describeAvailabilityZones(region).stream()
|
||||
.map(zone -> zone.get("zoneName"))
|
||||
.toList();
|
||||
List<String> locationFilter = filters != null ? filters.get("location") : null;
|
||||
|
||||
List<Map<String, String>> offerings = new ArrayList<>();
|
||||
for (Map<String, Object> type : describeInstanceTypes(effectiveTypeNames)) {
|
||||
String instanceType = (String) type.get("instanceType");
|
||||
for (String location : locations) {
|
||||
if (locationFilter != null && !matchesValue(location, locationFilter)) {
|
||||
continue;
|
||||
}
|
||||
Map<String, String> offering = new LinkedHashMap<>();
|
||||
offering.put("instanceType", instanceType);
|
||||
offering.put("locationType", effectiveLocationType);
|
||||
offering.put("location", location);
|
||||
offerings.add(offering);
|
||||
}
|
||||
}
|
||||
return offerings;
|
||||
}
|
||||
|
||||
// ─── Filter matching ───────────────────────────────────────────────────────
|
||||
|
||||
private boolean matchesValue(String resourceValue, List<String> filterValues) {
|
||||
@@ -1452,6 +1884,37 @@ public class Ec2Service {
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
if (resource instanceof LaunchTemplate lt) {
|
||||
return switch (filterName) {
|
||||
case "launch-template-id" -> matchesValue(values, lt.getLaunchTemplateId());
|
||||
case "launch-template-name" -> matchesValue(values, lt.getLaunchTemplateName());
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
if (resource instanceof VpcEndpoint endpoint) {
|
||||
return switch (filterName) {
|
||||
case "service-name" -> matchesValue(values, endpoint.getServiceName());
|
||||
case "vpc-endpoint-id" -> matchesValue(values, endpoint.getVpcEndpointId());
|
||||
case "vpc-endpoint-type" -> matchesValue(values, endpoint.getVpcEndpointType());
|
||||
case "vpc-id" -> matchesValue(values, endpoint.getVpcId());
|
||||
case "state" -> matchesValue(values, endpoint.getState());
|
||||
case "route-table-id" -> endpoint.getRouteTableIds().stream()
|
||||
.anyMatch(routeTableId -> matchesValue(values, routeTableId));
|
||||
case "subnet-id" -> endpoint.getSubnetIds().stream()
|
||||
.anyMatch(subnetId -> matchesValue(values, subnetId));
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
if (resource instanceof NatGateway natGateway) {
|
||||
return switch (filterName) {
|
||||
case "nat-gateway-id" -> matchesValue(values, natGateway.getNatGatewayId());
|
||||
case "subnet-id" -> matchesValue(values, natGateway.getSubnetId());
|
||||
case "vpc-id" -> matchesValue(values, natGateway.getVpcId());
|
||||
case "state" -> matchesValue(values, natGateway.getState());
|
||||
case "connectivity-type" -> matchesValue(values, natGateway.getConnectivityType());
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
if (resource instanceof Volume vol) {
|
||||
return switch (filterName) {
|
||||
case "volume-id" -> matchesValue(values, vol.getVolumeId());
|
||||
@@ -1496,6 +1959,9 @@ public class Ec2Service {
|
||||
if (resource instanceof Address addr) return addr.getTags();
|
||||
if (resource instanceof Volume vol) return vol.getTags();
|
||||
if (resource instanceof NetworkInterface ni) return ni.getTagSet();
|
||||
if (resource instanceof LaunchTemplate lt) return lt.getTags();
|
||||
if (resource instanceof VpcEndpoint endpoint) return endpoint.getTags();
|
||||
if (resource instanceof NatGateway natGateway) return natGateway.getTags();
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LaunchTemplate {
|
||||
|
||||
private String launchTemplateId;
|
||||
private String launchTemplateName;
|
||||
private String defaultVersionNumber = "1";
|
||||
private String latestVersionNumber = "1";
|
||||
private Instant createTime;
|
||||
private String createdBy;
|
||||
private String region;
|
||||
private String imageId;
|
||||
private String instanceType;
|
||||
private String keyName;
|
||||
private String userData;
|
||||
private List<String> securityGroupIds = new ArrayList<>();
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
private Map<String, LaunchTemplateData> versions = new LinkedHashMap<>();
|
||||
|
||||
public LaunchTemplate() {}
|
||||
|
||||
public String getLaunchTemplateId() { return launchTemplateId; }
|
||||
public void setLaunchTemplateId(String launchTemplateId) { this.launchTemplateId = launchTemplateId; }
|
||||
|
||||
public String getLaunchTemplateName() { return launchTemplateName; }
|
||||
public void setLaunchTemplateName(String launchTemplateName) { this.launchTemplateName = launchTemplateName; }
|
||||
|
||||
public String getDefaultVersionNumber() { return defaultVersionNumber; }
|
||||
public void setDefaultVersionNumber(String defaultVersionNumber) { this.defaultVersionNumber = defaultVersionNumber; }
|
||||
|
||||
public String getLatestVersionNumber() { return latestVersionNumber; }
|
||||
public void setLatestVersionNumber(String latestVersionNumber) { this.latestVersionNumber = latestVersionNumber; }
|
||||
|
||||
public Instant getCreateTime() { return createTime; }
|
||||
public void setCreateTime(Instant createTime) { this.createTime = createTime; }
|
||||
|
||||
public String getCreatedBy() { return createdBy; }
|
||||
public void setCreatedBy(String createdBy) { this.createdBy = createdBy; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public String getImageId() { return imageId; }
|
||||
public void setImageId(String imageId) { this.imageId = imageId; }
|
||||
|
||||
public String getInstanceType() { return instanceType; }
|
||||
public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
|
||||
|
||||
public String getKeyName() { return keyName; }
|
||||
public void setKeyName(String keyName) { this.keyName = keyName; }
|
||||
|
||||
public String getUserData() { return userData; }
|
||||
public void setUserData(String userData) { this.userData = userData; }
|
||||
|
||||
public List<String> getSecurityGroupIds() { return securityGroupIds; }
|
||||
public void setSecurityGroupIds(List<String> securityGroupIds) { this.securityGroupIds = securityGroupIds; }
|
||||
|
||||
public List<Tag> getTags() { return tags; }
|
||||
public void setTags(List<Tag> tags) { this.tags = tags; }
|
||||
|
||||
public Map<String, LaunchTemplateData> getVersions() { return versions; }
|
||||
public void setVersions(Map<String, LaunchTemplateData> versions) {
|
||||
this.versions = versions != null ? new LinkedHashMap<>(versions) : new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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 LaunchTemplateData {
|
||||
|
||||
private String imageId;
|
||||
private String instanceType;
|
||||
private String keyName;
|
||||
private String userData;
|
||||
private List<String> securityGroupIds = new ArrayList<>();
|
||||
|
||||
public LaunchTemplateData() {}
|
||||
|
||||
public LaunchTemplateData(LaunchTemplateData source) {
|
||||
this.imageId = source.imageId;
|
||||
this.instanceType = source.instanceType;
|
||||
this.keyName = source.keyName;
|
||||
this.userData = source.userData;
|
||||
this.securityGroupIds = new ArrayList<>(source.securityGroupIds);
|
||||
}
|
||||
|
||||
public String getImageId() { return imageId; }
|
||||
public void setImageId(String imageId) { this.imageId = imageId; }
|
||||
|
||||
public String getInstanceType() { return instanceType; }
|
||||
public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
|
||||
|
||||
public String getKeyName() { return keyName; }
|
||||
public void setKeyName(String keyName) { this.keyName = keyName; }
|
||||
|
||||
public String getUserData() { return userData; }
|
||||
public void setUserData(String userData) { this.userData = userData; }
|
||||
|
||||
public List<String> getSecurityGroupIds() { return securityGroupIds; }
|
||||
public void setSecurityGroupIds(List<String> securityGroupIds) {
|
||||
this.securityGroupIds = securityGroupIds != null ? new ArrayList<>(securityGroupIds) : new ArrayList<>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class NatGateway {
|
||||
|
||||
private String natGatewayId;
|
||||
private String subnetId;
|
||||
private String vpcId;
|
||||
private String allocationId;
|
||||
private String state = "available";
|
||||
private String connectivityType = "public";
|
||||
private Instant createTime;
|
||||
private String region;
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
|
||||
public NatGateway() {}
|
||||
|
||||
public String getNatGatewayId() { return natGatewayId; }
|
||||
public void setNatGatewayId(String natGatewayId) { this.natGatewayId = natGatewayId; }
|
||||
|
||||
public String getSubnetId() { return subnetId; }
|
||||
public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
|
||||
|
||||
public String getVpcId() { return vpcId; }
|
||||
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
|
||||
|
||||
public String getAllocationId() { return allocationId; }
|
||||
public void setAllocationId(String allocationId) { this.allocationId = allocationId; }
|
||||
|
||||
public String getState() { return state; }
|
||||
public void setState(String state) { this.state = state; }
|
||||
|
||||
public String getConnectivityType() { return connectivityType; }
|
||||
public void setConnectivityType(String connectivityType) { this.connectivityType = connectivityType; }
|
||||
|
||||
public Instant getCreateTime() { return createTime; }
|
||||
public void setCreateTime(Instant createTime) { this.createTime = createTime; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public List<Tag> getTags() { return tags; }
|
||||
public void setTags(List<Tag> tags) { this.tags = tags; }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class VpcEndpoint {
|
||||
|
||||
private String vpcEndpointId;
|
||||
private String vpcId;
|
||||
private String serviceName;
|
||||
private String vpcEndpointType = "Gateway";
|
||||
private String state = "available";
|
||||
private Instant creationTimestamp;
|
||||
private String region;
|
||||
private List<String> routeTableIds = new ArrayList<>();
|
||||
private List<String> subnetIds = new ArrayList<>();
|
||||
private List<String> securityGroupIds = new ArrayList<>();
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
|
||||
public VpcEndpoint() {}
|
||||
|
||||
public String getVpcEndpointId() { return vpcEndpointId; }
|
||||
public void setVpcEndpointId(String vpcEndpointId) { this.vpcEndpointId = vpcEndpointId; }
|
||||
|
||||
public String getVpcId() { return vpcId; }
|
||||
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
|
||||
|
||||
public String getServiceName() { return serviceName; }
|
||||
public void setServiceName(String serviceName) { this.serviceName = serviceName; }
|
||||
|
||||
public String getVpcEndpointType() { return vpcEndpointType; }
|
||||
public void setVpcEndpointType(String vpcEndpointType) { this.vpcEndpointType = vpcEndpointType; }
|
||||
|
||||
public String getState() { return state; }
|
||||
public void setState(String state) { this.state = state; }
|
||||
|
||||
public Instant getCreationTimestamp() { return creationTimestamp; }
|
||||
public void setCreationTimestamp(Instant creationTimestamp) { this.creationTimestamp = creationTimestamp; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public List<String> getRouteTableIds() { return routeTableIds; }
|
||||
public void setRouteTableIds(List<String> routeTableIds) { this.routeTableIds = routeTableIds; }
|
||||
|
||||
public List<String> getSubnetIds() { return subnetIds; }
|
||||
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }
|
||||
|
||||
public List<String> getSecurityGroupIds() { return securityGroupIds; }
|
||||
public void setSecurityGroupIds(List<String> securityGroupIds) { this.securityGroupIds = securityGroupIds; }
|
||||
|
||||
public List<Tag> getTags() { return tags; }
|
||||
public void setTags(List<Tag> tags) { this.tags = tags; }
|
||||
}
|
||||
Reference in new issue
Block a user