fix(ec2): report block-device attachment failures (#7690)

This commit is contained in:
Robert Stupp authored and GitHub committed 2026-11-07 02:05:34 -04:00
1 parent 62de6a717b
commit a99119e3b9
6 files changed
+574 -36

No files matched your search

@@ -1111,7 +1111,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
if (inst.getDockerContainerId() != null
&& containerManager.isContainerRunning(inst.getDockerContainerId())) {
volumeBlockDeviceManager.attachVolume(vol, inst, att.getDevice());
restoreVolumeDevice(vol, inst, att.getDevice());
}
}
}
@@ -1142,12 +1142,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
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());
restoreVolumeDevice(vol, inst, att.getDevice());
}
}
}
}
private void restoreVolumeDevice(Volume volume, Instance instance, String device) {
try {
volumeBlockDeviceManager.attachVolume(volume, instance, device);
} catch (AwsException e) {
LOG.warnv("Could not restore volume {0} on instance {1}: {2}",
volume.getVolumeId(), instance.getInstanceId(), e.getMessage());
}
}
/**
* 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.
@@ -14567,6 +14576,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
private final ConcurrentHashMap<String, RefCountedLock> volumeLocks = new ConcurrentHashMap<>();
private final Set<VolumeDevice> pendingVolumeAttachments = ConcurrentHashMap.newKeySet();
private record VolumeDevice(String accountId, String region, String instanceId, String device) {}
private <T> T withVolumeLock(String volumeId, Supplier<T> action) {
if (volumeId == null) {
@@ -14845,6 +14857,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
throw new AwsException("InvalidParameterValue",
"Value '" + device + "' for parameter device is invalid.", 400);
}
return withVolumeLock(volumeId, () -> {
String normalizedDevice = device.startsWith("/") ? device : "/dev/" + device;
VolumeDevice target = new VolumeDevice(callerAccountId(), region, instanceId, normalizedDevice);
if (!pendingVolumeAttachments.add(target)) {
throw new AwsException("InvalidParameterValue",
"The device '" + device + "' is already in use by an attachment in progress", 400);
}
try {
return attachVolumeToInstance(region, volumeId, instanceId, device);
} finally {
pendingVolumeAttachments.remove(target);
}
});
}
private VolumeAttachment attachVolumeToInstance(String region, String volumeId, String instanceId, String device) {
Volume volume = getRequiredVolume(region, volumeId);
Instance inst = getRequiredInstance(region, instanceId);
if (!List.of("running", "stopped").contains(inst.getState().getName())) {
@@ -14881,6 +14909,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
if (volumeBlockDeviceManager != null) {
volumeBlockDeviceManager.attachVolume(volume, inst, device);
}
VolumeAttachment attachment = new VolumeAttachment();
attachment.setVolumeId(volumeId);
attachment.setInstanceId(instanceId);
@@ -14893,10 +14925,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
volume.setState("in-use");
volumes.put(key(region, volumeId), volume);
if (volumeBlockDeviceManager != null) {
volumeBlockDeviceManager.attachVolume(volume, inst, device);
}
return attachment;
}
@@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.docker.ContainerBuilder;
@@ -265,7 +266,8 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
* 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.
* or empty for intentional metadata-only tracking.
* @throws AwsException if physical attachment is attempted but fails
*/
public Optional<String> attachVolume(Volume volume, Instance instance, String requestedDevice) {
if (!isAvailable()) {
@@ -281,6 +283,9 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
return Optional.empty();
}
if (instance.getState() != null && "stopped".equals(instance.getState().getName())) {
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",
@@ -295,9 +300,7 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
String helperId = ensureHelperContainer();
if (helperId == null) {
LOG.warnv("EC2 volume helper container unavailable; volume {0} attached as metadata only",
volume.getVolumeId());
return Optional.empty();
throw attachmentFailure(volume, instance, null, null, null, "Volume helper container unavailable");
}
int effectiveSize = volume.getSize() > 0 ? volume.getSize() : 8;
@@ -306,6 +309,7 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
+ "file=\"$1\"\n"
+ "size=\"$2\"\n"
+ "[ -f \"$file\" ] || truncate -s \"${size}G\" \"$file\"\n"
+ "allocated=0\n"
+ "loop=$(find_loops \"$file\" | head -n1)\n"
+ "if [ -z \"$loop\" ]; then\n"
+ " loop=$(losetup -f 2>/dev/null)\n"
@@ -315,11 +319,12 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
+ " mknod \"$loop\" b 7 \"$minor\" 2>/dev/null || true\n"
+ " fi\n"
+ " losetup \"$loop\" \"$file\" || exit 1\n"
+ " allocated=1\n"
+ " else\n"
+ " exit 1\n"
+ " fi\n"
+ "fi\n"
+ "echo \"$loop\"";
+ "echo \"$allocated $loop\"";
ContainerExec.Result helperResult;
synchronized (loopAllocationLock) {
@@ -328,16 +333,17 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
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();
throw attachmentFailure(volume, instance, null, null, null, helperResult.summary());
}
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();
String[] allocation = helperResult.summary().split("\\s+");
if (allocation.length != 2 || !("0".equals(allocation[0]) || "1".equals(allocation[0]))
|| !allocation[1].matches("/dev/loop[0-9]+")) {
throw attachmentFailure(volume, instance, null, null, null,
"Unexpected loop allocation: " + helperResult.summary());
}
String loopDev = allocation[1];
String allocatedLoop = "1".equals(allocation[0]) ? loopDev : null;
activeLoopDevices.put(volume.getVolumeId(), loopDev);
String minorStr = loopDev.replaceAll("[^0-9]", "");
@@ -355,15 +361,13 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
+ "else\n"
+ " ln -sf \"$loop\" \"$dev\"\n"
+ "fi\n"
+ "[ -b \"$dev\" ] || [ -L \"$dev\" ]";
+ "[ -b \"$dev\" ]";
ContainerExec.Result 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();
throw attachmentFailure(volume, instance, helperId, allocatedLoop, normalizedDevice, targetResult.summary());
}
LOG.infov("Attached volume {0} as block device {1} (loop device {2}) to instance {3}",
@@ -390,18 +394,52 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
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);
releaseVolumeLoops(helperId, volume);
}
}
private AwsException attachmentFailure(Volume volume, Instance instance, String helperId,
String allocatedLoop, String targetDevice, String reason) {
LOG.warnv("Failed to attach volume {0} to instance {1}: {2}",
volume.getVolumeId(), instance.getInstanceId(), reason);
if (targetDevice != null) {
ContainerExec.Result removed = execInContainer(instance.getDockerContainerId(),
new String[]{"rm", "-f", targetDevice}, DEFAULT_TIMEOUT_SECONDS);
if (removed.exitCode() != 0) {
LOG.warnv("Could not clean up device {0} for volume {1}: {2}",
targetDevice, volume.getVolumeId(), removed.summary());
}
}
if (helperId != null && allocatedLoop != null) {
ContainerExec.Result released = execInContainer(helperId,
new String[]{"losetup", "-d", allocatedLoop}, DEFAULT_TIMEOUT_SECONDS);
if (released.exitCode() != 0) {
LOG.warnv("Could not release newly allocated loop {0} for volume {1}: {2}",
allocatedLoop, volume.getVolumeId(), released.summary());
} else {
activeLoopDevices.remove(volume.getVolumeId(), allocatedLoop);
}
}
return new AwsException("InternalError", "Could not attach volume '" + volume.getVolumeId()
+ "' to instance '" + instance.getInstanceId() + "'", 500);
}
private void releaseVolumeLoops(String helperId, Volume volume) {
String script = SHELL_LOOP_FINDER
+ "raw=\"$1\"\n"
+ "failed=0\n"
+ "for loop in $(find_loops \"$raw\"); do\n"
+ " losetup -d \"$loop\" || failed=1\n"
+ "done\n"
+ "exit $failed";
ContainerExec.Result released = execInContainer(helperId,
new String[]{"sh", "-c", script, "detach", "/volumes/" + volume.getVolumeId() + ".raw"},
DEFAULT_TIMEOUT_SECONDS);
if (released.exitCode() != 0) {
LOG.warnv("Could not release loop devices for volume {0}: {1}", volume.getVolumeId(), released.summary());
} else {
activeLoopDevices.remove(volume.getVolumeId());
}
activeLoopDevices.remove(volume.getVolumeId());
}
/**
@@ -416,7 +454,12 @@ public class Ec2VolumeBlockDeviceManager implements ContainerTeardown, Resettabl
for (VolumeAttachment att : attachments) {
Optional<Volume> volumeOpt = volumeLookup.apply(att.getVolumeId());
if (volumeOpt.isPresent()) {
attachVolume(volumeOpt.get(), instance, att.getDevice());
try {
attachVolume(volumeOpt.get(), instance, att.getDevice());
} catch (AwsException e) {
LOG.warnv("Could not restore volume {0} on instance {1}: {2}",
att.getVolumeId(), instance.getInstanceId(), e.getMessage());
}
}
}
}