diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 24f72bfe13..e0a485df44 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1284,7 +1284,7 @@ When `floci.services.ec2.volume-block-devices` is enabled (the default), attache - **Restart reconciliation**: When an instance container stops and starts, or when Floci restarts, attached volume device nodes are automatically restored inside the target container. Backing raw files remain preserved across reboots in persistent storage. - **Metadata-only tracking**: Disabling `floci.services.ec2.volume-block-devices`, EC2 mock mode, unavailable Docker, or a missing or stopped target container retains metadata-only attachment without failing the API call. Stopped instances have their device nodes restored when started. Once physical attachment is attempted, helper, loop-device, or guest device-creation failures return `InternalError` without recording a successful attachment; partial guest devices and loop devices allocated by the failed attempt are cleaned up on a best-effort basis so attachment can be retried. Reused loop devices are retained on failure. Insufficient privileges can cause these failures. Restart reconciliation logs device-restoration failures and keeps the existing attachment records for a later retry. - **Platform requirements**: Requires a Linux Docker environment (native Linux Docker daemon, or Colima / Docker Desktop with a Linux virtual machine) and privileged instance containers. -- **Unmodeled aspects**: Multi-attach is tracked at metadata level only. Automated filesystem formatting (volumes start unformatted like real EBS block devices) and volume encryption at the block layer are not modeled. Root volume backing is logical (container rootfs); `ModifyVolume` updates recorded root volume metadata without modifying container storage, while EBS data volume size increases expand the underlying raw backing file and refresh any attached loop device. Volume type, IOPS, and throughput changes remain recorded metadata without altering device characteristics. +- **Unmodeled aspects**: Multi-attach is tracked at metadata level only. Automated filesystem formatting (volumes start unformatted like real EBS block devices) and volume encryption at the block layer are not modeled. Root volume backing is logical (container rootfs); when `DeleteOnTermination` is enabled, termination removes its metadata and tags without invoking a raw block-device helper. Failed-launch rollback also skips that helper when deleting a logical root that termination preserved. Data volumes still use their backing-storage cleanup; `ModifyVolume` updates recorded root volume metadata without modifying container storage, while EBS data volume size increases expand the underlying raw backing file and refresh any attached loop device. Volume type, IOPS, and throughput changes remain recorded metadata without altering device characteristics. Validation matches AWS behavior: - Unknown volumes are rejected with `InvalidVolume.NotFound`. diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index db33d28d1a..3c309eb4c3 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -16378,6 +16378,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * another instance since stays. */ public List> rollBackLaunch(String region, Reservation launch) { + Set rootVolumeIds = launch.getInstances().stream() + .map(Instance::getRootVolumeId).filter(Objects::nonNull).collect(Collectors.toSet()); try { return terminateInstances(region, launch.getInstances().stream().map(Instance::getInstanceId).toList()); } finally { @@ -16385,7 +16387,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String k = key(region, volumeId); withVolumeLock(volumeId, () -> volumes.get(k) .filter(current -> current.getAttachments().isEmpty()) - .ifPresent(current -> deleteVolumeRecord(region, k, current))); + .ifPresent(current -> deleteVolumeRecord(region, k, current, rootVolumeIds.contains(volumeId)))); } } } @@ -16428,7 +16430,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab boolean attachedElsewhere = vol.getAttachments().stream() .anyMatch(other -> !inst.getInstanceId().equals(other.getInstanceId())); if (att.isDeleteOnTermination() && !attachedElsewhere) { - deleteVolumeRecord(region, storeKey, vol); + deleteVolumeRecord(region, storeKey, vol, root); return; } vol.getAttachments().remove(att); @@ -16441,9 +16443,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } - /** Deletes a volume, its block device and its tags. Called under the volume's lock. */ - private void deleteVolumeRecord(String region, String storeKey, Volume vol) { - if (volumeBlockDeviceManager != null) { + /** Deletes metadata and tags, plus backing storage for data volumes. Called under the volume's lock. */ + private void deleteVolumeRecord(String region, String storeKey, Volume vol, boolean logicalRoot) { + if (!logicalRoot && volumeBlockDeviceManager != null) { volumeBlockDeviceManager.deleteVolume(vol.getVolumeId()); } volumes.delete(storeKey); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index 1de54e2056..1054f8f225 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -539,6 +539,74 @@ class Ec2ServiceTest { .collect(Collectors.toSet())); } + @ParameterizedTest + @ValueSource(strings = {"terminate", "settle", "rollback"}) + void logicalRootDeletionDoesNotRequireABlockDeviceHelper(String operation) { + Ec2VolumeBlockDeviceManager devices = mock(Ec2VolumeBlockDeviceManager.class); + when(devices.isAvailable()).thenReturn(true); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), + null, null, devices); + Reservation launch = service.runInstances("us-east-1", "ami-test", "t3.micro", 1, 1, + null, List.of(), null, null, List.of(), null, null); + Instance instance = launch.getInstances().getFirst(); + String rootId = instance.getRootVolumeId(); + service.createTags("us-east-1", List.of(rootId), List.of(new Tag("Owner", "root"))); + + switch (operation) { + case "terminate" -> service.terminateInstances("us-east-1", List.of(instance.getInstanceId())); + case "rollback" -> service.rollBackLaunch("us-east-1", launch); + case "settle" -> instance.setState(InstanceState.terminated()); + default -> throw new IllegalArgumentException(operation); + } + + assertTrue(service.describeVolumes("us-east-1", List.of(), Map.of()).isEmpty()); + assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(rootId))).isEmpty()); + verify(devices, never()).deleteVolume(anyString()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void rollbackDeletesRetainedLogicalRootWithoutBlockDeviceCleanup(boolean settleFirst) { + Ec2VolumeBlockDeviceManager devices = mock(Ec2VolumeBlockDeviceManager.class); + when(devices.isAvailable()).thenReturn(true); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), + null, null, devices); + LaunchTemplateData.Ebs ebs = new LaunchTemplateData.Ebs(); + ebs.setVolumeSize(5); + ebs.setDeleteOnTermination(false); + LaunchTemplateData.BlockDeviceMapping root = new LaunchTemplateData.BlockDeviceMapping(); + root.setDeviceName("/dev/xvda"); + root.setEbs(ebs); + LaunchTemplateData.BlockDeviceMapping data = new LaunchTemplateData.BlockDeviceMapping(); + data.setDeviceName("/dev/sdf"); + data.setEbs(ebs); + Reservation launch = service.runInstances("us-east-1", "ami-test", "t3.micro", 1, 1, + null, List.of(), null, null, List.of(), null, null, + null, null, 0, null, null, null, null, false, null, null, + List.of(root, data), false, null, null); + Instance instance = launch.getInstances().getFirst(); + String rootId = instance.getRootVolumeId(); + String dataId = launch.getLaunchVolumeIds().stream() + .filter(id -> !rootId.equals(id)).findFirst().orElseThrow(); + service.createTags("us-east-1", List.of(rootId, dataId), List.of(new Tag("Owner", "launch"))); + if (settleFirst) { + instance.setState(InstanceState.terminated()); + assertTrue(service.describeVolumes("us-east-1", List.of(), Map.of()).stream() + .allMatch(volume -> volume.getAttachments().isEmpty())); + } + + service.rollBackLaunch("us-east-1", launch); + + assertTrue(service.describeVolumes("us-east-1", List.of(), Map.of()).isEmpty()); + assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(rootId, dataId))).isEmpty()); + verify(devices, never()).deleteVolume(rootId); + verify(devices).deleteVolume(dataId); + } + private static Reservation launchKeepingADataVolume(Ec2Service service) { LaunchTemplateData.Ebs ebs = new LaunchTemplateData.Ebs(); ebs.setVolumeSize(5);