feat(ec2): attach volumes as real block devices (#4354)

* feat(ec2): attach volumes as real block devices

* fix(ec2): address review feedback on volume block device attachments

* fix(ec2,eks): handle volume deletion failures and node volume re-attachment on restore

* test(eks): verify cluster node instance registration and listener callback

* fix(ec2,eks): address review comments on loop device detachment and config

* fix(ec2): support both util-linux and busybox losetup in volume loop lookup
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-24 21:10:55 -04:00
1 parent 4abba5a218
commit 922402210f
11 files changed
+1193 -9

No files matched your search

@@ -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();
@@ -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());
}
}
});
}
@@ -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",
@@ -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();
}
}
}
@@ -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) {
@@ -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();