Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ec2): support registered images and snapshots (#1601)

Jason van Zyl2a6cf1c14784
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index e8dc40f127..d7a2fa5ac3 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -151,7 +151,7 @@ public class AwsQueryController {
"DescribeSecurityGroupRules", "ModifySecurityGroupRules",
"UpdateSecurityGroupRuleDescriptionsIngress", "UpdateSecurityGroupRuleDescriptionsEgress",
"CreateKeyPair", "DescribeKeyPairs", "DeleteKeyPair", "ImportKeyPair",
- "DescribeImages",
+ "DescribeImages", "RegisterImage", "DescribeSnapshots",
"CreateTags", "DeleteTags", "DescribeTags",
"CreateInternetGateway", "DescribeInternetGateways", "DeleteInternetGateway",
"AttachInternetGateway", "DetachInternetGateway",
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index 4bc8522a54..6b556d9971 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -98,6 +98,8 @@ public class Ec2QueryHandler {
case "ImportKeyPair" -> handleImportKeyPair(params, region);
// AMIs
case "DescribeImages" -> handleDescribeImages(params, region);
+ case "RegisterImage" -> handleRegisterImage(params, region);
+ case "DescribeSnapshots" -> handleDescribeSnapshots(params, region);
// Tags
case "CreateTags" -> handleCreateTags(params, region);
case "DeleteTags" -> handleDeleteTags(params, region);
@@ -199,6 +201,14 @@ public class Ec2QueryHandler {
return result;
}
+ private List<String> getList(MultivaluedMap<String, String> p, String... prefixes) {
+ List<String> result = new ArrayList<>();
+ for (String prefix : prefixes) {
+ result.addAll(getList(p, prefix));
+ }
+ return result;
+ }
+
private int parseIntParam(MultivaluedMap<String, String> p, String name, int defaultValue) {
String val = p.getFirst(name);
if (val == null || val.isEmpty()) return defaultValue;
@@ -226,6 +236,64 @@ public class Ec2QueryHandler {
return filters;
}
+ private List<BlockDeviceMapping> parseBlockDeviceMappings(MultivaluedMap<String, String> p) {
+ List<BlockDeviceMapping> mappings = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String prefix = "BlockDeviceMapping." + i;
+ String deviceName = p.getFirst(prefix + ".DeviceName");
+ String snapshotId = p.getFirst(prefix + ".Ebs.SnapshotId");
+ String volumeSize = p.getFirst(prefix + ".Ebs.VolumeSize");
+ String volumeType = p.getFirst(prefix + ".Ebs.VolumeType");
+ String deleteOnTermination = p.getFirst(prefix + ".Ebs.DeleteOnTermination");
+ String encrypted = p.getFirst(prefix + ".Ebs.Encrypted");
+ boolean hasEbs = snapshotId != null || volumeSize != null || volumeType != null
+ || deleteOnTermination != null || encrypted != null;
+ if (deviceName == null && !hasEbs) {
+ break;
+ }
+ if (deviceName == null || deviceName.isBlank()) {
+ throw new AwsException("InvalidParameterValue",
+ "BlockDeviceMapping." + i + ".DeviceName is required.", 400);
+ }
+ BlockDeviceMapping mapping = new BlockDeviceMapping();
+ mapping.setDeviceName(deviceName);
+ EbsBlockDevice ebs = new EbsBlockDevice();
+ ebs.setSnapshotId(snapshotId);
+ ebs.setVolumeSize(parseOptionalInt(volumeSize, prefix + ".Ebs.VolumeSize"));
+ ebs.setVolumeType(volumeType);
+ ebs.setDeleteOnTermination(parseOptionalBoolean(deleteOnTermination,
+ prefix + ".Ebs.DeleteOnTermination"));
+ ebs.setEncrypted(parseOptionalBoolean(encrypted, prefix + ".Ebs.Encrypted"));
+ mapping.setEbs(ebs);
+ mappings.add(mapping);
+ }
+ return mappings;
+ }
+
+ private Integer parseOptionalInt(String value, String name) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ try {
+ return Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidParameterValue", name + " is not a valid integer.", 400);
+ }
+ }
+
+ private Boolean parseOptionalBoolean(String value, String name) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ if ("true".equalsIgnoreCase(value)) {
+ return true;
+ }
+ if ("false".equalsIgnoreCase(value)) {
+ return false;
+ }
+ throw new AwsException("InvalidParameterValue", name + " is not a valid boolean.", 400);
+ }
+
private List<IpPermission> parseIpPermissions(MultivaluedMap<String, String> p, String prefix) {
List<IpPermission> perms = new ArrayList<>();
for (int i = 1; ; i++) {
@@ -1184,12 +1252,45 @@ public class Ec2QueryHandler {
.elem("hypervisor", img.getHypervisor())
.elem("imageOwnerAlias", img.getImageOwnerAlias())
.elem("creationDate", img.getCreationDate())
+ .raw(blockDeviceMappingXml(img.getBlockDeviceMappings()))
.end("item");
}
xml.end("imagesSet").end("DescribeImagesResponse");
return xmlResponse(xml.build());
}
+ private Response handleRegisterImage(MultivaluedMap<String, String> p, String region) {
+ Image image = service.registerImage(
+ region,
+ p.getFirst("Name"),
+ p.getFirst("Description"),
+ p.getFirst("Architecture"),
+ p.getFirst("RootDeviceName"),
+ parseBlockDeviceMappings(p));
+ XmlBuilder xml = new XmlBuilder()
+ .start("RegisterImageResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("imageId", image.getImageId())
+ .end("RegisterImageResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeSnapshots(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "SnapshotId");
+ List<String> owners = getList(p, "Owner", "OwnerId", "OwnerIds");
+ Map<String, List<String>> filters = getFilters(p);
+ List<Snapshot> snapshots = service.describeSnapshots(region, ids, owners, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeSnapshotsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("snapshotSet");
+ for (Snapshot snapshot : snapshots) {
+ xml.start("item").raw(snapshotXml(snapshot)).end("item");
+ }
+ xml.end("snapshotSet").end("DescribeSnapshotsResponse");
+ return xmlResponse(xml.build());
+ }
+
// ─── Tag handlers ─────────────────────────────────────────────────────────
private Response handleCreateTags(MultivaluedMap<String, String> p, String region) {
@@ -2314,6 +2415,61 @@ public class Ec2QueryHandler {
return xml.build();
}
+ private String blockDeviceMappingXml(List<BlockDeviceMapping> mappings) {
+ if (mappings == null || mappings.isEmpty()) {
+ return "<blockDeviceMapping/>";
+ }
+ XmlBuilder xml = new XmlBuilder().start("blockDeviceMapping");
+ for (BlockDeviceMapping mapping : mappings) {
+ xml.start("item")
+ .elem("deviceName", mapping.getDeviceName());
+ EbsBlockDevice ebs = mapping.getEbs();
+ if (ebs != null) {
+ xml.start("ebs");
+ if (ebs.getSnapshotId() != null) {
+ xml.elem("snapshotId", ebs.getSnapshotId());
+ }
+ if (ebs.getVolumeSize() != null) {
+ xml.elem("volumeSize", String.valueOf(ebs.getVolumeSize()));
+ }
+ if (ebs.getVolumeType() != null) {
+ xml.elem("volumeType", ebs.getVolumeType());
+ }
+ if (ebs.getDeleteOnTermination() != null) {
+ xml.elem("deleteOnTermination", String.valueOf(ebs.getDeleteOnTermination()));
+ }
+ if (ebs.getEncrypted() != null) {
+ xml.elem("encrypted", String.valueOf(ebs.getEncrypted()));
+ }
+ xml.end("ebs");
+ }
+ xml.end("item");
+ }
+ xml.end("blockDeviceMapping");
+ return xml.build();
+ }
+
+ private String snapshotXml(Snapshot snapshot) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("snapshotId", snapshot.getSnapshotId())
+ .elem("ownerId", snapshot.getOwnerId())
+ .elem("status", snapshot.getState())
+ .elem("progress", snapshot.getProgress())
+ .elem("encrypted", String.valueOf(snapshot.isEncrypted()))
+ .elem("description", snapshot.getDescription());
+ if (snapshot.getVolumeId() != null) {
+ xml.elem("volumeId", snapshot.getVolumeId());
+ }
+ if (snapshot.getVolumeSize() != null) {
+ xml.elem("volumeSize", String.valueOf(snapshot.getVolumeSize()));
+ }
+ if (snapshot.getStartTime() != null) {
+ xml.elem("startTime", ISO_FMT.format(snapshot.getStartTime()));
+ }
+ xml.raw(tagSetXml(snapshot.getTags()));
+ return xml.build();
+ }
+
// ─── Volume handlers ──────────────────────────────────────────────────────
private Response handleCreateVolume(MultivaluedMap<String, String> p, String region) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index 55705f2a36..84b6cbdbea 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -29,6 +29,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
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.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.services.ec2.model.Image;
@@ -59,6 +61,7 @@ import io.github.hectorvent.floci.services.ec2.model.RouteTable;
import io.github.hectorvent.floci.services.ec2.model.RouteTableAssociation;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
+import io.github.hectorvent.floci.services.ec2.model.Snapshot;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.Volume;
@@ -100,6 +103,8 @@ public class Ec2Service {
private final StorageBackend<String, Address> addresses;
private final StorageBackend<String, Instance> instances;
private final StorageBackend<String, Volume> volumes;
+ private final StorageBackend<String, Image> registeredImages;
+ private final StorageBackend<String, Snapshot> snapshots;
private final StorageBackend<String, LaunchTemplate> launchTemplates;
private final StorageBackend<String, VpcEndpoint> vpcEndpoints;
private final StorageBackend<String, NatGateway> natGateways;
@@ -127,6 +132,8 @@ public class Ec2Service {
storageFactory.create("ec2", "ec2-addresses.json", new TypeReference<Map<String, Address>>() {}),
storageFactory.create("ec2", "ec2-instances.json", new TypeReference<Map<String, Instance>>() {}),
storageFactory.create("ec2", "ec2-volumes.json", new TypeReference<Map<String, Volume>>() {}),
+ storageFactory.create("ec2", "ec2-registered-images.json", new TypeReference<Map<String, Image>>() {}),
+ storageFactory.create("ec2", "ec2-snapshots.json", new TypeReference<Map<String, Snapshot>>() {}),
storageFactory.create("ec2", "ec2-launch-templates.json", new TypeReference<Map<String, LaunchTemplate>>() {}),
storageFactory.create("ec2", "ec2-vpc-endpoints.json", new TypeReference<Map<String, VpcEndpoint>>() {}),
storageFactory.create("ec2", "ec2-nat-gateways.json", new TypeReference<Map<String, NatGateway>>() {}),
@@ -150,6 +157,8 @@ public class Ec2Service {
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,
@@ -173,6 +182,8 @@ public class Ec2Service {
this.addresses = addresses;
this.instances = instances;
this.volumes = volumes;
+ this.registeredImages = registeredImages;
+ this.snapshots = snapshots;
this.launchTemplates = launchTemplates;
this.vpcEndpoints = vpcEndpoints;
this.natGateways = natGateways;
@@ -1531,13 +1542,80 @@ public class Ec2Service {
}
public List<Image> describeImages(String region, List<String> imageIds, List<String> owners, Map<String, List<String>> filters) {
- return imageCatalog.images().stream()
+ List<Image> catalogImages = 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());
+ List<Image> createdImages = registeredImages.scan(k -> true).stream()
+ .filter(img -> region.equals(img.getRegion()))
+ .filter(img -> matchesImageIds(img, imageIds))
+ .filter(img -> matchesImageOwners(img, owners))
+ .filter(img -> matchesRegisteredImageFilters(img, filters))
+ .collect(Collectors.toList());
+ List<Image> images = new ArrayList<>(catalogImages);
+ images.addAll(createdImages);
+ return images;
+ }
+
+ public Image registerImage(String region, String name, String description, String architecture,
+ String rootDeviceName, List<BlockDeviceMapping> blockDeviceMappings) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("MissingParameter", "The request must contain the parameter Name", 400);
+ }
+ boolean duplicateName = registeredImages.scan(k -> true).stream()
+ .filter(img -> region.equals(img.getRegion()))
+ .anyMatch(img -> name.equals(img.getName()));
+ if (duplicateName) {
+ throw new AwsException("InvalidAMIName.Duplicate",
+ "AMI name '" + name + "' is already in use.", 400);
+ }
+ Image image = new Image();
+ image.setImageId("ami-" + randomHex(17));
+ image.setName(name);
+ image.setDescription(description != null ? description : name);
+ image.setOwnerId(accountId);
+ image.setImageOwnerAlias(null);
+ image.setPublic(false);
+ image.setArchitecture(architecture != null ? architecture : "x86_64");
+ image.setRootDeviceName(rootDeviceName != null ? rootDeviceName : "/dev/sda1");
+ image.setRootDeviceType("ebs");
+ image.setVirtualizationType("hvm");
+ image.setHypervisor("xen");
+ image.setCreationDate(ISO_FMT.format(Instant.now()));
+ image.setRegion(region);
+ image.setBlockDeviceMappings(blockDeviceMappings != null ? new ArrayList<>(blockDeviceMappings) : List.of());
+ registeredImages.put(key(region, image.getImageId()), image);
+ for (BlockDeviceMapping mapping : image.getBlockDeviceMappings()) {
+ EbsBlockDevice ebs = mapping.getEbs();
+ if (ebs != null && ebs.getSnapshotId() != null) {
+ String snapshotKey = key(region, ebs.getSnapshotId());
+ if (snapshots.get(snapshotKey).isEmpty()) {
+ snapshots.put(snapshotKey, snapshotFrom(region, ebs.getSnapshotId(), image, mapping));
+ }
+ }
+ }
+ return image;
+ }
+
+ public List<Snapshot> describeSnapshots(String region, List<String> snapshotIds,
+ List<String> ownerIds, Map<String, List<String>> filters) {
+ if (snapshotIds != null && !snapshotIds.isEmpty()) {
+ for (String id : snapshotIds) {
+ if (snapshots.get(key(region, id)).isEmpty()) {
+ throw new AwsException("InvalidSnapshot.NotFound",
+ "The snapshot '" + id + "' does not exist.", 400);
+ }
+ }
+ }
+ return snapshots.scan(k -> true).stream()
+ .filter(snapshot -> region.equals(snapshot.getRegion()))
+ .filter(snapshot -> snapshotIds == null || snapshotIds.isEmpty() || snapshotIds.contains(snapshot.getSnapshotId()))
+ .filter(snapshot -> matchesSnapshotOwners(snapshot, ownerIds))
+ .filter(snapshot -> matchesSnapshotFilters(snapshot, filters))
+ .collect(Collectors.toList());
}
// ─── Launch Templates ─────────────────────────────────────────────────────
@@ -1820,6 +1898,100 @@ public class Ec2Service {
};
}
+ private boolean matchesImageIds(Image image, List<String> imageIds) {
+ return imageIds == null || imageIds.isEmpty() || imageIds.contains(image.getImageId());
+ }
+
+ private boolean matchesImageOwners(Image image, List<String> owners) {
+ return owners == null || owners.isEmpty()
+ || owners.contains(image.getOwnerId())
+ || (owners.contains("self") && accountId.equals(image.getOwnerId()));
+ }
+
+ private boolean matchesRegisteredImageFilters(Image image, Map<String, List<String>> filters) {
+ if (filters == null || filters.isEmpty()) {
+ return true;
+ }
+ for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
+ if (!matchesRegisteredImageFilter(image, filter.getKey(), filter.getValue())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean matchesRegisteredImageFilter(Image image, String name, List<String> values) {
+ return switch (name) {
+ case "architecture" -> matchesFilterValue(values, image.getArchitecture());
+ case "block-device-mapping.snapshot-id" -> image.getBlockDeviceMappings().stream()
+ .map(BlockDeviceMapping::getEbs)
+ .filter(Objects::nonNull)
+ .map(EbsBlockDevice::getSnapshotId)
+ .anyMatch(snapshotId -> matchesFilterValue(values, snapshotId));
+ case "description" -> matchesFilterValue(values, image.getDescription());
+ case "hypervisor" -> matchesFilterValue(values, image.getHypervisor());
+ case "image-id" -> matchesFilterValue(values, image.getImageId());
+ 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 Snapshot snapshotFrom(String region, String snapshotId, Image image, BlockDeviceMapping mapping) {
+ EbsBlockDevice ebs = mapping.getEbs();
+ Snapshot snapshot = new Snapshot();
+ snapshot.setSnapshotId(snapshotId);
+ snapshot.setOwnerId(accountId);
+ snapshot.setState("completed");
+ snapshot.setDescription("Created by RegisterImage for " + image.getName());
+ snapshot.setStartTime(Instant.now());
+ snapshot.setVolumeSize(ebs.getVolumeSize());
+ snapshot.setEncrypted(Boolean.TRUE.equals(ebs.getEncrypted()));
+ snapshot.setRegion(region);
+ return snapshot;
+ }
+
+ private boolean matchesSnapshotFilters(Snapshot snapshot, Map<String, List<String>> filters) {
+ if (filters == null || filters.isEmpty()) {
+ return true;
+ }
+ for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
+ if (!matchesSnapshotFilter(snapshot, filter.getKey(), filter.getValue())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean matchesSnapshotOwners(Snapshot snapshot, List<String> ownerIds) {
+ if (ownerIds == null || ownerIds.isEmpty()) {
+ return accountId.equals(snapshot.getOwnerId());
+ }
+ return ownerIds.contains(snapshot.getOwnerId())
+ || ownerIds.contains("self") && accountId.equals(snapshot.getOwnerId());
+ }
+
+ private boolean matchesSnapshotFilter(Snapshot snapshot, String name, List<String> values) {
+ return switch (name) {
+ case "description" -> matchesFilterValue(values, snapshot.getDescription());
+ case "owner-id" -> matchesFilterValue(values, snapshot.getOwnerId());
+ case "progress" -> matchesFilterValue(values, snapshot.getProgress());
+ case "snapshot-id" -> matchesFilterValue(values, snapshot.getSnapshotId());
+ case "status" -> matchesFilterValue(values, snapshot.getState());
+ case "volume-id" -> matchesFilterValue(values, snapshot.getVolumeId());
+ case "volume-size" -> matchesFilterValue(values,
+ snapshot.getVolumeSize() != null ? String.valueOf(snapshot.getVolumeSize()) : null);
+ default -> true;
+ };
+ }
+
private boolean matchesFilterValue(List<String> patterns, String value) {
if (patterns == null || patterns.isEmpty()) {
return true;
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/BlockDeviceMapping.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/BlockDeviceMapping.java
new file mode 100644
index 0000000000..877810d2d9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/BlockDeviceMapping.java
@@ -0,0 +1,20 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class BlockDeviceMapping {
+
+ private String deviceName;
+ private EbsBlockDevice ebs;
+
+ public BlockDeviceMapping() {}
+
+ public String getDeviceName() { return deviceName; }
+ public void setDeviceName(String deviceName) { this.deviceName = deviceName; }
+
+ public EbsBlockDevice getEbs() { return ebs; }
+ public void setEbs(EbsBlockDevice ebs) { this.ebs = ebs; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/EbsBlockDevice.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/EbsBlockDevice.java
new file mode 100644
index 0000000000..dbdba11e60
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/EbsBlockDevice.java
@@ -0,0 +1,32 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class EbsBlockDevice {
+
+ private String snapshotId;
+ private Integer volumeSize;
+ private String volumeType;
+ private Boolean deleteOnTermination;
+ private Boolean encrypted;
+
+ public EbsBlockDevice() {}
+
+ public String getSnapshotId() { return snapshotId; }
+ public void setSnapshotId(String snapshotId) { this.snapshotId = snapshotId; }
+
+ public Integer getVolumeSize() { return volumeSize; }
+ public void setVolumeSize(Integer volumeSize) { this.volumeSize = volumeSize; }
+
+ public String getVolumeType() { return volumeType; }
+ public void setVolumeType(String volumeType) { this.volumeType = volumeType; }
+
+ public Boolean getDeleteOnTermination() { return deleteOnTermination; }
+ public void setDeleteOnTermination(Boolean deleteOnTermination) { this.deleteOnTermination = deleteOnTermination; }
+
+ public Boolean getEncrypted() { return encrypted; }
+ public void setEncrypted(Boolean encrypted) { this.encrypted = encrypted; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java
index 2d64aa0d4d..08191eca55 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java
@@ -24,6 +24,8 @@ public class Image {
private String platform;
private String imageOwnerAlias = "amazon";
private String creationDate;
+ private String region;
+ private List<BlockDeviceMapping> blockDeviceMappings = new ArrayList<>();
private List<Tag> tags = new ArrayList<>();
public Image() {}
@@ -70,6 +72,12 @@ public class Image {
public String getCreationDate() { return creationDate; }
public void setCreationDate(String creationDate) { this.creationDate = creationDate; }
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<BlockDeviceMapping> getBlockDeviceMappings() { return blockDeviceMappings; }
+ public void setBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) { this.blockDeviceMappings = blockDeviceMappings; }
+
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Snapshot.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Snapshot.java
new file mode 100644
index 0000000000..2a4c475ba1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Snapshot.java
@@ -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 Snapshot {
+
+ private String snapshotId;
+ private String volumeId;
+ private Integer volumeSize;
+ private String ownerId;
+ private String state = "completed";
+ private String description;
+ private Instant startTime;
+ private String progress = "100%";
+ private boolean encrypted;
+ private String region;
+ private List<Tag> tags = new ArrayList<>();
+
+ public Snapshot() {}
+
+ public String getSnapshotId() { return snapshotId; }
+ public void setSnapshotId(String snapshotId) { this.snapshotId = snapshotId; }
+
+ public String getVolumeId() { return volumeId; }
+ public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
+
+ public Integer getVolumeSize() { return volumeSize; }
+ public void setVolumeSize(Integer volumeSize) { this.volumeSize = volumeSize; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public Instant getStartTime() { return startTime; }
+ public void setStartTime(Instant startTime) { this.startTime = startTime; }
+
+ public String getProgress() { return progress; }
+ public void setProgress(String progress) { this.progress = progress; }
+
+ public boolean isEncrypted() { return encrypted; }
+ public void setEncrypted(boolean encrypted) { this.encrypted = encrypted; }
+
+ 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; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
index 5e3e5b0652..84033dbda0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
@@ -53,6 +53,7 @@ class Ec2IntegrationTest {
private static String launchTemplateId;
private static String vpcEndpointId;
private static String natGatewayId;
+ private static String registeredImageId;
// =========================================================================
// Default resources
@@ -242,6 +243,139 @@ class Ec2IntegrationTest {
.body("DescribeImagesResponse.imagesSet.item.architecture", everyItem(equalTo("arm64")));
}
+ @Test
+ @Order(10)
+ void registerImageCreatesDescribableImageWithSnapshotMapping() {
+ registeredImageId = given()
+ .formParam("Action", "RegisterImage")
+ .formParam("Name", "test-image")
+ .formParam("Description", "test image")
+ .formParam("Architecture", "x86_64")
+ .formParam("RootDeviceName", "/dev/sda1")
+ .formParam("BlockDeviceMapping.1.DeviceName", "/dev/sda1")
+ .formParam("BlockDeviceMapping.1.Ebs.SnapshotId", "snap-1234567890abcdef0")
+ .formParam("BlockDeviceMapping.1.Ebs.VolumeSize", "8")
+ .formParam("BlockDeviceMapping.1.Ebs.VolumeType", "gp3")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("RegisterImageResponse.imageId", startsWith("ami-"))
+ .extract().path("RegisterImageResponse.imageId");
+
+ given()
+ .formParam("Action", "DescribeImages")
+ .formParam("Filter.1.Name", "name")
+ .formParam("Filter.1.Value.1", "test-image")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeImagesResponse.imagesSet.item.imageId", equalTo(registeredImageId))
+ .body("DescribeImagesResponse.imagesSet.item.blockDeviceMapping.item.ebs.snapshotId",
+ equalTo("snap-1234567890abcdef0"));
+ }
+
+ @Test
+ @Order(11)
+ void describeSnapshotsReturnsRegisteredImageSnapshot() {
+ given()
+ .formParam("Action", "DescribeSnapshots")
+ .formParam("SnapshotId.1", "snap-1234567890abcdef0")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeSnapshotsResponse.snapshotSet.item.snapshotId", equalTo("snap-1234567890abcdef0"))
+ .body("DescribeSnapshotsResponse.snapshotSet.item.status", equalTo("completed"))
+ .body("DescribeSnapshotsResponse.snapshotSet.item.volumeSize", equalTo("8"));
+ }
+
+ @Test
+ @Order(12)
+ void describeSnapshotsAcceptsOwnerIdParameter() {
+ given()
+ .formParam("Action", "DescribeSnapshots")
+ .formParam("SnapshotId.1", "snap-1234567890abcdef0")
+ .formParam("OwnerId.1", "self")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeSnapshotsResponse.snapshotSet.item.snapshotId", equalTo("snap-1234567890abcdef0"));
+ }
+
+ @Test
+ @Order(13)
+ void describeSnapshotsAcceptsOwnerIdsParameter() {
+ given()
+ .formParam("Action", "DescribeSnapshots")
+ .formParam("SnapshotId.1", "snap-1234567890abcdef0")
+ .formParam("OwnerIds.1", "000000000000")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeSnapshotsResponse.snapshotSet.item.snapshotId", equalTo("snap-1234567890abcdef0"));
+ }
+
+ @Test
+ @Order(14)
+ void registerImageRejectsInvalidBlockDeviceVolumeSize() {
+ given()
+ .formParam("Action", "RegisterImage")
+ .formParam("Name", "bad-volume-size-image")
+ .formParam("BlockDeviceMapping.1.DeviceName", "/dev/sda1")
+ .formParam("BlockDeviceMapping.1.Ebs.VolumeSize", "large")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
+ }
+
+ @Test
+ @Order(15)
+ void registerImageRejectsInvalidBlockDeviceBoolean() {
+ given()
+ .formParam("Action", "RegisterImage")
+ .formParam("Name", "bad-boolean-image")
+ .formParam("BlockDeviceMapping.1.DeviceName", "/dev/sda1")
+ .formParam("BlockDeviceMapping.1.Ebs.Encrypted", "sometimes")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
+ }
+
+ @Test
+ @Order(16)
+ void registerImageRejectsBlockDeviceMappingWithoutDeviceName() {
+ given()
+ .formParam("Action", "RegisterImage")
+ .formParam("Name", "missing-device-image")
+ .formParam("BlockDeviceMapping.1.Ebs.SnapshotId", "snap-missing-device")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
+ }
+
@Test
@Order(17)
void describeInstanceTypes() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java
index 4a0c63043c..3009e50c75 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java
@@ -5,8 +5,11 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
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.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InternetGateway;
+import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
import io.github.hectorvent.floci.services.ec2.model.KeyPair;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
@@ -14,12 +17,14 @@ import io.github.hectorvent.floci.services.ec2.model.NatGateway;
import io.github.hectorvent.floci.services.ec2.model.RouteTable;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
+import io.github.hectorvent.floci.services.ec2.model.Snapshot;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.Volume;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
import io.github.hectorvent.floci.services.ec2.model.SpotInstanceRequest;
+import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -65,10 +70,42 @@ class Ec2ServicePersistenceTest {
assertEquals("10.0.1.0/24", subnets.get(0).getCidrBlock());
}
+ @Test
+ void registeredImageAndSnapshotSurviveRestart(@TempDir Path dir) {
+ Ec2Service first = newService(dir);
+ Image image = first.registerImage(REGION, "persisted-image", "persisted image", "x86_64",
+ "/dev/sda1", List.of(blockDeviceMapping("snap-persisted", 12)));
+
+ Ec2Service restarted = newService(dir);
+
+ List<Image> images = restarted.describeImages(REGION, List.of(image.getImageId()), List.of(), Map.of());
+ assertEquals(1, images.size(), "registered image must survive restart");
+ assertEquals("persisted-image", images.getFirst().getName());
+ assertEquals("snap-persisted",
+ images.getFirst().getBlockDeviceMappings().getFirst().getEbs().getSnapshotId());
+
+ List<Snapshot> snapshots = restarted.describeSnapshots(REGION, List.of("snap-persisted"), List.of(), Map.of());
+ assertEquals(1, snapshots.size(), "linked snapshot must survive restart");
+ assertEquals(12, snapshots.getFirst().getVolumeSize());
+ }
+
+ private BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
+ EbsBlockDevice ebs = new EbsBlockDevice();
+ ebs.setSnapshotId(snapshotId);
+ ebs.setVolumeSize(volumeSize);
+ BlockDeviceMapping mapping = new BlockDeviceMapping();
+ mapping.setDeviceName("/dev/sda1");
+ mapping.setEbs(ebs);
+ return mapping;
+ }
+
private Ec2Service newService(Path dir) {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
- return new Ec2Service(config, null, null, null, null, new Ec2InstanceTypeCatalog(),
+ Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
+ return new Ec2Service(config, null, mock(Ec2PortForwardManager.class),
+ new AmiImageResolver(imageCatalog), imageCatalog,
+ new Ec2InstanceTypeCatalog(),
load(dir, "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),
load(dir, "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),
load(dir, "ec2-security-groups.json", new TypeReference<Map<String, SecurityGroup>>() {}),
@@ -79,6 +116,8 @@ class Ec2ServicePersistenceTest {
load(dir, "ec2-addresses.json", new TypeReference<Map<String, Address>>() {}),
load(dir, "ec2-instances.json", new TypeReference<Map<String, Instance>>() {}),
load(dir, "ec2-volumes.json", new TypeReference<Map<String, Volume>>() {}),
+ load(dir, "ec2-registered-images.json", new TypeReference<Map<String, Image>>() {}),
+ load(dir, "ec2-snapshots.json", new TypeReference<Map<String, Snapshot>>() {}),
load(dir, "ec2-launch-templates.json", new TypeReference<Map<String, LaunchTemplate>>() {}),
load(dir, "ec2-vpc-endpoints.json", new TypeReference<Map<String, VpcEndpoint>>() {}),
load(dir, "ec2-nat-gateways.json", new TypeReference<Map<String, NatGateway>>() {}),
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
index f711c387be..1e8faa3235 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
@@ -7,12 +7,15 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
+import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
+import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
+import io.github.hectorvent.floci.services.ec2.model.Snapshot;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
import org.junit.jupiter.api.Test;
@@ -245,6 +248,71 @@ class Ec2ServiceTest {
assertEquals("InvalidGroup.NotFound", error.getErrorCode());
}
+ @Test
+ void registerImageNamesAreScopedToRegion() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory());
+
+ service.registerImage("us-east-1", "shared-name", null, null, null, List.of());
+ service.registerImage("us-west-2", "shared-name", null, null, null, List.of());
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.registerImage("us-east-1", "shared-name", null, null, null, List.of()));
+ assertEquals("InvalidAMIName.Duplicate", error.getErrorCode());
+ }
+
+ @Test
+ void registerImageReusingSnapshotDoesNotOverwriteSnapshotMetadata() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory());
+
+ service.registerImage("us-east-1", "first-image", null, null, null,
+ List.of(blockDeviceMapping("snap-reused", 8)));
+ service.registerImage("us-east-1", "second-image", null, null, null,
+ List.of(blockDeviceMapping("snap-reused", 64)));
+
+ List<Snapshot> snapshots = service.describeSnapshots("us-east-1", List.of("snap-reused"), List.of(), Map.of());
+ assertEquals(1, snapshots.size());
+ assertEquals(8, snapshots.getFirst().getVolumeSize());
+ assertEquals("Created by RegisterImage for first-image", snapshots.getFirst().getDescription());
+ }
+
+ @Test
+ void describeSnapshotsDefaultsToOwnedSnapshots() {
+ InMemoryStorage<String, Snapshot> snapshotStore = new InMemoryStorage<>();
+ Snapshot foreign = new Snapshot();
+ foreign.setSnapshotId("snap-foreign");
+ foreign.setOwnerId("111111111111");
+ foreign.setRegion("us-east-1");
+ snapshotStore.put("us-east-1::snap-foreign", foreign);
+
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory(Map.of("ec2-snapshots.json", snapshotStore)));
+ service.registerImage("us-east-1", "owned-image", null, null, null,
+ List.of(blockDeviceMapping("snap-owned", 16)));
+
+ List<Snapshot> snapshots = service.describeSnapshots("us-east-1", List.of(), List.of(), Map.of());
+
+ assertEquals(1, snapshots.size());
+ assertEquals("snap-owned", snapshots.getFirst().getSnapshotId());
+ }
+
+ private static BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
+ EbsBlockDevice ebs = new EbsBlockDevice();
+ ebs.setSnapshotId(snapshotId);
+ ebs.setVolumeSize(volumeSize);
+ BlockDeviceMapping mapping = new BlockDeviceMapping();
+ mapping.setDeviceName("/dev/sda1");
+ mapping.setEbs(ebs);
+ return mapping;
+ }
+
private static EmulatorConfig mockConfig(boolean ec2Mock) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
@@ -257,13 +325,25 @@ class Ec2ServiceTest {
}
private static final class InMemoryStorageFactory extends StorageFactory {
+ private final Map<String, StorageBackend<String, ?>> overrides;
+
private InMemoryStorageFactory() {
+ this(Map.of());
+ }
+
+ private InMemoryStorageFactory(Map<String, StorageBackend<String, ?>> overrides) {
super(null, null);
+ this.overrides = overrides;
}
@Override
+ @SuppressWarnings("unchecked")
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
+ StorageBackend<String, ?> override = overrides.get(fileName);
+ if (override != null) {
+ return (StorageBackend<String, V>) override;
+ }
return new InMemoryStorage<>();
}
}