Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ec2): attach volumes as real block devices (#4354)
Simone Primarosa922402210fd3
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 34909bb4f4..067afdc48c 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -698,7 +698,13 @@ A standalone ENI created via `CreateNetworkInterface` can also be handed to `Run| AttachVolume | Attaches a volume to an instance at the requested device; returns the attachment in `attaching` state. || DetachVolume | Detaches a volume from an instance, optionally forced; returns the attachment in `detaching` state. |-Volumes are tracked as logical metadata records and are not backed by real block storage devices. Volume modifications update recorded state only without resizing an underlying medium. `ModifyVolume` applies attribute updates directly to the volume record and records a modification entry in `completed` state with 100% progress.+When `floci.services.ec2.volume-block-devices` is enabled (the default), attached EBS volumes are backed by real Linux loop devices inside running instance containers and synthesized EKS cluster node containers:+- **Storage mechanism**: Backing sparse raw image files are allocated in Floci storage under `floci-aws-ec2-volumes` (named volume or host path). A privileged helper container (`floci-aws-ec2-volume-helper`, running `floci.services.ec2.volume-helper-image`, default `alpine:3.21`) manages Linux loop devices via `losetup`.+- **Target device nodes**: Inside privileged target instance containers, the corresponding device node is created at the requested path (for example `/dev/xvdf` or `/dev/sdf`) using `mknod` or a symlink to the loop device, matching the exact size specified during volume creation. Target containers can format filesystems (such as ext4 or xfs), mount them, and persist data across detach and reattach.+- **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.+- **Graceful degradation**: If Docker is unavailable, the target instance container is not running, or the container is not privileged, volume attachments degrade gracefully to metadata-only tracking without failing the API call.+- **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), volume encryption at the block layer, and live resizing of underlying raw backing files are not modeled. `ModifyVolume` updates recorded metadata and reports completion without resizing the backing raw image.Validation matches AWS behavior:- Unknown volumes are rejected with `InvalidVolume.NotFound`.diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 024a85cec1..ac79543541 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -2887,6 +2887,17 @@ public interface EmulatorConfig {@WithDefault("alpine/socat")String socatImage();+ /**+ * When true, EBS volumes are backed by real storage and attached as block devices+ * inside target containers. When false or unavailable, attachment remains metadata-only.+ */+ @WithDefault("true")+ boolean volumeBlockDevices();++ /** Image used for the helper container that manages volume loop devices and storage. */+ @WithDefault("alpine:3.21")+ String volumeHelperImage();+/** When true, instances go straight to RUNNING without launching Docker containers. */@WithDefault("false")boolean mock();diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.javaindex 0cce6871e3..92ef4fb613 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java@@ -967,9 +967,19 @@ public class Ec2ContainerManager {* Updates instance state through pending → running.*/public void start(Instance instance) {+ start(instance, null);+ }++ /**+ * Starts a previously stopped container, executing postStart once the container is running.+ */+ public void start(Instance instance, Runnable postStart) {String containerId = instance.getDockerContainerId();if (containerId == null) {instance.setState(InstanceState.running());+ if (postStart != null) {+ postStart.run();+ }return;}instance.setState(InstanceState.pending());@@ -1016,6 +1026,14 @@ public class Ec2ContainerManager {return;}instance.setState(InstanceState.running());+ if (postStart != null) {+ try {+ postStart.run();+ } catch (Exception e) {+ LOG.warnv("Error in post-start hook for instance {0}: {1}",+ instance.getInstanceId(), e.getMessage());+ }+ }});}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.javaindex 55c1c8b852..6c1e405dd0 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@@ -145,6 +145,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {private static final String AWS_MARKETPLACE_OWNER_ID = "679593333241";// The ASN AWS assigns when CreateTransitGateway omits Options.AmazonSideAsn.private static final long DEFAULT_AMAZON_SIDE_ASN = 64512L;+ private static final Pattern DEVICE_NAME_PATTERN = Pattern.compile("^(/dev/)?[a-zA-Z0-9/_-]+$");private static final Pattern TRANSIT_GATEWAY_ID_PATTERN = Pattern.compile("^tgw-[0-9a-f]{8}([0-9a-f]{9})?$");private static final Pattern TRANSIT_GATEWAY_ROUTE_TABLE_ID_PATTERN =Pattern.compile("^tgw-rtb-[0-9a-f]{8}([0-9a-f]{9})?$");@@ -234,11 +235,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {private VpcNetworkManager vpcNetworkManager;private jakarta.enterprise.inject.Instance<ClusterNodeInstanceProvider> clusterNodeInstanceProviders;private ClusterNodeInstanceProvider testClusterNodeInstanceProvider;+ private final Ec2VolumeBlockDeviceManager volumeBlockDeviceManager;void setClusterNodeInstanceProvider(ClusterNodeInstanceProvider provider) {this.testClusterNodeInstanceProvider = provider;}+ void putInstanceForTest(Instance instance) {+ instances.put(key(instance.getRegion(), instance.getInstanceId()), instance);+ }+// Public, no request context - for callers (and tests) that construct this service directly// without CDI. Caller-identity resolution falls back to the configured default account.public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,@@ -267,9 +273,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,VpcNetworkManager vpcNetworkManager, IamService iamService,- jakarta.enterprise.inject.Instance<ClusterNodeInstanceProvider> clusterNodeInstanceProviders) {+ jakarta.enterprise.inject.Instance<ClusterNodeInstanceProvider> clusterNodeInstanceProviders,+ Ec2VolumeBlockDeviceManager volumeBlockDeviceManager) {this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,- instanceTypeCatalog, storageFactory, requestContextInstance, iamService);+ instanceTypeCatalog, storageFactory, requestContextInstance, iamService, volumeBlockDeviceManager);this.vpcNetworkManager = vpcNetworkManager;this.clusterNodeInstanceProviders = clusterNodeInstanceProviders;}@@ -289,6 +296,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,IamService iamService) {+ this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,+ instanceTypeCatalog, storageFactory, requestContextInstance, iamService, null);+ }++ public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,+ Ec2PortForwardManager portForwardManager,+ AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,+ Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,+ jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,+ IamService iamService,+ Ec2VolumeBlockDeviceManager volumeBlockDeviceManager) {this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,storageFactory.create("ec2", "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),storageFactory.create("ec2", "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),@@ -326,7 +344,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {new TypeReference<Map<String, CapacityReservation>>() {}),storageFactory.create("ec2", "ec2-volume-modifications.json",new TypeReference<Map<String, VolumeModification>>() {}),- requestContextInstance, iamService);+ requestContextInstance, iamService, volumeBlockDeviceManager);}// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).@@ -479,7 +497,54 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {StorageBackend<String, VolumeModification> volumeModifications,jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,IamService iamService) {+ this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,+ instanceTypeCatalog, vpcs, subnets, securityGroups, securityGroupRules,+ internetGateways, routeTables, keyPairs, addresses, instances,+ volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,+ natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,+ transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,+ transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,+ networkInterfaces, capacityReservations, volumeModifications,+ requestContextInstance, iamService, null);+ }++ Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,+ Ec2PortForwardManager portForwardManager,+ AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,+ Ec2InstanceTypeCatalog instanceTypeCatalog,+ StorageBackend<String, Vpc> vpcs,+ StorageBackend<String, Subnet> subnets,+ StorageBackend<String, SecurityGroup> securityGroups,+ StorageBackend<String, SecurityGroupRule> securityGroupRules,+ StorageBackend<String, InternetGateway> internetGateways,+ StorageBackend<String, RouteTable> routeTables,+ StorageBackend<String, KeyPair> keyPairs,+ StorageBackend<String, Address> addresses,+ StorageBackend<String, Instance> instances,+ StorageBackend<String, Volume> volumes,+ StorageBackend<String, Image> registeredImages,+ StorageBackend<String, Snapshot> snapshots,+ StorageBackend<String, LaunchTemplate> launchTemplates,+ StorageBackend<String, VpcEndpoint> vpcEndpoints,+ StorageBackend<String, NatGateway> natGateways,+ StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,+ StorageBackend<String, NetworkAcl> networkAcls,+ StorageBackend<String, ManagedPrefixList> managedPrefixLists,+ StorageBackend<String, List<Tag>> tags,+ StorageBackend<String, TransitGateway> transitGateways,+ StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,+ StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,+ StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,+ StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,+ StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,+ StorageBackend<String, NetworkInterface> networkInterfaces,+ StorageBackend<String, CapacityReservation> capacityReservations,+ StorageBackend<String, VolumeModification> volumeModifications,+ jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,+ IamService iamService,+ Ec2VolumeBlockDeviceManager volumeBlockDeviceManager) {this.iamService = iamService;+ this.volumeBlockDeviceManager = volumeBlockDeviceManager;this.defaultAccountId = config.defaultAccountId();this.requestContextInstance = requestContextInstance;this.config = config;@@ -560,12 +625,85 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {if (restored > 0) {LOG.infov("Restored IMDS metadata registration for {0} EC2 container(s)", restored);}+ if (volumeBlockDeviceManager != null && volumeBlockDeviceManager.isAvailable()) {+ restoreAttachedVolumesOnStartup();+ }// Runs after the restore loop, so anything legitimately revived above is already// accounted for and only genuine leftovers are left to collect.containerManager.reconcileOrphanedContainers(this::instanceContainerStillWanted);}+ private void restoreAttachedVolumesOnStartup() {+ Map<String, Volume> allVolumes;+ if (volumes instanceof AccountAwareStorageBackend<?> rawAccountAware) {+ @SuppressWarnings("unchecked")+ AccountAwareStorageBackend<Volume> accountAware = (AccountAwareStorageBackend<Volume>) rawAccountAware;+ allVolumes = accountAware.scanAllAccountsAsMap();+ } else {+ allVolumes = new LinkedHashMap<>();+ for (String k : volumes.keys()) {+ volumes.get(k).ifPresent(v -> allVolumes.put(k, v));+ }+ }++ for (Volume vol : allVolumes.values()) {+ if (vol == null || !"in-use".equals(vol.getState()) || vol.getAttachments().isEmpty()) {+ continue;+ }+ for (VolumeAttachment att : vol.getAttachments()) {+ String reg = vol.getRegion() != null ? vol.getRegion() : config.defaultRegion();+ Instance inst = findAnyInstance(key(reg, att.getInstanceId())).orElse(null);+ if (inst == null) {+ inst = findExternalInstance(defaultAccountId, reg, att.getInstanceId()).orElse(null);+ }+ if (inst == null) {+ continue;+ }+ // Root volume backing is purely logical (Docker container rootfs overlayfs)+ if (vol.getVolumeId().equals(inst.getRootVolumeId())+ || att.getDevice().equals(inst.getRootDeviceName())) {+ continue;+ }+ if (inst.getDockerContainerId() != null+ && containerManager.isContainerRunning(inst.getDockerContainerId())) {+ volumeBlockDeviceManager.attachVolume(vol, inst, att.getDevice());+ }+ }+ }+ }++ public void restoreAttachedVolumesForInstance(String region, Instance inst) {+ if (volumeBlockDeviceManager == null || inst == null) {+ return;+ }+ Map<String, Volume> allVolumes;+ if (volumes instanceof AccountAwareStorageBackend<?> rawAccountAware) {+ @SuppressWarnings("unchecked")+ AccountAwareStorageBackend<Volume> accountAware = (AccountAwareStorageBackend<Volume>) rawAccountAware;+ allVolumes = accountAware.scanAllAccountsAsMap();+ } else {+ allVolumes = new LinkedHashMap<>();+ for (String k : volumes.keys()) {+ volumes.get(k).ifPresent(v -> allVolumes.put(k, v));+ }+ }+ for (Volume vol : allVolumes.values()) {+ if (vol == null || !region.equals(vol.getRegion()) || vol.getAttachments().isEmpty()) {+ continue;+ }+ if (vol.getVolumeId().equals(inst.getRootVolumeId())) {+ continue;+ }+ for (VolumeAttachment att : vol.getAttachments()) {+ if (inst.getInstanceId().equals(att.getInstanceId())+ && (inst.getRootDeviceName() == null || !att.getDevice().equals(inst.getRootDeviceName()))) {+ volumeBlockDeviceManager.attachVolume(vol, inst, att.getDevice());+ }+ }+ }+ }+/*** Whether a container labelled for (region, instanceId) still backs a live instance record.* False means the record is gone or already terminated, so the container is an orphan.@@ -3186,8 +3324,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {}// Delete root volume if deleteOnTermination (matches real AWS behavior)if (inst.getRootVolumeId() != null) {- volumes.delete(key(region, inst.getRootVolumeId()));+ Volume rootVol = volumes.get(key(region, inst.getRootVolumeId())).orElse(null);+ if (rootVol != null) {+ boolean attachedElsewhere = rootVol.getAttachments().stream()+ .anyMatch(a -> !inst.getInstanceId().equals(a.getInstanceId()));+ if (!attachedElsewhere) {+ if (volumeBlockDeviceManager != null) {+ volumeBlockDeviceManager.deleteVolume(inst.getRootVolumeId());+ }+ volumes.delete(key(region, inst.getRootVolumeId()));+ }+ }}+ detachAttachedVolumesOnTermination(region, inst);releaseStandaloneInterfacesOnTermination(region, inst);instances.put(key(region, id), inst);// The last instance depending on a deregistered AMI's capture has just gone away.@@ -3310,7 +3459,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {inst.setState(InstanceState.running());} else {restoreInstanceFirewall(inst);- containerManager.start(inst);+ String accountId = callerAccountId();+ containerManager.start(inst, () ->+ RequestScopes.runAs(accountId, () -> restoreAttachedVolumesForInstance(region, inst)));}instances.put(key(region, id), inst);Map<String, String> entry = new LinkedHashMap<>();@@ -3766,6 +3917,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {copy.setStateReasonCode(source.getStateReasonCode());copy.setStateReasonMessage(source.getStateReasonMessage());copy.setRegion(source.getRegion());+ copy.setDockerContainerId(source.getDockerContainerId());copy.setRootVolumeId(source.getRootVolumeId());copy.setDisableApiStop(source.isDisableApiStop());copy.setDisableApiTermination(source.isDisableApiTermination());@@ -8350,6 +8502,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {vol.setRegion(region);if (volumeTags != null) vol.setTags(new ArrayList<>(volumeTags));volumes.put(key(region, volumeId), vol);+ if (volumeBlockDeviceManager != null) {+ volumeBlockDeviceManager.createVolume(volumeId, vol.getSize());+ }return vol;}@@ -8371,9 +8526,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {}public void deleteVolume(String region, String volumeId) {- if (volumes.get(key(region, volumeId)).isEmpty()) {- throw new AwsException("InvalidVolume.NotFound",- "The volume '" + volumeId + "' does not exist.", 400);+ Volume volume = volumes.get(key(region, volumeId)).orElseThrow(() ->+ new AwsException("InvalidVolume.NotFound",+ "The volume '" + volumeId + "' does not exist.", 400));+ if ("in-use".equals(volume.getState()) || !volume.getAttachments().isEmpty()) {+ throw new AwsException("VolumeInUse",+ "Volume " + volumeId + " is currently attached to an instance", 400);+ }+ if (volumeBlockDeviceManager != null && volumeBlockDeviceManager.isAvailable()) {+ if (!volumeBlockDeviceManager.deleteVolume(volumeId)) {+ throw new AwsException("InternalError",+ "Failed to delete backing storage for volume " + volumeId, 500);+ }}volumes.delete(key(region, volumeId));}@@ -8511,6 +8675,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {throw new AwsException("MissingParameter","The parameter Device is missing", 400);}+ if (!DEVICE_NAME_PATTERN.matcher(device).matches() || device.contains("..")) {+ throw new AwsException("InvalidParameterValue",+ "Value '" + device + "' for parameter device is invalid.", 400);+ }Volume volume = getRequiredVolume(region, volumeId);Instance inst = getRequiredInstance(region, instanceId);if (!List.of("running", "stopped").contains(inst.getState().getName())) {@@ -8528,6 +8696,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {throw new AwsException("VolumeInUse","Volume '" + volumeId + "' is already attached", 400);}+ // Check if instance already has an attached volume using this device name+ String normalizedReqDev = device.startsWith("/") ? device : "/dev/" + device;+ for (String k : volumes.keys()) {+ Volume v = volumes.get(k).orElse(null);+ if (v == null || !region.equals(v.getRegion()) || v.getAttachments().isEmpty()) {+ continue;+ }+ for (VolumeAttachment existingAtt : v.getAttachments()) {+ if (inst.getInstanceId().equals(existingAtt.getInstanceId())) {+ String existingDev = existingAtt.getDevice() != null && existingAtt.getDevice().startsWith("/")+ ? existingAtt.getDevice() : "/dev/" + existingAtt.getDevice();+ if (normalizedReqDev.equals(existingDev)) {+ throw new AwsException("InvalidParameterValue",+ "The device '" + device + "' is already in use by volume '" + v.getVolumeId() + "'", 400);+ }+ }+ }+ }VolumeAttachment attachment = new VolumeAttachment();attachment.setVolumeId(volumeId);@@ -8540,6 +8726,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {volume.getAttachments().add(attachment);volume.setState("in-use");volumes.put(key(region, volumeId), volume);++ if (volumeBlockDeviceManager != null) {+ volumeBlockDeviceManager.attachVolume(volume, inst, device);+ }+return attachment;}@@ -8577,6 +8768,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {volume.getAttachments().clear();volume.setState("available");volumes.put(key(region, volumeId), volume);++ if (volumeBlockDeviceManager != null) {+ volumeBlockDeviceManager.detachVolume(volume, inst, target.getDevice());+ }+return target;}@@ -8994,6 +9190,38 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {}}+ private void detachAttachedVolumesOnTermination(String region, Instance inst) {+ for (String k : volumes.keys()) {+ Volume vol = volumes.get(k).orElse(null);+ if (vol == null || !region.equals(vol.getRegion()) || vol.getAttachments().isEmpty()) {+ continue;+ }+ boolean modified = false;+ for (VolumeAttachment att : new ArrayList<>(vol.getAttachments())) {+ if (inst.getInstanceId().equals(att.getInstanceId())) {+ if (volumeBlockDeviceManager != null) {+ volumeBlockDeviceManager.detachVolume(vol, inst, att.getDevice());+ }+ if (att.isDeleteOnTermination()) {+ if (volumeBlockDeviceManager != null) {+ volumeBlockDeviceManager.deleteVolume(vol.getVolumeId());+ }+ volumes.delete(k);+ modified = false;+ break;+ } else {+ vol.getAttachments().remove(att);+ modified = true;+ }+ }+ }+ if (modified) {+ vol.setState(vol.getAttachments().isEmpty() ? "available" : "in-use");+ volumes.put(k, vol);+ }+ }+ }+private NetworkInterface requireStandaloneNetworkInterface(String region, String networkInterfaceId) {NetworkInterface ni = networkInterfaces.get(key(region, networkInterfaceId)).orElseThrow(() ->new AwsException("InvalidNetworkInterfaceID.NotFound",diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.javanew file mode 100644index 0000000000..59f7595743--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.java@@ -0,0 +1,426 @@+package io.github.hectorvent.floci.services.ec2;++import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.async.ResultCallback;+import com.github.dockerjava.api.command.ExecCreateCmdResponse;+import com.github.dockerjava.api.command.InspectContainerResponse;+import com.github.dockerjava.api.exception.NotFoundException;+import com.github.dockerjava.api.model.Frame;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.Resettable;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;+import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.services.ec2.model.Volume;+import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.TimeUnit;+import java.util.function.Function;+import java.util.regex.Pattern;++/**+ * Manages backing files and block device attachments for EC2 EBS volumes.+ *+ * <p>EBS volumes are backed by raw files on persistent storage. When attached to a running+ * instance container (which runs privileged), a Linux kernel loop device is bound to the+ * backing file via a lightweight helper container, and the corresponding device node is+ * created inside the target container at the requested path.+ */+@ApplicationScoped+public class Ec2VolumeBlockDeviceManager implements Resettable {++ private static final Logger LOG = Logger.getLogger(Ec2VolumeBlockDeviceManager.class);+ private static final int DEFAULT_TIMEOUT_SECONDS = 30;++ private final DockerClient dockerClient;+ private final ContainerBuilder containerBuilder;+ private final ContainerLifecycleManager lifecycleManager;+ private final EmulatorConfig config;++ private final Map<String, String> activeLoopDevices = new ConcurrentHashMap<>();++ private volatile Boolean dockerAvailableCached;+ private volatile long dockerAvailableCheckTime;++ @Inject+ public Ec2VolumeBlockDeviceManager(DockerClient dockerClient,+ ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager,+ EmulatorConfig config) {+ this.dockerClient = dockerClient;+ this.containerBuilder = containerBuilder;+ this.lifecycleManager = lifecycleManager;+ this.config = config;+ }++ /**+ * Checks if volume block device support is configured and Docker is reachable.+ */+ public boolean isAvailable() {+ if (config == null || config.services() == null || config.services().ec2() == null) {+ return false;+ }+ if (!config.services().ec2().volumeBlockDevices() || config.services().ec2().mock()) {+ return false;+ }+ if (dockerClient == null || lifecycleManager == null) {+ return false;+ }+ long now = System.currentTimeMillis();+ if (dockerAvailableCached != null && (now - dockerAvailableCheckTime) < 5000) {+ return dockerAvailableCached;+ }+ try {+ dockerClient.pingCmd().exec();+ dockerAvailableCached = true;+ } catch (Exception e) {+ dockerAvailableCached = false;+ }+ dockerAvailableCheckTime = now;+ return dockerAvailableCached;+ }++ /**+ * Creates a raw backing file for the given volume.+ */+ public void createVolume(String volumeId, int sizeGib) {+ if (!isAvailable()) {+ return;+ }+ String helperId = ensureHelperContainer();+ if (helperId == null) {+ LOG.warnv("EC2 volume helper container unavailable; backing file for volume {0} will be created on attach",+ volumeId);+ return;+ }+ int effectiveSize = sizeGib > 0 ? sizeGib : 8;+ String rawFile = "/volumes/" + volumeId + ".raw";+ String cmd = "truncate -s " + effectiveSize + "G " + rawFile;+ ContainerExecResult result = execInContainer(helperId, new String[]{"sh", "-c", cmd}, DEFAULT_TIMEOUT_SECONDS);+ if (result.exitCode() != 0) {+ LOG.warnv("Failed to create backing file for volume {0}: {1}", volumeId, result.summary());+ }+ }++ private static final Pattern VALID_DEVICE_PATTERN =+ Pattern.compile("^(/dev/)?[a-zA-Z0-9/_-]+$");++ /**+ * Shell helper function that finds loop devices backing a file across both BusyBox+ * losetup (which outputs `/dev/loopX: 0 /path/file`) and util-linux losetup+ * (which supports {@code losetup -j} and formats {@code losetup -a} as {@code /dev/loopX: [dev]:ino (/path/file)}).+ */+ private static final String SHELL_LOOP_FINDER =+ "find_loops() {\n"+ + " f=\"$1\"\n"+ + " if losetup -j \"$f\" >/dev/null 2>&1; then\n"+ + " losetup -j \"$f\" 2>/dev/null | cut -d: -f1\n"+ + " else\n"+ + " losetup -a 2>/dev/null | grep -E \"[ (]$f[) ]?$\" | cut -d: -f1\n"+ + " fi\n"+ + "}\n";++ private final Object loopAllocationLock = new Object();++ /**+ * Deletes the volume's backing file and releases any associated loop device.+ */+ public boolean deleteVolume(String volumeId) {+ if (!isAvailable()) {+ return false;+ }+ String helperId = ensureHelperContainer();+ if (helperId == null) {+ LOG.warnv("EC2 volume helper container unavailable; backing file for volume {0} could not be deleted",+ volumeId);+ return false;+ }+ String rawFile = "/volumes/" + volumeId + ".raw";+ String script = SHELL_LOOP_FINDER+ + "raw=\"$1\"\n"+ + "while true; do\n"+ + " loop=$(find_loops \"$raw\" | head -n1)\n"+ + " [ -n \"$loop\" ] || break\n"+ + " losetup -d \"$loop\" 2>/dev/null || break\n"+ + "done\n"+ + "rm -f \"$raw\"";+ ContainerExecResult result = execInContainer(helperId,+ new String[]{"sh", "-c", script, "delete", rawFile}, DEFAULT_TIMEOUT_SECONDS);+ activeLoopDevices.remove(volumeId);+ return result.exitCode() == 0;+ }++ /**+ * Attaches a volume to a target instance container as a block device.+ *+ * @return the device path inside the container if block device creation succeeded,+ * or empty if degraded or container was not running.+ */+ public Optional<String> attachVolume(Volume volume, Instance instance, String requestedDevice) {+ if (!isAvailable()) {+ LOG.debugv("Volume block devices disabled or unavailable; skipping device creation for volume {0}",+ volume.getVolumeId());+ return Optional.empty();+ }+ if (instance == null || requestedDevice == null || requestedDevice.isBlank()) {+ return Optional.empty();+ }+ if (!VALID_DEVICE_PATTERN.matcher(requestedDevice).matches() || requestedDevice.contains("..")) {+ LOG.warnv("Rejecting invalid device path {0} for volume {1}", requestedDevice, volume.getVolumeId());+ return Optional.empty();+ }++ String targetContainerId = instance.getDockerContainerId();+ if (targetContainerId == null || targetContainerId.isBlank()) {+ LOG.warnv("Instance {0} has no Docker container ID; volume {1} attached as metadata only",+ instance.getInstanceId(), volume.getVolumeId());+ return Optional.empty();+ }+ if (!lifecycleManager.isContainerRunning(targetContainerId)) {+ LOG.warnv("Container {0} for instance {1} is not running; volume {2} attached as metadata only",+ targetContainerId, instance.getInstanceId(), volume.getVolumeId());+ return Optional.empty();+ }++ String helperId = ensureHelperContainer();+ if (helperId == null) {+ LOG.warnv("EC2 volume helper container unavailable; volume {0} attached as metadata only",+ volume.getVolumeId());+ return Optional.empty();+ }++ int effectiveSize = volume.getSize() > 0 ? volume.getSize() : 8;+ String rawFile = "/volumes/" + volume.getVolumeId() + ".raw";+ String helperScript = SHELL_LOOP_FINDER+ + "file=\"$1\"\n"+ + "size=\"$2\"\n"+ + "[ -f \"$file\" ] || truncate -s \"${size}G\" \"$file\"\n"+ + "loop=$(find_loops \"$file\" | head -n1)\n"+ + "if [ -z \"$loop\" ]; then\n"+ + " loop=$(losetup -f 2>/dev/null)\n"+ + " if [ -n \"$loop\" ]; then\n"+ + " minor=$(echo \"$loop\" | sed 's/[^0-9]*//g')\n"+ + " if [ -n \"$minor\" ] && [ ! -b \"$loop\" ]; then\n"+ + " mknod \"$loop\" b 7 \"$minor\" 2>/dev/null || true\n"+ + " fi\n"+ + " losetup \"$loop\" \"$file\" || exit 1\n"+ + " else\n"+ + " exit 1\n"+ + " fi\n"+ + "fi\n"+ + "echo \"$loop\"";++ ContainerExecResult helperResult;+ synchronized (loopAllocationLock) {+ helperResult = execInContainer(helperId,+ new String[]{"sh", "-c", helperScript, "helper", rawFile, String.valueOf(effectiveSize)},+ DEFAULT_TIMEOUT_SECONDS);+ }+ if (helperResult.exitCode() != 0) {+ LOG.warnv("Failed to allocate loop device for volume {0} in helper: {1}",+ volume.getVolumeId(), helperResult.summary());+ return Optional.empty();+ }++ String loopDev = helperResult.summary();+ if (loopDev == null || !loopDev.startsWith("/dev/loop")) {+ LOG.warnv("Unexpected loop device format for volume {0}: {1}", volume.getVolumeId(), loopDev);+ return Optional.empty();+ }+ activeLoopDevices.put(volume.getVolumeId(), loopDev);++ String minorStr = loopDev.replaceAll("[^0-9]", "");+ String normalizedDevice = requestedDevice.startsWith("/") ? requestedDevice : "/dev/" + requestedDevice;++ String targetScript = "dev=\"$1\"\n"+ + "loop=\"$2\"\n"+ + "minor=\"$3\"\n"+ + "mkdir -p $(dirname \"$dev\")\n"+ + "if [ -e \"$dev\" ] || [ -L \"$dev\" ]; then\n"+ + " rm -f \"$dev\"\n"+ + "fi\n"+ + "if [ -n \"$minor\" ]; then\n"+ + " mknod \"$dev\" b 7 \"$minor\" 2>/dev/null || ln -sf \"$loop\" \"$dev\"\n"+ + "else\n"+ + " ln -sf \"$loop\" \"$dev\"\n"+ + "fi\n"+ + "[ -b \"$dev\" ] || [ -L \"$dev\" ]";++ ContainerExecResult targetResult = execInContainer(targetContainerId,+ new String[]{"sh", "-c", targetScript, "target", normalizedDevice, loopDev, minorStr},+ DEFAULT_TIMEOUT_SECONDS);+ if (targetResult.exitCode() != 0) {+ LOG.warnv("Failed to create block device {0} in container {1} for volume {2}: {3}",+ normalizedDevice, targetContainerId, volume.getVolumeId(), targetResult.summary());+ return Optional.empty();+ }++ LOG.infov("Attached volume {0} as block device {1} (loop device {2}) to instance {3}",+ volume.getVolumeId(), normalizedDevice, loopDev, instance.getInstanceId());+ return Optional.of(normalizedDevice);+ }++ /**+ * Detaches a volume block device from the target container and releases the loop device.+ */+ public void detachVolume(Volume volume, Instance instance, String requestedDevice) {+ if (!isAvailable()) {+ return;+ }+ if (instance != null && requestedDevice != null && !requestedDevice.isBlank()+ && VALID_DEVICE_PATTERN.matcher(requestedDevice).matches() && !requestedDevice.contains("..")) {+ String targetContainerId = instance.getDockerContainerId();+ if (targetContainerId != null && !targetContainerId.isBlank()+ && lifecycleManager.isContainerRunning(targetContainerId)) {+ String normalizedDevice = requestedDevice.startsWith("/") ? requestedDevice : "/dev/" + requestedDevice;+ execInContainer(targetContainerId, new String[]{"rm", "-f", normalizedDevice}, DEFAULT_TIMEOUT_SECONDS);+ }+ }++ String helperId = ensureHelperContainer();+ if (helperId != null) {+ String rawFile = "/volumes/" + volume.getVolumeId() + ".raw";+ String script = SHELL_LOOP_FINDER+ + "raw=\"$1\"\n"+ + "while true; do\n"+ + " loop=$(find_loops \"$raw\" | head -n1)\n"+ + " [ -n \"$loop\" ] || break\n"+ + " losetup -d \"$loop\" 2>/dev/null || break\n"+ + "done";+ execInContainer(helperId,+ new String[]{"sh", "-c", script, "detach", rawFile}, DEFAULT_TIMEOUT_SECONDS);+ }+ activeLoopDevices.remove(volume.getVolumeId());+ }++ /**+ * Restores block device nodes inside an instance container after it is started or restarted.+ */+ public void restoreInstanceVolumeDevices(Instance instance,+ List<VolumeAttachment> attachments,+ Function<String, Optional<Volume>> volumeLookup) {+ if (!isAvailable() || instance == null || attachments == null || attachments.isEmpty()) {+ return;+ }+ for (VolumeAttachment att : attachments) {+ Optional<Volume> volumeOpt = volumeLookup.apply(att.getVolumeId());+ if (volumeOpt.isPresent()) {+ attachVolume(volumeOpt.get(), instance, att.getDevice());+ }+ }+ }++ private synchronized String ensureHelperContainer() {+ String helperName = ContainerStorageHelper.resourceName(config, "ec2", null, "volume-helper");+ try {+ InspectContainerResponse inspect = dockerClient.inspectContainerCmd(helperName).exec();+ if (Boolean.TRUE.equals(inspect.getState().getRunning())) {+ return inspect.getId();+ }+ dockerClient.startContainerCmd(helperName).exec();+ return inspect.getId();+ } catch (NotFoundException e) {+ // Container does not exist yet; proceed to create it+ } catch (Exception e) {+ LOG.warnv("Failed to inspect EC2 volume helper container {0}: {1}", helperName, e.getMessage());+ return null;+ }++ try {+ String helperImage = config.services().ec2().volumeHelperImage();+ ContainerBuilder.Builder builder = containerBuilder.newContainer(helperImage)+ .withName(helperName)+ .withPrivileged(true)+ .withEntrypoint(List.of("sleep", "2147483647"))+ .withLabels(ContainerStorageHelper.defaultLabels(config))+ .withLabels(ContainerStorageHelper.resourceIdentityLabels("ec2", "volume-helper", "default", "global"));++ if (ContainerStorageHelper.isNamedVolumeMode(config)) {+ String volumeName = ContainerStorageHelper.dockerName(config, "ec2-volumes");+ ContainerStorageHelper.applyNamedVolume(builder, lifecycleManager, volumeName, "/volumes");+ } else {+ Path hostPath = ContainerStorageHelper.hostResourcePath(config, "ec2", "volumes");+ Files.createDirectories(hostPath);+ builder.withBind(hostPath.toAbsolutePath().toString(), "/volumes");+ }++ ContainerSpec spec = builder.build();+ return lifecycleManager.createAndStart(spec).containerId();+ } catch (Exception e) {+ LOG.warnv("Failed to create and start EC2 volume helper container {0}: {1}", helperName, e.getMessage());+ return null;+ }+ }++ private ContainerExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds) {+ try {+ ExecCreateCmdResponse exec = dockerClient+ .execCreateCmd(containerId)+ .withCmd(cmd)+ .withAttachStdout(true)+ .withAttachStderr(true)+ .exec();++ StringBuilder output = new StringBuilder();+ boolean completed = dockerClient.execStartCmd(exec.getId())+ .exec(new ResultCallback.Adapter<Frame>() {+ @Override+ public void onNext(Frame frame) {+ if (frame != null && frame.getPayload() != null) {+ output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));+ }+ }+ })+ .awaitCompletion(timeoutSeconds, TimeUnit.SECONDS);++ if (!completed) {+ return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s");+ }+ Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();+ return new ContainerExecResult(exitCode != null ? exitCode : -1, output.toString());+ } catch (Exception e) {+ return new ContainerExecResult(-1, e.getMessage());+ }+ }++ @Override+ public void clear() {+ if (!isAvailable()) {+ activeLoopDevices.clear();+ return;+ }+ String helperId = ensureHelperContainer();+ if (helperId != null) {+ String script = SHELL_LOOP_FINDER+ + "for f in /volumes/*.raw; do\n"+ + " [ -f \"$f\" ] || continue\n"+ + " while true; do\n"+ + " loop=$(find_loops \"$f\" | head -n1)\n"+ + " [ -n \"$loop\" ] || break\n"+ + " losetup -d \"$loop\" 2>/dev/null || break\n"+ + " done\n"+ + " rm -f \"$f\"\n"+ + "done";+ execInContainer(helperId, new String[]{"sh", "-c", script}, DEFAULT_TIMEOUT_SECONDS);+ }+ activeLoopDevices.clear();+ }++ public record ContainerExecResult(long exitCode, String output) {+ public String summary() {+ return output == null || output.isBlank() ? "(no output)" : output.trim();+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.javaindex e0bb1a4860..6c3e1911bd 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java@@ -65,7 +65,9 @@ import java.util.Optional;import java.util.Set;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.TimeUnit;+import java.util.function.Consumer;/*** Manages the Docker lifecycle of k3s containers for real-mode EKS clusters.@@ -133,6 +135,11 @@ public class EksClusterManager implements ClusterNodeInstanceProvider {private final ContainerLogStreamer logStreamer;private final Map<String, ClusterNodeRecord> clusterNodeInstances = new ConcurrentHashMap<>();private final Map<String, Closeable> clusterLogHandles = new ConcurrentHashMap<>();+ private final List<Consumer<Instance>> nodeRegistrationListeners = new CopyOnWriteArrayList<>();++ public void addNodeRegistrationListener(Consumer<Instance> listener) {+ this.nodeRegistrationListeners.add(listener);+ }record ClusterNodeRecord(String accountId, String region, Instance instance) {}@@ -1644,7 +1651,16 @@ public class EksClusterManager implements ClusterNodeInstanceProvider {String region = clusterRegion(cluster);ContainerIps containerIps = resolveContainerIps(containerId);Instance nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);+ nodeInstance.setDockerContainerId(containerId);clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));+ for (Consumer<Instance> listener : nodeRegistrationListeners) {+ try {+ listener.accept(nodeInstance);+ } catch (Exception e) {+ LOG.warnv("Node registration listener failed for cluster {0}: {1}",+ cluster.getName(), e.getMessage());+ }+ }} catch (Exception e) {LOG.warnv("Could not register cluster node instance for EKS cluster {0}: {1}",cluster.getName(), e.getMessage());@@ -1663,7 +1679,10 @@ public class EksClusterManager implements ClusterNodeInstanceProvider {String accountId = resolveClusterAccountId(cluster);String region = clusterRegion(cluster);nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);+ nodeInstance.setDockerContainerId(containerId);clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));+ } else if (nodeInstance.getDockerContainerId() == null) {+ nodeInstance.setDockerContainerId(containerId);}if (metadataServer != null) {diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.javaindex b4651212f1..e5ba8a60b0 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java@@ -148,6 +148,12 @@ public class EksService implements TagHandler, ResourceProvider {backfillOidcIdentities();backfillClusterSecurityGroups();backfillLogging();+ if (clusterManager != null && ec2Service != null) {+ clusterManager.addNodeRegistrationListener(nodeInst -> {+ String reg = nodeInst.getRegion() != null ? nodeInst.getRegion() : regionResolver.getRegion();+ ec2Service.restoreAttachedVolumesForInstance(reg, nodeInst);+ });+ }if (!config.services().eks().mock()) {restorePersistedClusters();startReadinessPoller();diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 502e38a0c0..aadd77b835 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -540,6 +540,8 @@ floci:app-port-range-end: 30999max-published-ports-per-instance: 20socat-image: alpine/socat+ volume-block-devices: true+ volume-helper-image: alpine:3.21mock: false# Bound instance containers to their instance type's CPU and memory limits from the catalog.# FLOCI_SERVICES_EC2_INSTANCE_RESOURCE_LIMITSdiff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.javanew file mode 100644index 0000000000..9810493b0f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.java@@ -0,0 +1,430 @@+package io.github.hectorvent.floci.services.ec2;++import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.async.ResultCallback;+import com.github.dockerjava.api.command.ExecCreateCmdResponse;+import com.github.dockerjava.api.model.Frame;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;+import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.services.ec2.model.InstanceState;+import io.github.hectorvent.floci.services.ec2.model.Placement;+import io.github.hectorvent.floci.services.ec2.model.Volume;+import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+@TestProfile(Ec2VolumeBlockDeviceDockerIntegrationTest.Profile.class)+class Ec2VolumeBlockDeviceDockerIntegrationTest {++ public static class Profile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.services.ec2.mock", "false",+ "floci.services.ec2.volume-block-devices", "true"+ );+ }+ }++ @Inject+ Ec2Service ec2Service;++ @Inject+ Ec2VolumeBlockDeviceManager volumeBlockDeviceManager;++ @Inject+ ContainerLifecycleManager lifecycleManager;++ @Inject+ ContainerBuilder containerBuilder;++ @Inject+ DockerClient dockerClient;++ @Inject+ EmulatorConfig config;++ private static final Logger LOG = Logger.getLogger(Ec2VolumeBlockDeviceDockerIntegrationTest.class);++ private final List<String> containersToClean = new ArrayList<>();+ private final List<String> volumesToClean = new ArrayList<>();++ @BeforeEach+ void checkPrerequisites() {+ Assumptions.assumeTrue(isDockerAvailable(),+ "Docker daemon must be available for EC2 volume block device tests");+ }++ @AfterEach+ void cleanup() {+ for (String volId : volumesToClean) {+ try {+ Volume vol = ec2Service.describeVolumes("us-east-1", List.of(volId), null).getFirst();+ if (vol != null && vol.getAttachments() != null) {+ for (VolumeAttachment att : vol.getAttachments()) {+ try {+ ec2Service.detachVolume("us-east-1", att.getVolumeId(), att.getInstanceId(), att.getDevice(), true);+ } catch (Exception e) {+ LOG.debugv("Ignoring detach volume error during test cleanup: {0}", e.getMessage());+ }+ }+ }+ } catch (Exception e) {+ LOG.debugv("Ignoring describe volume error during test cleanup: {0}", e.getMessage());+ }+ try {+ ec2Service.deleteVolume("us-east-1", volId);+ } catch (Exception e) {+ LOG.debugv("Ignoring delete volume error during test cleanup: {0}", e.getMessage());+ }+ }+ volumesToClean.clear();+ ec2Service.setClusterNodeInstanceProvider(null);++ for (String cid : containersToClean) {+ try {+ dockerClient.stopContainerCmd(cid).withTimeout(2).exec();+ } catch (Exception e) {+ LOG.debugv("Ignoring stop container error during test cleanup: {0}", e.getMessage());+ }+ try {+ dockerClient.removeContainerCmd(cid).withForce(true).exec();+ } catch (Exception e) {+ LOG.debugv("Ignoring remove container error during test cleanup: {0}", e.getMessage());+ }+ }+ containersToClean.clear();+ }++ private boolean isDockerAvailable() {+ if (dockerClient == null) {+ return false;+ }+ try {+ dockerClient.pingCmd().exec();+ return true;+ } catch (Exception e) {+ return false;+ }+ }++ private Instance createRunningTestInstance(String suffix) {+ String containerName = "floci-test-instance-" + suffix;+ ContainerSpec spec = containerBuilder.newContainer("alpine:3.21")+ .withName(containerName)+ .withPrivileged(true)+ .withEntrypoint(List.of("sleep", "3600"))+ .build();++ String containerId = lifecycleManager.createAndStart(spec).containerId();+ containersToClean.add(containerId);+ execIn(containerId, "apk add --no-cache e2fsprogs");++ String instanceId = "i-" + suffix;+ Instance instance = new Instance();+ instance.setInstanceId(instanceId);+ instance.setDockerContainerId(containerId);+ instance.setRegion("us-east-1");+ Placement placement = new Placement();+ placement.setAvailabilityZone("us-east-1a");+ instance.setPlacement(placement);+ instance.setState(InstanceState.running());++ // Register directly into service storage for hermetic test execution+ ec2Service.putInstanceForTest(instance);+ return instance;+ }++ @Test+ void volumeAttachedProducesUsableBlockDeviceOfCorrectSize() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance = createRunningTestInstance(suffix);++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ VolumeAttachment attachment = ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");+ assertNotNull(attachment);+ assertEquals("attached", attachment.getState());+ assertEquals("/dev/xvdf", attachment.getDevice());++ String targetContainerId = instance.getDockerContainerId();++ // 1. Device node exists in container+ ExecResult checkDev = execIn(targetContainerId, "test -b /dev/xvdf || test -L /dev/xvdf");+ assertEquals(0, checkDev.exitCode(), "Device /dev/xvdf should exist as block or symlink: " + checkDev.output());++ // 2. Size matches 1 GiB (1073741824 bytes)+ ExecResult checkSize = execIn(targetContainerId, "blockdev --getsize64 /dev/xvdf");+ assertEquals(0, checkSize.exitCode(), "blockdev query should succeed: " + checkSize.output());+ assertEquals("1073741824", checkSize.output().trim());++ // 3. Format filesystem, mount, write data, unmount+ ExecResult mkfs = execIn(targetContainerId, "mkfs.ext4 -F /dev/xvdf");+ assertEquals(0, mkfs.exitCode(), "mkfs.ext4 should succeed: " + mkfs.output());++ ExecResult mountAndWrite = execIn(targetContainerId,+ "mkdir -p /mnt/vol && mount /dev/xvdf /mnt/vol && echo 'floci-ebs-test-data' > /mnt/vol/test.txt && cat /mnt/vol/test.txt && umount /mnt/vol");+ assertEquals(0, mountAndWrite.exitCode(), "Mount, write, read and umount should succeed: " + mountAndWrite.output());+ assertTrue(mountAndWrite.output().contains("floci-ebs-test-data"));+ }++ @Test+ void detachingRemovesDeviceAndDeletingRemovesBackingFile() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance = createRunningTestInstance(suffix);++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");+ String targetContainerId = instance.getDockerContainerId();++ ExecResult existsBefore = execIn(targetContainerId, "test -e /dev/xvdf");+ assertEquals(0, existsBefore.exitCode());++ // Detach volume+ VolumeAttachment detached = ec2Service.detachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf", false);+ assertEquals("detached", detached.getState());++ // Device node should be removed from container+ ExecResult existsAfter = execIn(targetContainerId, "test ! -e /dev/xvdf");+ assertEquals(0, existsAfter.exitCode(), "Device /dev/xvdf should no longer exist in container");++ // Delete volume+ ec2Service.deleteVolume("us-east-1", volume.getVolumeId());+ volumesToClean.remove(volume.getVolumeId());++ // Verify helper container removed backing file+ String helperName = ContainerStorageHelper.resourceName(config, "ec2", null, "volume-helper");+ ExecResult checkFile = execIn(helperName, "test ! -f /volumes/" + volume.getVolumeId() + ".raw");+ assertEquals(0, checkFile.exitCode(), "Backing file should be removed on volume deletion");+ }++ @Test+ void secondAttachWhileAttachedFailsAndReAttachPreservesData() {+ String suffix1 = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ String suffix2 = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance1 = createRunningTestInstance(suffix1);+ Instance instance2 = createRunningTestInstance(suffix2);++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ // Attach to instance1+ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance1.getInstanceId(), "/dev/xvdf");++ // Attempt second attach to instance2 while in-use: must fail with VolumeInUse+ AwsException ex = assertThrows(AwsException.class, () ->+ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance2.getInstanceId(), "/dev/xvdg"));+ assertEquals("VolumeInUse", ex.getErrorCode());++ // Format and write data on instance1+ ExecResult formatAndWrite = execIn(instance1.getDockerContainerId(),+ "mkfs.ext4 -F /dev/xvdf && mkdir -p /mnt/vol1 && mount /dev/xvdf /mnt/vol1 && echo 'persisted-payload' > /mnt/vol1/hello.txt && umount /mnt/vol1");+ assertEquals(0, formatAndWrite.exitCode(), formatAndWrite.output());++ // Detach from instance1+ ec2Service.detachVolume("us-east-1", volume.getVolumeId(), instance1.getInstanceId(), "/dev/xvdf", false);++ // Re-attach to instance2 at /dev/xvdg+ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance2.getInstanceId(), "/dev/xvdg");++ // Verify device exists on instance2 and data is preserved+ ExecResult verifyData = execIn(instance2.getDockerContainerId(),+ "mkdir -p /mnt/vol2 && mount /dev/xvdg /mnt/vol2 && cat /mnt/vol2/hello.txt && umount /mnt/vol2");+ assertEquals(0, verifyData.exitCode(), "Data should be preserved across detach and re-attach: " + verifyData.output());+ assertTrue(verifyData.output().contains("persisted-payload"));+ }++ @Test+ void restoreInstanceVolumeDevicesRecreatesBlockDevice() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance = createRunningTestInstance(suffix);++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");+ String targetContainerId = instance.getDockerContainerId();++ // Simulate device node loss (e.g. container reboot or tmpfs recreation)+ execIn(targetContainerId, "rm -f /dev/xvdf");+ ExecResult deleted = execIn(targetContainerId, "test ! -e /dev/xvdf");+ assertEquals(0, deleted.exitCode());++ // Call restoreInstanceVolumeDevices+ volumeBlockDeviceManager.restoreInstanceVolumeDevices(instance, volume.getAttachments(),+ volId -> Optional.of(volume));++ // Verify device node is restored+ ExecResult restored = execIn(targetContainerId, "test -b /dev/xvdf || test -L /dev/xvdf");+ assertEquals(0, restored.exitCode(), "Device /dev/xvdf should be restored: " + restored.output());+ }++ @Test+ void attachVolumeToClusterNodeInstanceCreatesBlockDevice() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ String containerName = "floci-test-eks-node-" + suffix;+ ContainerSpec spec = containerBuilder.newContainer("alpine:3.21")+ .withName(containerName)+ .withPrivileged(true)+ .withEntrypoint(List.of("sleep", "3600"))+ .build();++ String containerId = lifecycleManager.createAndStart(spec).containerId();+ containersToClean.add(containerId);++ String instanceId = "i-" + suffix;+ Instance nodeInstance = new Instance();+ nodeInstance.setInstanceId(instanceId);+ nodeInstance.setDockerContainerId(containerId);+ nodeInstance.setRegion("us-east-1");+ Placement placement = new Placement();+ placement.setAvailabilityZone("us-east-1a");+ nodeInstance.setPlacement(placement);+ nodeInstance.setState(InstanceState.running());++ // Register via ClusterNodeInstanceProvider+ ec2Service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {+ @Override+ public Optional<Instance> findInstance(String accountId, String region, String id) {+ if (instanceId.equals(id)) {+ return Optional.of(nodeInstance);+ }+ return Optional.empty();+ }++ @Override+ public List<Instance> listInstances(String accountId, String region) {+ return List.of(nodeInstance);+ }+ });++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ VolumeAttachment attachment = ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instanceId, "/dev/xvdf");+ assertNotNull(attachment);++ ExecResult checkDev = execIn(containerId, "test -b /dev/xvdf || test -L /dev/xvdf");+ assertEquals(0, checkDev.exitCode(), "Block device should exist inside cluster node container: " + checkDev.output());++ ec2Service.setClusterNodeInstanceProvider(null);+ }++ @Test+ void attachVolumeGracefullyDegradesWhenContainerNotRunning() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance = new Instance();+ instance.setInstanceId("i-" + suffix);+ instance.setDockerContainerId("non-existent-container-id");+ instance.setRegion("us-east-1");+ Placement placement = new Placement();+ placement.setAvailabilityZone("us-east-1a");+ instance.setPlacement(placement);+ instance.setState(InstanceState.running());+ ec2Service.putInstanceForTest(instance);++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ // attachVolume succeeds at metadata level even if target container is missing+ VolumeAttachment att = ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");+ assertNotNull(att);+ assertEquals("attached", att.getState());+ }++ @Test+ void attachVolumeRejectsInvalidDeviceName() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance = createRunningTestInstance(suffix);++ Volume volume = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(volume.getVolumeId());++ AwsException ex1 = assertThrows(AwsException.class, () ->+ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf$(touch /tmp/bad)"));+ assertEquals("InvalidParameterValue", ex1.getErrorCode());++ AwsException ex2 = assertThrows(AwsException.class, () ->+ ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/../etc/passwd"));+ assertEquals("InvalidParameterValue", ex2.getErrorCode());+ }++ @Test+ void attachVolumeRejectsDuplicateDeviceName() {+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);+ Instance instance = createRunningTestInstance(suffix);++ Volume vol1 = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(vol1.getVolumeId());+ Volume vol2 = ec2Service.createVolume("us-east-1", "us-east-1a", "gp3", 1, false, 3000, 125, null, null);+ volumesToClean.add(vol2.getVolumeId());++ ec2Service.attachVolume("us-east-1", vol1.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");++ AwsException ex = assertThrows(AwsException.class, () ->+ ec2Service.attachVolume("us-east-1", vol2.getVolumeId(), instance.getInstanceId(), "/dev/xvdf"));+ assertEquals("InvalidParameterValue", ex.getErrorCode());+ assertTrue(ex.getMessage().contains("already in use by volume"));+ }++ private ExecResult execIn(String containerIdOrName, String command) {+ try {+ ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerIdOrName)+ .withCmd("sh", "-c", command)+ .withAttachStdout(true)+ .withAttachStderr(true)+ .exec();++ StringBuilder sb = new StringBuilder();+ boolean done = dockerClient.execStartCmd(exec.getId())+ .exec(new ResultCallback.Adapter<Frame>() {+ @Override+ public void onNext(Frame frame) {+ if (frame != null && frame.getPayload() != null) {+ sb.append(new String(frame.getPayload(), StandardCharsets.UTF_8));+ }+ }+ })+ .awaitCompletion(30, TimeUnit.SECONDS);++ if (!done) {+ return new ExecResult(-1, "Timed out: " + sb);+ }+ Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();+ return new ExecResult(exitCode != null ? exitCode : -1, sb.toString());+ } catch (Exception e) {+ return new ExecResult(-1, e.getMessage());+ }+ }++ private record ExecResult(long exitCode, String output) {}+}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.javaindex 9931cc3740..dbd1713ba0 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java@@ -599,6 +599,42 @@ class EksClusterManagerTest {assertEquals("floci-aws-eks-999999999999.demo", cluster.getDockerName());verify(lifecycleManager).removeIfExists("floci-aws-eks-999999999999.demo");}++ @Test+ void startClusterRegistersNodeInstanceAndNotifiesListener() {+ stubFreshStart("cid-new", 6440);+ List<Instance> registered = new ArrayList<>();+ manager.addNodeRegistrationListener(registered::add);++ Cluster cluster = cluster();+ manager.startCluster(cluster);++ Instance inst = manager.getRegisteredClusterNodeInstance(cluster);+ assertNotNull(inst);+ assertEquals("cid-new", inst.getDockerContainerId());+ assertEquals(1, registered.size());+ assertEquals(inst.getInstanceId(), registered.getFirst().getInstanceId());+ }++ @Test+ void restoreClusterRegistersNodeInstanceAndNotifiesListener() {+ when(lifecycleManager.findByName("floci-eks-demo"))+ .thenReturn(Optional.of(survivingContainer("cid-1")));+ when(lifecycleManager.adopt("cid-1", List.of(6443)))+ .thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6512)));++ List<Instance> registered = new ArrayList<>();+ manager.addNodeRegistrationListener(registered::add);++ Cluster cluster = cluster();+ manager.restoreCluster(cluster);++ Instance inst = manager.getRegisteredClusterNodeInstance(cluster);+ assertNotNull(inst);+ assertEquals("cid-1", inst.getDockerContainerId());+ assertEquals(1, registered.size());+ assertEquals(inst.getInstanceId(), registered.getFirst().getInstanceId());+ }}/** Mirror-injection guard behavior, without a Docker daemon. */diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex deafb99b22..9cf1630bf7 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -298,6 +298,8 @@ floci:app-port-range-end: 30999max-published-ports-per-instance: 20socat-image: alpine/socat+ volume-block-devices: false+ volume-helper-image: alpine:3.21mock: trueinstance-resource-limits: trueaws-faithful-private-ip: false