mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 15:21:05 -05:00
fix(ec2): attach launch-created EBS volumes as block devices when the instance runs (#9438)
Restore the data volumes a launch creates from its block device mappings as guest block devices through the StartInstances restore hook, run before the instance is marked running so they exist before UserData. DetachVolume takes the per-volume lock attach and delete already take, and the restore re-reads each volume under it, so a detach during a restore removes the device afterwards.
This commit is contained in:
1 parent
bde90de4d4
commit
f046df07aa
8 files changed
+194
-62
No files matched your search
@@ -1379,7 +1379,7 @@ An encrypted volume reports the KMS key it was created with as `kmsKeyId` in `Cr
|
||||
|
||||
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`. It starts on the first volume operation and is removed when Floci shuts down; the backing files stay in storage.
|
||||
- **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.
|
||||
- **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. The data volumes a launch creates from its block device mappings have their device nodes by the time the instance is running, before its UserData runs.
|
||||
- **Restart reconciliation**: When an instance container stops and starts, or when Floci restarts, attached volume device nodes are automatically restored inside the target container. Backing raw files remain preserved across reboots in persistent storage.
|
||||
- **Metadata-only tracking**: Disabling `floci.services.ec2.volume-block-devices`, EC2 mock mode, unavailable Docker, or a missing or stopped target container retains metadata-only attachment without failing the API call. Stopped instances have their device nodes restored when started. Once physical attachment is attempted, helper, loop-device, or guest device-creation failures return `InternalError` without recording a successful attachment; partial guest devices and loop devices allocated by the failed attempt are cleaned up on a best-effort basis so attachment can be retried. Reused loop devices are retained on failure. Insufficient privileges can cause these failures. Restart reconciliation logs device-restoration failures and keeps the existing attachment records for a later retry.
|
||||
- **Platform requirements**: Requires a Linux Docker environment (native Linux Docker daemon, or Colima / Docker Desktop with a Linux virtual machine) and privileged instance containers.
|
||||
|
||||
@@ -484,6 +484,12 @@ public class Ec2ContainerManager {
|
||||
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region,
|
||||
Ec2PortForwardManager.DesiredPorts appPorts, List<SecurityGroup> groups,
|
||||
Map<String, List<String>> prefixLists) {
|
||||
launch(instance, image, publicKey, region, appPorts, groups, prefixLists, null);
|
||||
}
|
||||
|
||||
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region,
|
||||
Ec2PortForwardManager.DesiredPorts appPorts, List<SecurityGroup> groups,
|
||||
Map<String, List<String>> prefixLists, Runnable beforeRunning) {
|
||||
instance.setState(InstanceState.pending());
|
||||
|
||||
// An instance record is metadata: id, addresses, tags and lifecycle state are all
|
||||
@@ -599,6 +605,16 @@ public class Ec2ContainerManager {
|
||||
exposeReachablePublicAddress(instance);
|
||||
}
|
||||
|
||||
// The launch's volumes are attached by the time a poller sees running, and before UserData.
|
||||
if (beforeRunning != null) {
|
||||
try {
|
||||
beforeRunning.run();
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error in before-running hook for instance {0}: {1}",
|
||||
instanceId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Published before the state flips, so a poller that sees running never sees it without the address.
|
||||
if (!markRunning(instance)) {
|
||||
failLaunch(instance, leasedPrivateIp);
|
||||
|
||||
@@ -1430,30 +1430,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
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()) {
|
||||
for (AccountAwareStorageBackend.AccountEntry<Volume> entry : entriesOfEveryAccount(volumes)) {
|
||||
Volume vol = entry.value();
|
||||
if (vol == null || !region.equals(vol.getRegion()) || vol.getVolumeId().equals(inst.getRootVolumeId())) {
|
||||
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()))) {
|
||||
restoreVolumeDevice(vol, inst, att.getDevice());
|
||||
}
|
||||
}
|
||||
// Under the lock a detach or delete takes, and from the stored volume: one that ended
|
||||
// the attachment after the scan must not have its device created again.
|
||||
withVolumeLock(vol.getVolumeId(), () -> AccountAwareStorageBackend
|
||||
.readInAccount(volumes, entry.accountId(), entry.key())
|
||||
.ifPresent(current -> {
|
||||
for (VolumeAttachment att : List.copyOf(current.getAttachments())) {
|
||||
if (inst.getInstanceId().equals(att.getInstanceId())
|
||||
&& (inst.getRootDeviceName() == null
|
||||
|| !att.getDevice().equals(inst.getRootDeviceName()))) {
|
||||
restoreVolumeDevice(current, inst, att.getDevice());
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4816,7 +4810,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
.orElseThrow(() -> new IllegalStateException("Missing security group " + group.getGroupId())))
|
||||
.toList();
|
||||
containerManager.launch(inst, dockerImage, publicKey, region, desiredPublishedPorts(region, inst),
|
||||
policyGroups, policyPrefixLists(region, policyGroups));
|
||||
policyGroups, policyPrefixLists(region, policyGroups),
|
||||
() -> restoreAttachedVolumesForInstance(region, inst));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16652,45 +16647,47 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (volumeId == null || volumeId.isEmpty()) {
|
||||
throw new AwsException("MissingParameter", "The parameter VolumeId is missing", 400);
|
||||
}
|
||||
ensureDefaultResources(region);
|
||||
Volume volume = getRequiredVolume(region, volumeId);
|
||||
return withVolumeLock(volumeId, () -> {
|
||||
ensureDefaultResources(region);
|
||||
Volume volume = getRequiredVolume(region, volumeId);
|
||||
|
||||
if ("available".equals(volume.getState()) || volume.getAttachments().isEmpty()) {
|
||||
throw new AwsException("InvalidVolume.NotAttached",
|
||||
"Volume '" + volumeId + "' is not attached", 400);
|
||||
}
|
||||
VolumeAttachment target = volume.getAttachments().getFirst();
|
||||
if (instanceId != null && !target.getInstanceId().equals(instanceId)) {
|
||||
throw new AwsException("InvalidAttachment.NotFound",
|
||||
"Volume '" + volumeId + "' is not attached to instance '" + instanceId + "'", 400);
|
||||
}
|
||||
if (device != null && !target.getDevice().equals(device)) {
|
||||
throw new AwsException("InvalidAttachment.NotFound",
|
||||
"Volume '" + volumeId + "' is not attached with device '" + device + "'", 400);
|
||||
}
|
||||
Instance inst = getRequiredInstance(region, target.getInstanceId());
|
||||
if (!inst.getState().getName().equals("stopped") && target.getDevice().equals(inst.getRootDeviceName())) {
|
||||
throw new AwsException("OperationNotPermitted",
|
||||
"The root volume of an instance cannot be detached while the instance is running", 400);
|
||||
}
|
||||
if (!force && target.getDevice().equals(inst.getRootDeviceName())) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"Device " + inst.getRootDeviceName() + " has the root partition on it. Detaching it will damage the " +
|
||||
"filesystem/partition tables. To force detachment, use the force parameter", 400);
|
||||
}
|
||||
if (dryRun) {
|
||||
throw dryRunOperation();
|
||||
}
|
||||
target.setState("detached");
|
||||
volume.getAttachments().clear();
|
||||
volume.setState("available");
|
||||
volumes.put(key(region, volumeId), volume);
|
||||
if ("available".equals(volume.getState()) || volume.getAttachments().isEmpty()) {
|
||||
throw new AwsException("InvalidVolume.NotAttached",
|
||||
"Volume '" + volumeId + "' is not attached", 400);
|
||||
}
|
||||
VolumeAttachment target = volume.getAttachments().getFirst();
|
||||
if (instanceId != null && !target.getInstanceId().equals(instanceId)) {
|
||||
throw new AwsException("InvalidAttachment.NotFound",
|
||||
"Volume '" + volumeId + "' is not attached to instance '" + instanceId + "'", 400);
|
||||
}
|
||||
if (device != null && !target.getDevice().equals(device)) {
|
||||
throw new AwsException("InvalidAttachment.NotFound",
|
||||
"Volume '" + volumeId + "' is not attached with device '" + device + "'", 400);
|
||||
}
|
||||
Instance inst = getRequiredInstance(region, target.getInstanceId());
|
||||
if (!inst.getState().getName().equals("stopped") && target.getDevice().equals(inst.getRootDeviceName())) {
|
||||
throw new AwsException("OperationNotPermitted",
|
||||
"The root volume of an instance cannot be detached while the instance is running", 400);
|
||||
}
|
||||
if (!force && target.getDevice().equals(inst.getRootDeviceName())) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"Device " + inst.getRootDeviceName() + " has the root partition on it. Detaching it will damage the " +
|
||||
"filesystem/partition tables. To force detachment, use the force parameter", 400);
|
||||
}
|
||||
if (dryRun) {
|
||||
throw dryRunOperation();
|
||||
}
|
||||
target.setState("detached");
|
||||
volume.getAttachments().clear();
|
||||
volume.setState("available");
|
||||
volumes.put(key(region, volumeId), volume);
|
||||
|
||||
if (volumeBlockDeviceManager != null) {
|
||||
volumeBlockDeviceManager.detachVolume(volume, inst, target.getDevice());
|
||||
}
|
||||
if (volumeBlockDeviceManager != null) {
|
||||
volumeBlockDeviceManager.detachVolume(volume, inst, target.getDevice());
|
||||
}
|
||||
|
||||
return target;
|
||||
return target;
|
||||
});
|
||||
}
|
||||
|
||||
private Volume getRequiredVolume(String region, String volumeId) {
|
||||
|
||||
@@ -122,7 +122,7 @@ class Ec2CapturedImageReclaimIntegrationTest {
|
||||
/** The image reference the container manager was asked to launch for the given instance. */
|
||||
private ResolvedAmiImage launchedImageOf(Instance instance) {
|
||||
ArgumentCaptor<ResolvedAmiImage> resolved = ArgumentCaptor.forClass(ResolvedAmiImage.class);
|
||||
verify(containerManager).launch(eq(instance), resolved.capture(), any(), anyString(), any(), any(), any());
|
||||
verify(containerManager).launch(eq(instance), resolved.capture(), any(), anyString(), any(), any(), any(), any());
|
||||
return resolved.getValue();
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,7 @@ import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockingDetails;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -1676,6 +1677,31 @@ class Ec2ContainerManagerTest {
|
||||
verify(harness.dockerClient, never()).execStartCmd("userdata-exec");
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchRunsItsStartedHookBeforeTheInstanceIsRunningAndBeforeUserData() throws Exception {
|
||||
LaunchHarness harness = launchHarness();
|
||||
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
|
||||
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
|
||||
InspectContainerResponse response = inspectResponse("192.168.215.42");
|
||||
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
|
||||
when(inspect.exec()).thenReturn(response);
|
||||
Instance instance = instance("i-startedhook");
|
||||
instance.setUserData("""
|
||||
#!/bin/bash
|
||||
test -b /dev/sdf
|
||||
""");
|
||||
List<String> events = new CopyOnWriteArrayList<>();
|
||||
|
||||
harness.manager.launch(instance, ResolvedAmiImage.minimal("ubuntu:24.04"), null, "us-west-2",
|
||||
Ec2PortForwardManager.DesiredPorts.NONE, List.of(), Map.of(), () -> events.add(
|
||||
"hook while " + instance.getState().getName() + ", user data started: "
|
||||
+ mockingDetails(harness.streamingDockerClient).getInvocations().stream()
|
||||
.anyMatch(call -> call.getMethod().getName().equals("execStartCmd"))));
|
||||
|
||||
verify(harness.streamingDockerClient, timeout(2000)).execStartCmd("userdata-exec");
|
||||
assertEquals(List.of("hook while pending, user data started: false"), events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchLabelsContainerWithResourceIdentity() throws Exception {
|
||||
LaunchHarness harness = launchHarness();
|
||||
|
||||
@@ -70,7 +70,7 @@ class Ec2CreateKeyPairLaunchIntegrationTest {
|
||||
List.of(), null, null, List.of(), null, null).getInstances().getFirst();
|
||||
|
||||
ArgumentCaptor<String> injected = ArgumentCaptor.forClass(String.class);
|
||||
verify(containerManager).launch(eq(instance), any(), injected.capture(), anyString(), any(), any(), any());
|
||||
verify(containerManager).launch(eq(instance), any(), injected.capture(), anyString(), any(), any(), any(), any());
|
||||
assertEquals("ssh-ed25519 " + Base64.getEncoder().encodeToString(blob), injected.getValue());
|
||||
} finally {
|
||||
// The application is shared with another class: the key pair goes, and the instance gives
|
||||
|
||||
@@ -110,6 +110,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -660,6 +661,30 @@ class Ec2ServiceTest {
|
||||
verify(devices).deleteVolume(dataId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchAttachesTheVolumesItCreatesOnceTheInstanceRuns() {
|
||||
Ec2VolumeBlockDeviceManager devices = mock(Ec2VolumeBlockDeviceManager.class);
|
||||
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
|
||||
doAnswer(invocation -> {
|
||||
invocation.<Runnable>getArgument(7).run();
|
||||
return null;
|
||||
}).when(containerManager).launch(any(Instance.class), any(ResolvedAmiImage.class), any(), anyString(),
|
||||
any(), anyList(), anyMap(), any(Runnable.class));
|
||||
AmiImageResolver resolver = mock(AmiImageResolver.class);
|
||||
when(resolver.resolveImage("ami-test")).thenReturn(ResolvedAmiImage.minimal("guest:latest"));
|
||||
Ec2Service service = new Ec2Service(mockConfig(false), containerManager,
|
||||
mock(Ec2PortForwardManager.class), resolver, mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), null, null, devices);
|
||||
|
||||
Reservation launch = launchKeepingADataVolume(service);
|
||||
|
||||
Instance instance = launch.getInstances().getFirst();
|
||||
String dataId = launch.getLaunchVolumeIds().stream()
|
||||
.filter(id -> !id.equals(instance.getRootVolumeId())).findFirst().orElseThrow();
|
||||
verify(devices).attachVolume(argThat(volume -> dataId.equals(volume.getVolumeId())), eq(instance),
|
||||
eq("/dev/sdf"));
|
||||
}
|
||||
|
||||
private static Reservation launchKeepingADataVolume(Ec2Service service) {
|
||||
LaunchTemplateData.Ebs ebs = new LaunchTemplateData.Ebs();
|
||||
ebs.setVolumeSize(5);
|
||||
@@ -7522,6 +7547,52 @@ class Ec2ServiceTest {
|
||||
assertEquals(1, stored.getAttachments().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void detachDuringARestoreRemovesTheDeviceAfterTheRestoreCreatesIt() throws Exception {
|
||||
VolumeAttachmentFixture fixture = volumeAttachmentFixture();
|
||||
Ec2VolumeBlockDeviceManager blockDevices = fixture.blockDevices();
|
||||
Ec2Service service = fixture.service();
|
||||
Instance instance = fixture.instance();
|
||||
Volume volume = fixture.volume();
|
||||
doReturn(Optional.of("/dev/xvdf")).when(blockDevices).attachVolume(any(), any(), anyString());
|
||||
service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");
|
||||
List<String> events = new CopyOnWriteArrayList<>();
|
||||
CountDownLatch restoring = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
when(blockDevices.attachVolume(any(), any(), anyString())).thenAnswer(invocation -> {
|
||||
events.add("restore starts");
|
||||
restoring.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
events.add("restore ends");
|
||||
return Optional.of("/dev/xvdf");
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
events.add("detach");
|
||||
return null;
|
||||
}).when(blockDevices).detachVolume(any(), any(), anyString());
|
||||
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
Future<?> restore = executor.submit(() -> service.restoreAttachedVolumesForInstance("us-east-1", instance));
|
||||
try {
|
||||
assertTrue(restoring.await(10, TimeUnit.SECONDS));
|
||||
AtomicReference<Thread> detacher = new AtomicReference<>();
|
||||
Future<?> detach = executor.submit(() -> {
|
||||
detacher.set(Thread.currentThread());
|
||||
service.detachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(),
|
||||
"/dev/xvdf", false);
|
||||
});
|
||||
awaitBlockedOrDone(detacher, detach);
|
||||
assertFalse(detach.isDone(), "detach must wait for the restore");
|
||||
release.countDown();
|
||||
restore.get(10, TimeUnit.SECONDS);
|
||||
detach.get(10, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(List.of("restore starts", "restore ends", "detach"), events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentAttachmentWaitsForThePhysicalOperation() throws Exception {
|
||||
VolumeAttachmentFixture fixture = volumeAttachmentFixture();
|
||||
|
||||
+22
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.LaunchTemplateData;
|
||||
import io.floci.aws.services.ec2.model.Placement;
|
||||
import io.floci.aws.services.ec2.model.Volume;
|
||||
import io.floci.aws.services.ec2.model.VolumeAttachment;
|
||||
@@ -383,6 +384,27 @@ class Ec2VolumeBlockDeviceDockerNightlyIntegrationTest {
|
||||
assertEquals(0, checkDev.exitCode(), "Block device should exist inside cluster node container: " + checkDev.summary());
|
||||
}
|
||||
|
||||
@Test
|
||||
void volumeALaunchCreatesIsABlockDeviceByTheTimeTheInstanceRuns() {
|
||||
LaunchTemplateData.Ebs ebs = new LaunchTemplateData.Ebs();
|
||||
ebs.setVolumeSize(1);
|
||||
ebs.setDeleteOnTermination(true);
|
||||
LaunchTemplateData.BlockDeviceMapping data = new LaunchTemplateData.BlockDeviceMapping();
|
||||
data.setDeviceName("/dev/sdf");
|
||||
data.setEbs(ebs);
|
||||
Instance instance = ec2Service.runInstances("us-east-1", "ami-alpine", "t3.micro", 1, 1, null, List.of(),
|
||||
null, null, List.of(), null, null, null, null, 0, null, null, null, null, false, null, null,
|
||||
List.of(data), false, null, null).getInstances().getFirst();
|
||||
try {
|
||||
ec2Service.awaitContainerLaunch(instance);
|
||||
|
||||
ContainerExec.Result checkDev = execIn(instance.getDockerContainerId(), "test -b /dev/sdf || test -L /dev/sdf");
|
||||
assertEquals(0, checkDev.exitCode(), "Block device should exist once the instance runs: " + checkDev.summary());
|
||||
} finally {
|
||||
ec2Service.terminateInstances("us-east-1", List.of(instance.getInstanceId()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachVolumeGracefullyDegradesWhenContainerNotRunning() {
|
||||
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
|
||||
|
||||
Reference in new issue
Block a user