Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(ec2): support CreateImage (create AMI from instance) (#1979)

lex0030a61646ac22
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 9e315711fe..122fcd3a27 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -225,6 +225,8 @@ Floci seeds the following resources on first use in each region so Terraform, th
| Action | Description |
|--------|-------------|
| DescribeImages | Returns AMI metadata known to the local EC2 service. |
+| CreateImage | Captures an instance as a new AMI. Reboots the source unless `NoReboot=true`. |
+| RegisterImage | Registers an AMI from supplied metadata and block device mappings. |
### Tags
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 4120f5d53c..8a7009c6f6 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
@@ -113,6 +113,7 @@ public class Ec2QueryHandler {
case "ImportKeyPair" -> handleImportKeyPair(params, region);
// AMIs
case "DescribeImages" -> handleDescribeImages(params, region);
+ case "CreateImage" -> handleCreateImage(params, region);
case "RegisterImage" -> handleRegisterImage(params, region);
case "DescribeSnapshots" -> handleDescribeSnapshots(params, region);
// Tags
@@ -1504,6 +1505,21 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+ private Response handleCreateImage(MultivaluedMap<String, String> p, String region) {
+ Image image = service.createImage(
+ region,
+ p.getFirst("InstanceId"),
+ p.getFirst("Name"),
+ p.getFirst("Description"),
+ Boolean.parseBoolean(p.getFirst("NoReboot")));
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateImageResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("imageId", image.getImageId())
+ .end("CreateImageResponse");
+ return xmlResponse(xml.build());
+ }
+
private Response handleRegisterImage(MultivaluedMap<String, String> p, String region) {
Image image = service.registerImage(
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 af94ec505b..56b2e57ebe 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
@@ -88,6 +88,8 @@ public class Ec2Service implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(Ec2Service.class);
private static final DateTimeFormatter ISO_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneOffset.UTC);
+ private static final int DEFAULT_ROOT_VOLUME_SIZE_GIB = 8;
+ private static final String DEFAULT_ROOT_VOLUME_TYPE = "gp3";
private final String accountId;
private final EmulatorConfig config;
@@ -953,8 +955,8 @@ public class Ec2Service implements ContainerTeardown {
Volume rootVol = new Volume();
rootVol.setVolumeId(rootVolId);
rootVol.setAvailabilityZone(az);
- rootVol.setVolumeType("gp3");
- rootVol.setSize(8);
+ rootVol.setVolumeType(DEFAULT_ROOT_VOLUME_TYPE);
+ rootVol.setSize(DEFAULT_ROOT_VOLUME_SIZE_GIB);
rootVol.setState("in-use");
rootVol.setRegion(region);
rootVol.setCreateTime(Instant.now());
@@ -972,7 +974,9 @@ public class Ec2Service implements ContainerTeardown {
reservation.getInstances().add(inst);
if (!config.services().ec2().mock()) {
- ResolvedAmiImage dockerImage = amiImageResolver.resolveImage(imageId);
+ // A CreateImage AMI is not in the catalog, so resolve through its source.
+ ResolvedAmiImage dockerImage =
+ amiImageResolver.resolveImage(resolveLaunchableImageId(region, imageId));
String publicKey = null;
if (keyName != null) {
KeyPair kp = findKeyPair(region, keyName);
@@ -2006,6 +2010,156 @@ public class Ec2Service implements ContainerTeardown {
return images;
}
+ public Image createImage(String region, String instanceId, String name, String description,
+ boolean noReboot) {
+ ensureDefaultResources(region);
+ if (instanceId == null || instanceId.isBlank()) {
+ throw new AwsException("MissingParameter", "The request must contain the parameter InstanceId", 400);
+ }
+ Instance source = getRequiredInstance(region, instanceId);
+
+ // AWS reboots the source instance by default so the image is captured from a quiesced
+ // file system; NoReboot=true opts out and accepts the integrity risk.
+ if (!noReboot) {
+ rebootInstances(region, List.of(instanceId));
+ }
+
+ // The new AMI inherits what it was captured from rather than the registerImage defaults,
+ // so DescribeImages does not report a generic x86_64 / /dev/sda1 image with no devices.
+ Image sourceImage = findImageForCapture(region, source.getImageId());
+ Image image = registerImage(region, name, description,
+ sourceImage != null ? sourceImage.getArchitecture() : null,
+ sourceImage != null ? sourceImage.getRootDeviceName() : null,
+ captureBlockDeviceMappings(region, source, sourceImage));
+
+ // Carry the launchable ancestor so RunInstances on this AMI starts the same guest instead
+ // of falling through to the catalog default.
+ image.setSourceImageId(resolveLaunchableImageId(region, source.getImageId()));
+ registeredImages.put(key(region, image.getImageId()), image);
+ return image;
+ }
+
+ /**
+ * The devices the captured AMI reports. AWS captures what the source AMI describes plus any
+ * volume attached to the instance afterwards, so a data volume added post-launch is part of
+ * the image rather than being dropped.
+ */
+ private List<BlockDeviceMapping> captureBlockDeviceMappings(String region, Instance source,
+ Image sourceImage) {
+ List<BlockDeviceMapping> mappings = new ArrayList<>(sourceImageMappings(sourceImage));
+ Set<String> devices = mappings.stream()
+ .map(BlockDeviceMapping::getDeviceName)
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ for (Volume volume : volumes.scan(k -> true)) {
+ if (!region.equals(volume.getRegion())
+ || volume.getVolumeId().equals(source.getRootVolumeId())) {
+ continue;
+ }
+ for (VolumeAttachment attachment : volume.getAttachments()) {
+ if (!source.getInstanceId().equals(attachment.getInstanceId())
+ || !devices.add(attachment.getDevice())) {
+ continue;
+ }
+ mappings.add(attachedMapping(volume, attachment));
+ }
+ }
+ return mappings.isEmpty() ? null : mappings;
+ }
+
+ /** The device an attached volume contributes, snapshotted as of the capture. */
+ private BlockDeviceMapping attachedMapping(Volume volume, VolumeAttachment attachment) {
+ EbsBlockDevice ebs = new EbsBlockDevice();
+ ebs.setSnapshotId("snap-" + randomHex(17));
+ ebs.setVolumeSize(volume.getSize());
+ ebs.setVolumeType(volume.getVolumeType());
+ ebs.setDeleteOnTermination(attachment.isDeleteOnTermination());
+ ebs.setEncrypted(volume.isEncrypted());
+ BlockDeviceMapping mapping = new BlockDeviceMapping();
+ mapping.setDeviceName(attachment.getDevice());
+ mapping.setEbs(ebs);
+ return mapping;
+ }
+
+ /**
+ * A registered source carries its own mappings, while a catalog entry describes only its root
+ * device, so the root is rebuilt from that rather than leaving the capture with no devices.
+ */
+ private List<BlockDeviceMapping> sourceImageMappings(Image sourceImage) {
+ if (sourceImage == null) {
+ return List.of();
+ }
+ List<BlockDeviceMapping> declared = sourceImage.getBlockDeviceMappings();
+ if (declared != null && !declared.isEmpty()) {
+ return declared.stream().map(this::recapture).toList();
+ }
+ String rootDeviceName = sourceImage.getRootDeviceName();
+ if (rootDeviceName == null || rootDeviceName.isBlank()) {
+ return List.of();
+ }
+ EbsBlockDevice ebs = new EbsBlockDevice();
+ ebs.setSnapshotId("snap-" + randomHex(17));
+ ebs.setVolumeSize(DEFAULT_ROOT_VOLUME_SIZE_GIB);
+ ebs.setVolumeType(DEFAULT_ROOT_VOLUME_TYPE);
+ ebs.setDeleteOnTermination(true);
+ BlockDeviceMapping mapping = new BlockDeviceMapping();
+ mapping.setDeviceName(rootDeviceName);
+ mapping.setEbs(ebs);
+ return List.of(mapping);
+ }
+
+ /**
+ * A capture takes its own snapshot of each device. Handing back the source AMI's snapshot ids
+ * would leave two images sharing one snapshot, so deleting either would appear to take the
+ * other's backing with it.
+ */
+ private BlockDeviceMapping recapture(BlockDeviceMapping source) {
+ BlockDeviceMapping mapping = new BlockDeviceMapping();
+ mapping.setDeviceName(source.getDeviceName());
+ EbsBlockDevice sourceEbs = source.getEbs();
+ if (sourceEbs == null) {
+ return mapping;
+ }
+ EbsBlockDevice ebs = new EbsBlockDevice();
+ ebs.setSnapshotId(sourceEbs.getSnapshotId() != null ? "snap-" + randomHex(17) : null);
+ ebs.setVolumeSize(sourceEbs.getVolumeSize());
+ ebs.setVolumeType(sourceEbs.getVolumeType());
+ ebs.setDeleteOnTermination(sourceEbs.getDeleteOnTermination());
+ ebs.setEncrypted(sourceEbs.getEncrypted());
+ mapping.setEbs(ebs);
+ return mapping;
+ }
+
+ /** The image a CreateImage source was launched from, whether catalog-backed or registered. */
+ private Image findImageForCapture(String region, String imageId) {
+ if (imageId == null || imageId.isBlank()) {
+ return null;
+ }
+ Image registered = registeredImages.get(key(region, imageId)).orElse(null);
+ if (registered != null) {
+ return registered;
+ }
+ return imageCatalog.findByIdOrAlias(imageId)
+ .map(Ec2ImageCatalog.CatalogImage::toImage)
+ .orElse(null);
+ }
+
+ /**
+ * Follows CreateImage ancestry back to an id the AMI resolver can map to a guest image.
+ * Images from RegisterImage have no source and stop the walk, as does a catalog id.
+ */
+ private String resolveLaunchableImageId(String region, String imageId) {
+ String current = imageId;
+ for (int hops = 0; hops < 16 && current != null; hops++) {
+ Image registered = registeredImages.get(key(region, current)).orElse(null);
+ if (registered == null || registered.getSourceImageId() == null) {
+ return current;
+ }
+ current = registered.getSourceImageId();
+ }
+ return current;
+ }
+
public Image registerImage(String region, String name, String description, String architecture,
String rootDeviceName, List<BlockDeviceMapping> blockDeviceMappings) {
if (name == null || name.isBlank()) {
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 08191eca55..c34c27aeb7 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
@@ -25,6 +25,12 @@ public class Image {
private String imageOwnerAlias = "amazon";
private String creationDate;
private String region;
+ /**
+ * For images produced by CreateImage: the AMI the source instance was launched from. Not an
+ * EC2 field — Floci uses it to resolve the guest image to run, since a generated ami-* id is
+ * not in the catalog and would otherwise fall back to the default guest.
+ */
+ private String sourceImageId;
private List<BlockDeviceMapping> blockDeviceMappings = new ArrayList<>();
private List<Tag> tags = new ArrayList<>();
@@ -75,6 +81,9 @@ public class Image {
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
+ public String getSourceImageId() { return sourceImageId; }
+ public void setSourceImageId(String sourceImageId) { this.sourceImageId = sourceImageId; }
+
public List<BlockDeviceMapping> getBlockDeviceMappings() { return blockDeviceMappings; }
public void setBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) { this.blockDeviceMappings = blockDeviceMappings; }
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 025a354205..8de108f85f 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
@@ -247,6 +247,133 @@ class Ec2IntegrationTest {
.body("DescribeImagesResponse.imagesSet.item.architecture", everyItem(equalTo("arm64")));
}
+ @Test
+ // Runs after the DescribeNetworkInterfaces pagination tests at @Order(92), like the
+ // metadata test below. Terminating the source instance is not enough on its own:
+ // TerminateInstances flips the state to shutting-down synchronously and only reaches
+ // terminated on a background task, and describeNetworkInterfaces filters on terminated.
+ @Order(322)
+ void createImageFromInstanceReturnsDescribableAmi() {
+ String imgInstanceId = given()
+ .formParam("Action", "RunInstances")
+ .formParam("ImageId", "ami-createimage-src")
+ .formParam("InstanceType", "t3.micro")
+ .formParam("MinCount", "1")
+ .formParam("MaxCount", "1")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("RunInstancesResponse.instancesSet.item.instanceId");
+
+ String amiId = given()
+ .formParam("Action", "CreateImage")
+ .formParam("InstanceId", imgInstanceId)
+ .formParam("Name", "created-from-instance")
+ .formParam("Description", "CreateImage test")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("CreateImageResponse.imageId", startsWith("ami-"))
+ .extract().path("CreateImageResponse.imageId");
+
+ given()
+ .formParam("Action", "DescribeImages")
+ .formParam("ImageId.1", amiId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeImagesResponse.imagesSet.item.name", equalTo("created-from-instance"));
+
+ // The source instance is terminated here rather than left running: the
+ // DescribeNetworkInterfaces pagination tests at @Order(92) assert that the
+ // final page carries no nextToken, which an extra live ENI would break.
+ given()
+ .formParam("Action", "TerminateInstances")
+ .formParam("InstanceId.1", imgInstanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ // Runs last: it launches two extra instances, and the DescribeNetworkInterfaces
+ // pagination tests at @Order(92) assert on exact ENI counts.
+ @Order(321)
+ void createImageInheritsTheSourceImageMetadata() {
+ // An arm64 source: a created AMI that reported the registerImage defaults would come
+ // back x86_64 here, which is the whole point of the assertion.
+ String armInstanceId = given()
+ .formParam("Action", "RunInstances")
+ .formParam("ImageId", "ami-ubuntu2404-arm64")
+ .formParam("InstanceType", "t4g.micro")
+ .formParam("MinCount", "1")
+ .formParam("MaxCount", "1")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("RunInstancesResponse.instancesSet.item.instanceId");
+
+ String amiId = given()
+ .formParam("Action", "CreateImage")
+ .formParam("InstanceId", armInstanceId)
+ .formParam("Name", "created-from-arm-instance")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CreateImageResponse.imageId");
+
+ given()
+ .formParam("Action", "DescribeImages")
+ .formParam("ImageId.1", amiId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeImagesResponse.imagesSet.item.architecture", equalTo("arm64"));
+
+ // The created AMI is launchable, not just describable.
+ given()
+ .formParam("Action", "RunInstances")
+ .formParam("ImageId", amiId)
+ .formParam("InstanceType", "t4g.micro")
+ .formParam("MinCount", "1")
+ .formParam("MaxCount", "1")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("RunInstancesResponse.instancesSet.item.imageId", equalTo(amiId));
+ }
+
+ @Test
+ @Order(10)
+ void createImageRequiresExistingInstance() {
+ given()
+ .formParam("Action", "CreateImage")
+ .formParam("InstanceId", "i-doesnotexist12345")
+ .formParam("Name", "should-not-exist")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400);
+ }
+
@Test
@Order(10)
void registerImageCreatesDescribableImageWithSnapshotMapping() {
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 0518511ab5..c76e1ced1b 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
@@ -9,6 +9,7 @@ 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.Image;
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.ManagedPrefixList;
@@ -26,12 +27,19 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -481,6 +489,133 @@ class Ec2ServiceTest {
assertEquals("snap-owned", snapshots.getFirst().getSnapshotId());
}
+ @Test
+ void createImageRebootsTheSourceInstanceUnlessNoRebootIsSet() {
+ Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
+ Ec2Service service = liveService(containerManager, mock(AmiImageResolver.class));
+ String instanceId = runOne(service, "ami-src");
+
+ service.createImage("us-east-1", instanceId, "with-reboot", null, false);
+ verify(containerManager).reboot(argThat(i -> instanceId.equals(i.getInstanceId())));
+
+ service.createImage("us-east-1", instanceId, "without-reboot", null, true);
+ // Still one: NoReboot=true opted the second call out.
+ verify(containerManager, times(1)).reboot(argThat(i -> instanceId.equals(i.getInstanceId())));
+ }
+
+ @Test
+ void runInstancesOnACreatedImageResolvesTheSourceGuest() {
+ AmiImageResolver resolver = mock(AmiImageResolver.class);
+ Ec2Service service = liveService(mock(Ec2ContainerManager.class), resolver);
+ String instanceId = runOne(service, "ami-src");
+
+ String createdAmi = service.createImage("us-east-1", instanceId, "captured", null, true)
+ .getImageId();
+ String chainedAmi = service.createImage("us-east-1", runOne(service, createdAmi),
+ "captured-again", null, true).getImageId();
+
+ runOne(service, createdAmi);
+ runOne(service, chainedAmi);
+
+ // Every launch resolves through to the catalog id; the generated ami-* ids are
+ // unknown to the resolver and would otherwise fall back to the default guest.
+ verify(resolver, times(4)).resolveImage("ami-src");
+ verify(resolver, never()).resolveImage(createdAmi);
+ verify(resolver, never()).resolveImage(chainedAmi);
+ }
+
+ @Test
+ void createImageOnACatalogSourceCarriesItsRootDevice() {
+ Ec2ImageCatalog catalog = mock(Ec2ImageCatalog.class);
+ Ec2ImageCatalog.CatalogImage source = new Ec2ImageCatalog.CatalogImage();
+ source.imageId = "ami-src";
+ source.architecture = "x86_64";
+ source.rootDeviceType = "ebs";
+ source.rootDeviceName = "/dev/xvda";
+ when(catalog.findByIdOrAlias("ami-src")).thenReturn(Optional.of(source));
+ Ec2Service service = liveService(mock(Ec2ContainerManager.class), mock(AmiImageResolver.class), catalog);
+ String instanceId = runOne(service, "ami-src");
+
+ Image image = service.createImage("us-east-1", instanceId, "captured", null, true);
+
+ assertEquals("/dev/xvda", image.getRootDeviceName());
+ assertEquals(1, image.getBlockDeviceMappings().size());
+ BlockDeviceMapping root = image.getBlockDeviceMappings().getFirst();
+ assertEquals("/dev/xvda", root.getDeviceName());
+ assertNotNull(root.getEbs().getSnapshotId());
+
+ // The rebuilt root describes the volume RunInstances actually created for the
+ // source, so DescribeImages does not report a type the instance never had.
+ assertEquals("gp3", root.getEbs().getVolumeType());
+ assertEquals(8, root.getEbs().getVolumeSize());
+
+ // The mapping's snapshot is registered, so DescribeSnapshots can resolve it.
+ List<Snapshot> snapshots = service.describeSnapshots("us-east-1",
+ List.of(root.getEbs().getSnapshotId()), null, null);
+ assertEquals(1, snapshots.size());
+ }
+
+ @Test
+ void createImageTakesItsOwnSnapshotRatherThanTheSourceAmisOne() {
+ Ec2Service service = liveService(mock(Ec2ContainerManager.class), mock(AmiImageResolver.class));
+ Image source = service.registerImage("us-east-1", "source-image", null, null, "/dev/sda1",
+ List.of(blockDeviceMapping("snap-source", 16)));
+
+ Image image = service.createImage("us-east-1", runOne(service, source.getImageId()),
+ "captured", null, true);
+
+ BlockDeviceMapping captured = image.getBlockDeviceMappings().getFirst();
+ assertEquals("/dev/sda1", captured.getDeviceName());
+ assertEquals(16, captured.getEbs().getVolumeSize());
+ assertNotEquals("snap-source", captured.getEbs().getSnapshotId());
+
+ // Both snapshots exist, so deleting one image does not strand the other.
+ assertEquals(2, service.describeSnapshots("us-east-1", List.of(), List.of(), Map.of()).size());
+ }
+
+ @Test
+ void createImageCapturesAVolumeAttachedAfterLaunch() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
+ Image sourceAmi = service.registerImage("us-east-1", "source-image", null, null, "/dev/sda1",
+ List.of(blockDeviceMapping("snap-source", 8)));
+ Instance inst = service.runInstances("us-east-1", sourceAmi.getImageId(), "t3.micro", 1, 1,
+ null, List.of(), null, null, List.of(), null, null).getInstances().getFirst();
+ inst.setState(InstanceState.running());
+ Volume data = service.createVolume("us-east-1", inst.getPlacement().getAvailabilityZone(),
+ "gp3", 50, false, 0, null, null, List.of());
+ service.attachVolume("us-east-1", data.getVolumeId(), inst.getInstanceId(), "/dev/sdf");
+
+ Image image = service.createImage("us-east-1", inst.getInstanceId(), "captured", null, true);
+
+ // The root device the source AMI describes, plus the volume attached after launch.
+ assertEquals(2, image.getBlockDeviceMappings().size());
+ BlockDeviceMapping attached = image.getBlockDeviceMappings().stream()
+ .filter(m -> "/dev/sdf".equals(m.getDeviceName()))
+ .findFirst().orElseThrow();
+ assertEquals(50, attached.getEbs().getVolumeSize());
+ assertEquals("gp3", attached.getEbs().getVolumeType());
+ assertNotNull(attached.getEbs().getSnapshotId());
+ }
+
+ private static String runOne(Ec2Service service, String imageId) {
+ return service.runInstances("us-east-1", imageId, "t3.micro", 1, 1, null,
+ List.of(), null, null, List.of(), null, null)
+ .getInstances().getFirst().getInstanceId();
+ }
+
+ /** mock=false so the container-manager and resolver interactions actually happen. */
+ private static Ec2Service liveService(Ec2ContainerManager containerManager, AmiImageResolver resolver) {
+ return liveService(containerManager, resolver, mock(Ec2ImageCatalog.class));
+ }
+
+ private static Ec2Service liveService(Ec2ContainerManager containerManager, AmiImageResolver resolver,
+ Ec2ImageCatalog catalog) {
+ return new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class),
+ resolver, catalog, new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
+ }
+
private static BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setSnapshotId(snapshotId);