feat(ec2): capture the instance file system in CreateImage, and implement Deregister/CopyImage (#3306)

* fix(ec2): capture the instance file system in CreateImage

CreateImage recorded only metadata. It registered a new id and set

    image.setSourceImageId(resolveLaunchableImageId(region, source.getImageId()));

so the AMI pointed at the *base* image the source instance was launched
from. Launching it started that base image, and everything provisioned on
the source instance was silently discarded.

This was worse than an unimplemented operation. A full Packer amazon-ebs
build ran green against Floci -- keypair, security group, launch, SSH,
provisioner, stop, CreateImage, cleanup -- and produced an AMI reporting
state "available" that contained nothing:

    ==> amazon-ebs.floci: PROVISIONED_BY_PACKER
    ==> amazon-ebs.floci: AMI: ami-42ba1c3d9f8023703
    Build finished after 1 minute 41 seconds.

    $ # launch that AMI, then:
    $ cat /etc/floci-probe
    cat: /etc/floci-probe: No such file or directory

Anyone building a golden AMI locally would have believed it worked.

Per API_CreateImage, CreateImage "creates an Amazon EBS-backed AMI from an
Amazon EBS-backed instance that is either running or stopped", and the
resulting AMI is a point-in-time capture of the instance's volumes. The
contract is that state at capture time is preserved.

CreateImage now commits the source container to a Docker image
(floci-ami/<ami-id>:latest) and stores that reference on the Image.
RunInstances prefers it, walking the CreateImage chain so an AMI captured
from an instance that was itself launched from a capture still resolves.
The guest runtime (systemd vs minimal, cloud-init) still comes from the
ancestor, since committing a layer does not change how the guest boots.

Capture is best-effort by design: if the daemon refuses the commit, the
AMI keeps its sourceImageId and behaves exactly as before rather than
failing the API call. Skipped entirely in mock mode, where there is no
container.

Ec2ContainerManager gains commitInstance() and removeCommittedImage(); the
latter exists so captures can be reclaimed when the owning AMI is
deregistered, rather than accumulating on disk.

Verified end to end against a real Packer 1.16.0 build on this branch: the
build succeeds, and launching the resulting AMI and reading the file the
provisioner wrote returns PROVISIONED_BY_PACKER. The committed image is
visible as floci-ami/ami-295129250f0c23320:latest.

Tests cover the capture itself with a mocked Docker client: that the
reference is split into repository and tag (passing it whole would create
a repository literally named "floci-ami/ami-123:latest"), that a missing
container captures nothing, that a daemon failure yields null rather than
propagating, and that removing an absent or never-captured image is not an
error. 8 tests, all green.

Not addressed here: reclaiming the committed image on DeregisterImage,
which needs the DeregisterImage work to land first.

* feat(ec2): implement DeregisterImage and CopyImage

Both actions returned UnsupportedOperation:

    $ aws ec2 deregister-image --image-id ami-... --endpoint-url http://localhost:4577
    An error occurred (UnsupportedOperation) ... Operation DeregisterImage is not supported.
    $ aws ec2 copy-image --source-region us-east-1 ...
    An error occurred (UnsupportedOperation) ... Operation CopyImage is not supported.

The rest of the AMI lifecycle already worked -- RegisterImage, CreateImage,
DescribeImages, and RunInstances from a created AMI -- so the gap sat at the
end of it. DeregisterImage is what Packer calls under force_deregister to
clear the AMI holding the name it is about to reuse; without it the second
run of any iterative build dies on InvalidAMIName.Duplicate and the build is
one-shot. CopyImage is the build-in-one-region, promote-to-the-others
pattern that several Gruntwork AMI modules use.

The cause was only the missing `case` arms in Ec2QueryHandler's dispatch
switch, whose default is UnsupportedOperation. EC2_ACTIONS in
AwsQueryController is not on this path for a signed request: resolveService()
takes the service from the SigV4 credential scope and only falls back to
inferServiceFromAction() when that fails. CreateImage is likewise absent from
EC2_ACTIONS and works fine. All three are added anyway so the unsigned/raw
client fallback agrees with the dispatcher.

DeregisterImage. "Deregisters the specified AMI. A deregistered AMI can't be
used to launch new instances", and it does not delete "Instances already
launched from the AMI" (API_DeregisterImage). The image is therefore
tombstoned with the documented AMI state `deregistered` rather than dropped
from the store: DescribeImages stops reporting it, its name is released so
the rebuild can claim it, RunInstances rejects it with
InvalidAMIID.Unavailable, but an instance launched from it keeps resolving
its ancestry to a guest image, so a stop/start still comes back on the right
one. Keeping the tombstone is also what lets a repeat call answer
InvalidAMIID.Unavailable ("has been deregistered and is no longer available")
instead of InvalidAMIID.NotFound ("The specified AMI doesn't exist") -- a
retry can tell the two apart. Deregistering a catalog AMI, which is owned by
amazon rather than by the caller, is AuthFailure: "trying to use an AMI for
which you do not have permissions". Snapshots are kept unless
DeleteAssociatedSnapshots is set ("Default: The snapshots are not deleted"),
and one shared with another AMI is reported `skipped` rather than deleted,
since "if a snapshot is associated with multiple AMIs, it won't be deleted
even if specified for deletion, although the AMI will still be deregistered."

CopyImage. "The copy operation must be initiated in the destination Region",
and for a Region-to-Region copy "the destination Region is the Region in
which you initiate the copy operation" (API_CopyImage) -- so the request's
own region is the destination and only the source is looked up under
SourceRegion. That matters here because Floci keys registered AMIs by
(region, id) and describeImages filters on the stored region, so a source id
that exists in us-east-1 is genuinely absent when SourceRegion names another
region; that case is InvalidAMIID.NotFound. The copy is an independent image:
its own id, its own snapshot ids (sharing the source's would make deleting
either look like it took the other's backing with it), owned by the caller.

State: AWS reports the copy as `pending` until the backing snapshots finish.
Floci's store is in-memory and the copy completes inside the call, so it is
`available` immediately -- matching what CreateImage and RegisterImage
already return rather than inventing a state machine that nothing would ever
advance. A caller polling for `available` returns on its first poll.

Concurrency. registerImage's duplicate-name check is a read-modify-write over
the whole image store, and CopyImage now reaches it too. The stripe is taken
on (region, name), not on an image id -- the id does not exist yet and is
unique by construction, whereas the name is the invariant. deregisterImage's
check-then-tombstone takes the (region, id) stripe. Both are the striped-lock
pattern already used by modifyVpcEndpoint.

Tests are driven through the service, not over HTTP, for the concurrency
cases: requests through the test server serialize enough to hide a lost
update, the same trap called out in
Ec2ModifyVpcEndpointTest.concurrentAssociationsAllSurvive. Both race tests
were confirmed to fail with their lock removed -- 6 of 24 concurrent copies
claimed one name, and one AMI was deregistered twice -- which is also why the
name race pads the store first: the window that has to be hit is the scan,
and against an empty store the test passes with or without the lock.

The rest of the coverage is over HTTP: that DeregisterImage answers
return=true and the AMI then vanishes from DescribeImages, that unknown,
already-deregistered and not-owned ids get the three distinct documented
errors, that the freed name can be registered again (the force_deregister
loop), that an instance launched from the AMI keeps running while a new
launch is refused, snapshot retention and the shared-snapshot skip, and for
CopyImage that the copy lands in the caller's region and not the source's,
is available and owned by the caller, gets its own snapshots, is launchable
where it landed, and rejects a missing or deregistered source.

Not implemented: the Encrypted/KmsKeyId, CopyImageTags, TagSpecification and
ClientToken parameters of CopyImage, and Outpost/Local Zone destinations.

* fix(ec2): release an AMI's captured image when it is deregistered

CreateImage captures the source instance's file system as a committed
Docker image (floci-ami/<ami-id>:latest). Those are real disk. Nothing
released them, so an iterative build -- Packer with force_deregister, or
any loop that rebuilds the same AMI -- left one committed layer behind per
iteration, indefinitely.

DeregisterImage now releases the capture. The AMI record itself is still
kept as a tombstone, as the DeregisterImage implementation requires for
ancestry resolution; only the Docker image is reclaimed.

The exception is the one that matters for correctness. AWS keeps instances
launched from a deregistered AMI running, and DeregisterImage's own
documentation notes that already-launched instances are unaffected -- they
can still be stopped and started. Removing the layer such an instance
boots from would break exactly that, so reclamation is skipped while any
non-terminated instance still resolves to the capture, and the tombstone
keeps its reference. Correctness before disk: the worst case is a layer
that outlives its AMI, not an instance that cannot start.

Terminated instances deliberately do not pin a capture. They can never
boot again, and treating them as live would mean nothing is ever reclaimed
in a long-running emulator.

Tests drive the real CreateImage path rather than building a fixture by
hand -- the image store returns detached copies, so setting the captured
reference on a returned Image never reaches the store and the test would
silently assert nothing. They needed two further pieces of care worth
noting:

  - The shared test configuration sets floci.services.ec2.mock=true, which
    skips all container work, so both capture and reclamation would be
    dead code under test. A QuarkusTestProfile turns it off; the container
    manager is still mocked, so no Docker is involved.
  - Outside mock mode, termination is delegated to the container manager.
    With that mocked, an instance stays "running" forever, which would
    have made the terminated-instance assertion vacuous. The mock now
    performs the same state transition the real path does.

* fix(ec2): make a capture survive the copy, and fail loudly when it cannot

Six review findings on the image-capture stack, all of which end in the same
place: an AMI that reports itself available while its file system is not what
the caller asked for.

CopyImage copied the flattened ancestry but not the capture, so launching a
copy silently started the base image. The copy now carries the reference, and
because a Docker reference is global to the daemon, reclamation counts another
AMI carrying the same tag as a live user.

A capture that could not be made was reported the same way as "there was
nothing to capture", so a refused commit produced an immediately-available AMI
that booted the ancestor. commitInstance now throws, and CreateImage drops the
half-built AMI and fails: InternalError when the commit was refused,
IncorrectInstanceState when the instance has no container to capture. Floci
commits inline, so there is no later state transition a poller could observe
and no honest way to report this asynchronously.

Two races shared one cause: the invariants over the image registry are whole
set scan-then-mutate sequences, and the three operations that hold them ran
under three different monitors. RegisterImage locked a name stripe while
DeregisterImage locked an id stripe, so a registration could reuse a snapshot
between the shared-reference scan and the delete. RunInstances took no image
lock at all, so a launch could resolve a captured tag, pause before storing its
instance, and have deregistration remove the tag underneath it. Both now run
under one imageRegistryLock; RunInstances holds it only to resolve the AMI and
publish its instances, with the container launches outside it. The lock is
single rather than striped because the capture invariant is not region-scoped:
a copy shares its source's layer across regions.

removeCommittedImage suppressed docker errors while the caller cleared the
reference regardless, so a transient failure leaked the layer permanently.
It now reports whether the layer is gone, and the reference survives a refusal.

Finally, a capture retained for a live instance was never reclaimed, because
reclamation only ran during deregistration and a second deregistration is
rejected. Termination now reclaims what deregistration had to keep.

Ec2ServiceTest builds a container-backed service with a bare container-manager
mock, so its instances have no container and every CreateImage there would now
be rejected for a reason those tests are not about; they get a commit stub.

* fix(ec2): reject a mid-launch deregistration before the launch persists anything

RunInstances checks the AMI tombstone twice: once on entry, and once under the image
registry lock, because DeregisterImage releases the captured layer as soon as no live
instance resolves to it, and a launch that had resolved the layer but not yet stored
its instance would lose it underneath.

The second check fired too late. By the time it ran, the launch had already written a
root volume per instance, the instance tags, a subnet IP, and the attachment on a
caller-supplied ENI. The reservation was never returned, so no caller had an id to
clean any of that up with, and the interface stayed in-use for good.

Move the build loop inside the same locked section, after the check, so the launch
persists nothing until it knows it is allowed to proceed. Rollback was the other
option and is worse: the subnet IP counter has no free list to return an offset to,
and a rollback path only runs once something has already gone wrong. The lock is not
meaningfully wider, since what moved inside it is in-memory record construction; the
slow part, the container launch, still runs outside.

The regression test holds the registry lock itself, so the launch parks at a known
point and the tombstone lands there on purpose rather than racing for the window.
Its file is renamed to *IntegrationTest, matching what the rest of the repo calls a
@QuarkusTest.

* test(ec2): name the captured image reclaim QuarkusTest an IntegrationTest

607 of the 736 @QuarkusTest classes on main end in IntegrationTest, and this one
starts a full application like the rest of them. Ec2CreateImageCaptureTest is left
alone: it drives a plain Ec2Service with Mockito and is not an integration test.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-12 00:44:35 -05:00
1 parent ae580974cc
commit a2285072c9
9 files changed
+1858 -116

No files matched your search

@@ -0,0 +1,400 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* CreateImage captures an instance's file system as a committed Docker image. Those layers are
* real disk, and a build loop that re-creates the same AMI would otherwise leave one behind per
* iteration, so deregistering an AMI releases its capture.
*
* <p>The exception is the case that matters for correctness: AWS keeps instances launched from a
* deregistered AMI running, and lets them stop and start again. While anything can still boot
* from a capture, the capture has to stay.
*
* <p>These drive the real CreateImage path rather than setting the captured reference by hand.
* The image store hands back detached copies, so a mutation applied to a returned Image never
* reaches the store -- a hand-built fixture silently tests nothing.
*/
@QuarkusTest
@TestProfile(Ec2CapturedImageReclaimIntegrationTest.ContainerBackedEc2.class)
class Ec2CapturedImageReclaimIntegrationTest {
/**
* The shared test configuration runs EC2 in mock mode, which skips container work entirely --
* including the capture and its reclamation, so neither path would execute. This turns it
* back on; the container manager itself is mocked, so no Docker is involved.
*/
public static class ContainerBackedEc2 implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ec2.mock", "false");
}
}
@Inject
Ec2Service service;
@InjectMock
Ec2ContainerManager containerManager;
/**
* Mocked so the reference a launch resolves is observable, and so a launch can be suspended
* inside the section that reads the AMI. The real resolver only maps an AMI id to a base
* Docker image, which no assertion here depends on.
*/
@InjectMock
AmiImageResolver amiImageResolver;
private static final String REGION = "us-east-1";
private static final String WEST = "us-west-2";
private static final String BASE_AMI = "ami-amazonlinux2023";
private static final ResolvedAmiImage BASE_IMAGE = ResolvedAmiImage.minimal("floci/base:latest");
@BeforeEach
void resolveEveryAmiToABaseImage() {
when(amiImageResolver.resolveImage(anyString())).thenReturn(BASE_IMAGE);
when(containerManager.removeCommittedImage(anyString())).thenReturn(true);
}
@BeforeEach
void terminationMarksInstancesTerminated() {
// Outside mock mode Ec2Service delegates termination to the container manager, which is
// mocked here, so without this an instance stays "running" in the store forever and any
// assertion about terminated instances would be vacuous.
doAnswer(invocation -> {
invocation.<Instance>getArgument(0).setState(InstanceState.terminated());
return null;
}).when(containerManager).terminate(any(Instance.class));
}
private Instance launch(String imageId) {
return launch(REGION, imageId);
}
private Instance launch(String region, String imageId) {
return service.runInstances(region, imageId, "t3.micro", 1, 1,
null, List.of(), null, null, List.of(), null, null)
.getInstances().getFirst();
}
/** 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());
return resolved.getValue();
}
/** Runs an instance and captures it, with the commit stubbed to the given reference. */
private Image captureAmi(String name, String tag) {
when(containerManager.commitInstance(any(Instance.class), anyString())).thenReturn(tag);
Instance source = launch(BASE_AMI);
Image image = service.createImage(REGION, source.getInstanceId(), name, "captured", true);
service.terminateInstances(REGION, List.of(source.getInstanceId()));
return image;
}
@Test
void deregisteringAnUnusedAmiReleasesItsCapture() {
Image image = captureAmi("reclaim-unused", "floci-ami/ami-unused:latest");
service.deregisterImage(REGION, image.getImageId(), false);
verify(containerManager).removeCommittedImage("floci-ami/ami-unused:latest");
}
@Test
void deregisteringAnAmiWithALiveInstanceKeepsItsCapture() {
// Removing the layer this instance boots from would break the stop/start that AWS
// explicitly still permits after deregistration.
Image image = captureAmi("reclaim-inuse", "floci-ami/ami-inuse:latest");
launch(image.getImageId());
service.deregisterImage(REGION, image.getImageId(), false);
verify(containerManager, never()).removeCommittedImage("floci-ami/ami-inuse:latest");
}
@Test
void aTerminatedInstanceDoesNotPinACapture() {
// Terminated instances can never boot again, so they must not keep the layer alive --
// otherwise nothing is ever reclaimed in a long-running emulator.
Image image = captureAmi("reclaim-terminated", "floci-ami/ami-terminated:latest");
Instance launched = launch(image.getImageId());
service.terminateInstances(REGION, List.of(launched.getInstanceId()));
service.deregisterImage(REGION, image.getImageId(), false);
verify(containerManager).removeCommittedImage("floci-ami/ami-terminated:latest");
}
@Test
void deregisteringAnAmiThatWasNeverCapturedRemovesNothing() {
// RegisterImage and catalog AMIs have no captured layer to release.
Image image = service.registerImage(REGION, "reclaim-uncaptured", "plain",
"x86_64", "/dev/xvda", List.of());
service.deregisterImage(REGION, image.getImageId(), false);
verify(containerManager, never()).removeCommittedImage(anyString());
}
// ─── The copy carries the capture ─────────────────────────────────────────
@Test
void aCopiedAmiLaunchesTheCapturedFileSystemRatherThanTheBaseImage() {
// The ancestry a copy inherits is flattened to a launchable catalog id, and the
// CreateImage chain in between lives in the source region where the copy cannot see it.
// Without the capture reference itself being copied, launching the copy silently starts
// the base image and everything the source AMI captured is gone.
String tag = "floci-ami/ami-copied:latest";
Image source = captureAmi("copy-carries-capture", tag);
Image copy = service.copyImage(WEST, REGION, source.getImageId(),
uniqueName("copy-carries-capture-west"), "copied");
Instance fromCopy = launch(WEST, copy.getImageId());
assertEquals(tag, launchedImageOf(fromCopy).dockerImage());
}
@Test
void deregisteringTheSourceKeepsACaptureItsCopyStillCarries() {
// The copy shares the layer rather than duplicating it, so releasing it here would leave
// a live AMI in another region whose file system had been deleted.
String tag = "floci-ami/ami-copy-shared:latest";
Image source = captureAmi("copy-shared-capture", tag);
service.copyImage(WEST, REGION, source.getImageId(),
uniqueName("copy-shared-capture-west"), "copied");
service.deregisterImage(REGION, source.getImageId(), false);
verify(containerManager, never()).removeCommittedImage(tag);
}
// ─── A capture that fails is not an available AMI ─────────────────────────
@Test
void aCaptureThatFailsFailsCreateImageRatherThanProducingAnEmptyAmi() {
// An AMI with no captured file system launches its ancestor. Returning one here would
// report success and hand back an image that does not contain what was asked for.
when(containerManager.commitInstance(any(Instance.class), anyString()))
.thenThrow(new Ec2ContainerManager.CaptureFailedException("daemon is unavailable", null));
Instance source = launch(BASE_AMI);
AwsException failure = assertThrows(AwsException.class, () ->
service.createImage(REGION, source.getInstanceId(), uniqueName("failed-capture"),
"captured", true));
assertEquals("InternalError", failure.getErrorCode());
}
@Test
void anInstanceWithNoContainerToCaptureIsRejected() {
// Nothing to commit means nothing to capture, and an AMI recorded anyway would boot the
// ancestor. AWS reports CreateImage against an instance that is not running or stopped as
// IncorrectInstanceState, which is the same condition seen from here.
when(containerManager.commitInstance(any(Instance.class), anyString())).thenReturn(null);
Instance source = launch(BASE_AMI);
AwsException failure = assertThrows(AwsException.class, () ->
service.createImage(REGION, source.getInstanceId(), uniqueName("no-container"),
"captured", true));
assertEquals("IncorrectInstanceState", failure.getErrorCode());
}
@Test
void anAmiWhoseCaptureFailedDoesNotHoldOnToItsName() {
// The AMI record is created before the capture is attempted. Left behind, it would meet
// the retry with InvalidAMIName.Duplicate against an image nothing can describe.
String name = uniqueName("failed-capture-name");
when(containerManager.commitInstance(any(Instance.class), anyString()))
.thenThrow(new Ec2ContainerManager.CaptureFailedException("daemon is unavailable", null));
Instance source = launch(BASE_AMI);
assertThrows(AwsException.class, () ->
service.createImage(REGION, source.getInstanceId(), name, "captured", true));
when(containerManager.commitInstance(any(Instance.class), anyString()))
.thenReturn("floci-ami/ami-retry:latest");
Image retried = service.createImage(REGION, source.getInstanceId(), name, "captured", true);
assertEquals(name, retried.getName());
}
// ─── A failed removal keeps the reference ─────────────────────────────────
@Test
void aRemovalTheDaemonRefusesKeepsTheReferenceForALaterAttempt() {
// Deregistration is rejected the second time and nothing else can rediscover the tag, so
// clearing the reference on a transient docker failure leaks the layer permanently. The
// second termination is the later attempt: it only reaches the daemon at all if the
// reference survived the first failure.
String tag = "floci-ami/ami-removal-refused:latest";
Image image = captureAmi("removal-refused", tag);
Instance dependent = launch(image.getImageId());
service.deregisterImage(REGION, image.getImageId(), false);
verify(containerManager, never()).removeCommittedImage(tag);
when(containerManager.removeCommittedImage(tag)).thenReturn(false);
service.terminateInstances(REGION, List.of(dependent.getInstanceId()));
verify(containerManager, times(1)).removeCommittedImage(tag);
when(containerManager.removeCommittedImage(tag)).thenReturn(true);
service.terminateInstances(REGION, List.of(dependent.getInstanceId()));
verify(containerManager, times(2)).removeCommittedImage(tag);
}
// ─── Termination reclaims what deregistration had to retain ───────────────
@Test
void terminatingTheLastDependentInstanceReleasesARetainedCapture() {
// Deregistration is the only other place a capture is reclaimed and it is rejected the
// second time, so a capture retained for a live instance would otherwise stay on disk for
// the lifetime of the emulator.
String tag = "floci-ami/ami-retained:latest";
Image image = captureAmi("retained-then-terminated", tag);
Instance dependent = launch(image.getImageId());
service.deregisterImage(REGION, image.getImageId(), false);
verify(containerManager, never()).removeCommittedImage(tag);
service.terminateInstances(REGION, List.of(dependent.getInstanceId()));
verify(containerManager).removeCommittedImage(tag);
}
@Test
void terminatingOneOfTwoDependentsKeepsTheCapture() {
String tag = "floci-ami/ami-two-dependents:latest";
Image image = captureAmi("two-dependents", tag);
Instance first = launch(image.getImageId());
launch(image.getImageId());
service.deregisterImage(REGION, image.getImageId(), false);
service.terminateInstances(REGION, List.of(first.getInstanceId()));
verify(containerManager, never()).removeCommittedImage(tag);
}
@Test
void terminatingAnInstanceOfAStillRegisteredAmiKeepsTheCapture() {
// The AMI can still be launched again; its capture is not garbage.
String tag = "floci-ami/ami-still-registered:latest";
Image image = captureAmi("still-registered", tag);
Instance dependent = launch(image.getImageId());
service.terminateInstances(REGION, List.of(dependent.getInstanceId()));
verify(containerManager, never()).removeCommittedImage(tag);
}
// ─── The registry invariants are one lock ─────────────────────────────────
@Test
void deregistrationCannotReclaimACaptureALaunchHasAlreadyResolved() throws Exception {
// The launch is suspended after it has resolved the AMI and before its instance is
// stored. Deregistration decides whether to release the capture by scanning for live
// instances, so if it can run in that window it sees none and deletes the layer the
// launch is about to boot from.
String tag = "floci-ami/ami-launch-race:latest";
Image image = captureAmi("launch-race", tag);
CountDownLatch resolving = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(amiImageResolver.resolveImage(anyString())).thenAnswer(invocation -> {
resolving.countDown();
assertTrue(release.await(30, TimeUnit.SECONDS), "the launch was never released");
return BASE_IMAGE;
});
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<Instance> launching = pool.submit(() -> launch(image.getImageId()));
assertTrue(resolving.await(30, TimeUnit.SECONDS), "the launch never reached the AMI");
Future<?> deregistering = pool.submit(
() -> service.deregisterImage(REGION, image.getImageId(), false));
assertThrows(TimeoutException.class, () -> deregistering.get(1, TimeUnit.SECONDS),
"deregistration ran while a launch was mid-resolution of the same AMI");
release.countDown();
launching.get(30, TimeUnit.SECONDS);
deregistering.get(30, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
// The launch's instance was published before deregistration could look, so the capture is
// retained for it rather than deleted underneath it.
verify(containerManager, never()).removeCommittedImage(tag);
}
@Test
void registrationCannotSlipBetweenDeregistrationsSnapshotScanAndItsDelete() throws Exception {
// DeregisterImage decides which snapshots to delete by scanning the other AMIs for shared
// references. A registration that lands between that scan and the delete leaves a live
// AMI whose backing snapshot has been removed, so the two must exclude each other. The
// deregistration is suspended inside its critical section to check that they do.
String tag = "floci-ami/ami-register-race:latest";
Image image = captureAmi("register-race", tag);
CountDownLatch inside = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(containerManager.removeCommittedImage(tag)).thenAnswer(invocation -> {
inside.countDown();
assertTrue(release.await(30, TimeUnit.SECONDS), "the deregistration was never released");
return true;
});
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> deregistering = pool.submit(
() -> service.deregisterImage(REGION, image.getImageId(), true));
assertTrue(inside.await(30, TimeUnit.SECONDS), "deregistration never started");
Future<Image> registering = pool.submit(() -> service.registerImage(
REGION, uniqueName("register-race-other"), "other", "x86_64", "/dev/xvda",
List.of()));
assertThrows(TimeoutException.class, () -> registering.get(1, TimeUnit.SECONDS),
"registration ran inside a deregistration's critical section");
release.countDown();
deregistering.get(30, TimeUnit.SECONDS);
assertTrue(registering.get(30, TimeUnit.SECONDS).getImageId().startsWith("ami-"));
} finally {
pool.shutdownNow();
}
}
private static String uniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID();
}
}
@@ -0,0 +1,177 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CommitCmd;
import com.github.dockerjava.api.command.RemoveImageCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Answers.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
/**
* CreateImage used to record only metadata: the new AMI carried a sourceImageId pointing at the
* ancestor, so launching it started the *base* image and everything provisioned on the source
* instance was silently discarded. A Packer build against Floci therefore reported success and
* produced an empty artifact -- the AMI existed, was "available", and contained nothing.
*
* <p>These cover the capture itself. That the captured image is what actually gets launched is
* covered end to end by a real Packer build; see the commit message.
*/
class Ec2CreateImageCaptureTest {
private static final String CONTAINER_ID = "container-1";
private static Ec2ContainerManager managerWith(DockerClient dockerClient) {
return new Ec2ContainerManager(
mock(ContainerBuilder.class),
mock(ContainerLifecycleManager.class),
mock(ContainerLogStreamer.class),
mock(ContainerDetector.class),
mock(DockerHostResolver.class),
dockerClient,
mock(PortAllocator.class),
mock(EmulatorConfig.class),
mock(Ec2MetadataServer.class),
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class),
mock(ContainerNetworkReachability.class),
mock(VpcNetworkManager.class));
}
private static Instance instance(String containerId) {
Instance instance = new Instance();
instance.setInstanceId("i-capture");
instance.setDockerContainerId(containerId);
return instance;
}
@Test
void commitInstanceCommitsTheContainerToTheRequestedRepositoryAndTag() {
DockerClient dockerClient = mock(DockerClient.class);
CommitCmd commit = mock(CommitCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.commitCmd(CONTAINER_ID)).thenReturn(commit);
when(commit.exec()).thenReturn("sha256:abc123");
Ec2ContainerManager manager = managerWith(dockerClient);
String tag = manager.commitInstance(instance(CONTAINER_ID), "floci-ami/ami-123:latest");
assertEquals("floci-ami/ami-123:latest", tag);
// Repository and tag must be split, not passed as one string -- docker-java would
// otherwise produce a repository literally named "floci-ami/ami-123:latest".
verify(commit).withRepository("floci-ami/ami-123");
verify(commit).withTag("latest");
}
@Test
void commitInstanceDefaultsTheTagWhenTheReferenceHasNone() {
DockerClient dockerClient = mock(DockerClient.class);
CommitCmd commit = mock(CommitCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.commitCmd(CONTAINER_ID)).thenReturn(commit);
when(commit.exec()).thenReturn("sha256:abc123");
managerWith(dockerClient).commitInstance(instance(CONTAINER_ID), "floci-ami/ami-123");
verify(commit).withRepository("floci-ami/ami-123");
verify(commit).withTag("latest");
}
@Test
void commitInstanceWithoutAContainerCapturesNothing() {
DockerClient dockerClient = mock(DockerClient.class);
assertNull(managerWith(dockerClient).commitInstance(instance(null), "floci-ami/ami-1:latest"));
verify(dockerClient, never()).commitCmd(org.mockito.ArgumentMatchers.anyString());
}
@Test
void aFailedCaptureThrowsRatherThanReportingNothingToCapture() {
// Reporting a refused commit the same way as "there was nothing to commit" hands back an
// AMI that is immediately available and boots the ancestor, so a Packer build succeeds
// and produces the empty artifact this capture exists to prevent. CreateImage turns this
// into a failed call.
DockerClient dockerClient = mock(DockerClient.class);
CommitCmd commit = mock(CommitCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.commitCmd(CONTAINER_ID)).thenReturn(commit);
when(commit.exec()).thenThrow(new RuntimeException("daemon is unavailable"));
Ec2ContainerManager.CaptureFailedException failure = assertThrows(
Ec2ContainerManager.CaptureFailedException.class,
() -> managerWith(dockerClient)
.commitInstance(instance(CONTAINER_ID), "floci-ami/ami-123:latest"));
assertTrue(failure.getMessage().contains("daemon is unavailable"));
}
@Test
void removeCommittedImageRemovesTheCapture() {
DockerClient dockerClient = mock(DockerClient.class);
RemoveImageCmd remove = mock(RemoveImageCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.removeImageCmd("floci-ami/ami-123:latest")).thenReturn(remove);
assertTrue(managerWith(dockerClient).removeCommittedImage("floci-ami/ami-123:latest"));
verify(remove).withForce(true);
verify(remove).exec();
}
@Test
void removingAnAlreadyAbsentCaptureIsNotAnError() {
// Deregistering twice, or after a docker prune, must not surface as a failure.
DockerClient dockerClient = mock(DockerClient.class);
RemoveImageCmd remove = mock(RemoveImageCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.removeImageCmd("floci-ami/ami-gone:latest")).thenReturn(remove);
when(remove.exec()).thenThrow(new NotFoundException("no such image"));
assertTrue(managerWith(dockerClient).removeCommittedImage("floci-ami/ami-gone:latest"));
}
@Test
void aRemovalTheDaemonRefusesIsReportedAsNotRemoved() {
// The caller clears the AMI's reference to the layer on the strength of this answer, and
// nothing can rediscover the tag afterwards, so a refusal must not read as a removal.
DockerClient dockerClient = mock(DockerClient.class);
RemoveImageCmd remove = mock(RemoveImageCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.removeImageCmd("floci-ami/ami-busy:latest")).thenReturn(remove);
when(remove.exec()).thenThrow(new RuntimeException("conflict: image is in use"));
assertFalse(managerWith(dockerClient).removeCommittedImage("floci-ami/ami-busy:latest"));
}
@Test
void removeCommittedImageIgnoresAnAmiThatWasNeverCaptured() {
DockerClient dockerClient = mock(DockerClient.class);
assertTrue(managerWith(dockerClient).removeCommittedImage(null));
verify(dockerClient, never()).removeImageCmd(org.mockito.ArgumentMatchers.anyString());
}
@Test
void committedImageTagIsNamespacedAndUniquePerAmi() {
assertEquals("floci-ami/ami-123:latest", Ec2Service.committedImageTag("ami-123"));
assertEquals("floci-ami/ami-456:latest", Ec2Service.committedImageTag("ami-456"));
}
}
@@ -0,0 +1,613 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* DeregisterImage and CopyImage. Without DeregisterImage an iterative image build is one-shot:
* the second run hits InvalidAMIName.Duplicate and Packer's force_deregister has no way to clear
* the previous AMI. Without CopyImage the build-in-one-region, promote-to-others pattern cannot
* run at all.
*
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeregisterImage.html">DeregisterImage</a>
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopyImage.html">CopyImage</a>
*/
@QuarkusTest
class Ec2DeregisterAndCopyImageIntegrationTest {
@Inject
Ec2Service service;
private static final String EAST = "us-east-1";
private static final String WEST = "us-west-2";
private static final String EAST_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String WEST_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-west-2/ec2/aws4_request";
private String ec2(String auth, String action, String... formParams) {
var req = given().formParam("Action", action).header("Authorization", auth);
for (int i = 0; i < formParams.length; i += 2) {
req = req.formParam(formParams[i], formParams[i + 1]);
}
return req.when().post("/").then().statusCode(200).extract().asString();
}
private String xmlValue(String xml, String element) {
String open = "<" + element + ">";
String close = "</" + element + ">";
int start = xml.indexOf(open);
return start < 0 ? null : xml.substring(start + open.length(), xml.indexOf(close, start));
}
/** A name unique per test run, so tests never collide on InvalidAMIName.Duplicate. */
private String uniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID();
}
private String registerViaHttp(String auth, String name) {
return xmlValue(ec2(auth, "RegisterImage", "Name", name, "RootDeviceName", "/dev/xvda"), "imageId");
}
// ─── DeregisterImage ──────────────────────────────────────────────────────
@Test
void deregisterImageSucceedsAndTheAmiStopsBeingDescribed() {
String name = uniqueName("floci-deregister");
String imageId = registerViaHttp(EAST_AUTH, name);
assertTrue(ec2(EAST_AUTH, "DescribeImages", "Owner.1", "self").contains(imageId));
given()
.formParam("Action", "DeregisterImage")
.formParam("ImageId", imageId)
.header("Authorization", EAST_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
// "Returns true if the request succeeds; otherwise, it returns an error."
.body(hasXPath("//*[local-name()='DeregisterImageResponse']/*[local-name()='return']",
equalTo("true")));
assertFalse(ec2(EAST_AUTH, "DescribeImages", "Owner.1", "self").contains(imageId),
"a deregistered AMI must not be reported by DescribeImages");
}
@Test
void deregisteringAnUnknownImageIsRejected() {
// Silently succeeding here would make an idempotency check on a fresh account believe a
// previous AMI had just been cleaned up.
given()
.formParam("Action", "DeregisterImage")
.formParam("ImageId", "ami-0000000000000dead")
.header("Authorization", EAST_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']", equalTo("InvalidAMIID.NotFound")));
}
@Test
void deregisteringTwiceReportsTheImageAsUnavailable() {
// "The specified AMI has been deregistered and is no longer available" -- distinguishable
// from an id that never existed, which is what makes a retry diagnosable.
String imageId = registerViaHttp(EAST_AUTH, uniqueName("floci-deregister-twice"));
ec2(EAST_AUTH, "DeregisterImage", "ImageId", imageId);
given()
.formParam("Action", "DeregisterImage")
.formParam("ImageId", imageId)
.header("Authorization", EAST_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']", equalTo("InvalidAMIID.Unavailable")));
}
@Test
void deregisteringSomeoneElsesAmiIsAnAuthFailure() {
// Catalog AMIs are owned by amazon. AWS reports "trying to use an AMI for which you do not
// have permissions" as AuthFailure rather than as a missing image.
given()
.formParam("Action", "DeregisterImage")
.formParam("ImageId", "ami-0abcdef1234567890")
.header("Authorization", EAST_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']", equalTo("AuthFailure")));
}
@Test
void theNameIsFreedSoTheSameAmiNameCanBeRegisteredAgain() {
// Exactly what Packer's force_deregister does: deregister the AMI holding the name, then
// register the rebuilt one under the same name. Without this the second build fails with
// InvalidAMIName.Duplicate.
String name = uniqueName("floci-packer-rebuild");
String first = registerViaHttp(EAST_AUTH, name);
ec2(EAST_AUTH, "DeregisterImage", "ImageId", first);
String second = registerViaHttp(EAST_AUTH, name);
assertNotEquals(first, second);
String described = ec2(EAST_AUTH, "DescribeImages", "Owner.1", "self");
assertTrue(described.contains(second));
assertFalse(described.contains(first));
}
@Test
void anInstanceLaunchedFromTheAmiKeepsRunningAfterDeregistration() {
// "Deregistering an AMI does not delete ... Instances already launched from the AMI."
Image image = service.registerImage(EAST, uniqueName("floci-live-instance"), null,
"x86_64", "/dev/xvda", null);
String instanceId = service.runInstances(EAST, image.getImageId(), "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null, null)
.getInstances().getFirst().getInstanceId();
service.deregisterImage(EAST, image.getImageId(), false);
Instance instance = service.describeInstances(EAST, List.of(instanceId), java.util.Map.of()).getFirst()
.getInstances().getFirst();
assertEquals("running", instance.getState().getName());
assertEquals(image.getImageId(), instance.getImageId());
}
@Test
void aDeregisteredAmiCannotLaunchNewInstances() {
// "A deregistered AMI can't be used to launch new instances." Falling back to the default
// guest image instead would silently launch the wrong thing.
Image image = service.registerImage(EAST, uniqueName("floci-no-relaunch"), null,
"x86_64", "/dev/xvda", null);
service.deregisterImage(EAST, image.getImageId(), false);
AwsException error = assertThrows(AwsException.class, () -> service.runInstances(
EAST, image.getImageId(), "t3.micro", 1, 1, null, List.of(), null, null,
List.of(), null, null, null));
assertEquals("InvalidAMIID.Unavailable", error.getErrorCode());
}
@Test
void snapshotsAreKeptByDefaultAndDeletedOnlyOnRequest() {
// "Default: The snapshots are not deleted."
Image kept = service.registerImage(EAST, uniqueName("floci-keep-snapshots"), null,
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex())));
String keptSnapshot = snapshotIdOf(kept);
service.deregisterImage(EAST, kept.getImageId(), false);
assertEquals(1, service.describeSnapshots(EAST, List.of(keptSnapshot), null, null).size());
Image deleted = service.registerImage(EAST, uniqueName("floci-delete-snapshots"), null,
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex())));
String deletedSnapshot = snapshotIdOf(deleted);
List<Ec2Service.SnapshotDeletion> results =
service.deregisterImage(EAST, deleted.getImageId(), true);
assertEquals(List.of(new Ec2Service.SnapshotDeletion(deletedSnapshot, "success")), results);
assertThrows(AwsException.class,
() -> service.describeSnapshots(EAST, List.of(deletedSnapshot), null, null));
}
@Test
void aSnapshotSharedWithAnotherAmiIsSkippedRatherThanDeleted() {
// "if a snapshot is associated with multiple AMIs, it won't be deleted even if specified
// for deletion, although the AMI will still be deregistered."
String snapshotId = "snap-" + hex();
Image first = service.registerImage(EAST, uniqueName("floci-shared-a"), null,
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", snapshotId)));
service.registerImage(EAST, uniqueName("floci-shared-b"), null,
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", snapshotId)));
List<Ec2Service.SnapshotDeletion> results =
service.deregisterImage(EAST, first.getImageId(), true);
assertEquals(List.of(new Ec2Service.SnapshotDeletion(snapshotId, "skipped")), results);
assertEquals(1, service.describeSnapshots(EAST, List.of(snapshotId), null, null).size());
assertTrue(service.describeImages(EAST, List.of(first.getImageId()), null).isEmpty(),
"the AMI is still deregistered even when its snapshot is kept");
}
// ─── CopyImage ────────────────────────────────────────────────────────────
@Test
void copyImageProducesADistinctAmiInTheRegionTheCallWasMadeIn() {
// "The copy operation must be initiated in the destination Region" -- the destination is
// the caller's own region, so the copy must appear in us-west-2 and not in us-east-1.
String sourceName = uniqueName("floci-copy-source");
String sourceId = registerViaHttp(EAST_AUTH, sourceName);
String copyName = uniqueName("floci-copy-dest");
String copyId = xmlValue(ec2(WEST_AUTH, "CopyImage",
"SourceRegion", EAST,
"SourceImageId", sourceId,
"Name", copyName,
"Description", "promoted"), "imageId");
assertNotEquals(sourceId, copyId);
assertTrue(copyId.startsWith("ami-"));
String west = ec2(WEST_AUTH, "DescribeImages", "Owner.1", "self");
assertTrue(west.contains(copyId), "the copy must be visible in the destination region");
assertTrue(west.contains(copyName));
assertFalse(west.contains(sourceId), "the source AMI stays in its own region");
String east = ec2(EAST_AUTH, "DescribeImages", "Owner.1", "self");
assertTrue(east.contains(sourceId));
assertFalse(east.contains(copyId), "the copy must not leak back into the source region");
}
@Test
void theCopyIsOwnedByTheCallerAndAvailableImmediately() {
// AWS reports 'pending' until the backing snapshots finish copying. Floci's store is
// in-memory and the copy completes within the call, so it is 'available' at once, which
// is what CreateImage and RegisterImage already report.
Image source = service.registerImage(EAST, uniqueName("floci-copy-state-src"), null,
"arm64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex())));
Image copy = service.copyImage(WEST, EAST, source.getImageId(),
uniqueName("floci-copy-state-dst"), "promoted");
assertEquals("available", copy.getState());
assertEquals(source.getOwnerId(), copy.getOwnerId());
assertFalse(copy.isPublic());
assertEquals("arm64", copy.getArchitecture());
assertEquals("/dev/xvda", copy.getRootDeviceName());
assertEquals("promoted", copy.getDescription());
assertEquals(WEST, copy.getRegion());
}
@Test
void theCopyGetsItsOwnSnapshotsRatherThanSharingTheSourcesBacking() {
// Two AMIs sharing one snapshot would make deleting either look like it took the other's
// backing with it -- and the source's snapshots are not in the destination region anyway.
Image source = service.registerImage(EAST, uniqueName("floci-copy-snap-src"), null,
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex())));
Image copy = service.copyImage(WEST, EAST, source.getImageId(),
uniqueName("floci-copy-snap-dst"), null);
assertNotEquals(snapshotIdOf(source), snapshotIdOf(copy));
assertEquals(1, service.describeSnapshots(WEST, List.of(snapshotIdOf(copy)), null, null).size());
assertEquals(1, service.describeSnapshots(EAST, List.of(snapshotIdOf(source)), null, null).size());
}
@Test
void aCopyCanBeLaunchedInTheDestinationRegion() {
// The promotion pattern is only useful if the copy is launchable where it landed.
Image source = service.registerImage(EAST, uniqueName("floci-copy-launch-src"), null,
"x86_64", "/dev/xvda", null);
Image copy = service.copyImage(WEST, EAST, source.getImageId(),
uniqueName("floci-copy-launch-dst"), null);
String instanceId = service.runInstances(WEST, copy.getImageId(), "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null, null)
.getInstances().getFirst().getInstanceId();
assertEquals(copy.getImageId(), service.describeInstances(WEST, List.of(instanceId), java.util.Map.of())
.getFirst().getInstances().getFirst().getImageId());
}
@Test
void copyingFromARegionThatHasNoSuchImageIsRejected() {
// Registered AMIs are region-scoped, so a source id that exists in us-east-1 is genuinely
// absent when SourceRegion names a region it was never copied to.
String sourceId = registerViaHttp(EAST_AUTH, uniqueName("floci-copy-wrong-region"));
given()
.formParam("Action", "CopyImage")
.formParam("SourceRegion", "eu-west-1")
.formParam("SourceImageId", sourceId)
.formParam("Name", uniqueName("floci-copy-wrong-region-dst"))
.header("Authorization", WEST_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']", equalTo("InvalidAMIID.NotFound")));
}
@Test
void copyingADeregisteredSourceIsRejected() {
String sourceId = registerViaHttp(EAST_AUTH, uniqueName("floci-copy-deregistered"));
ec2(EAST_AUTH, "DeregisterImage", "ImageId", sourceId);
given()
.formParam("Action", "CopyImage")
.formParam("SourceRegion", EAST)
.formParam("SourceImageId", sourceId)
.formParam("Name", uniqueName("floci-copy-deregistered-dst"))
.header("Authorization", WEST_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']", equalTo("InvalidAMIID.Unavailable")));
}
@Test
void copyImageRequiresNameSourceImageIdAndSourceRegion() {
// All three are documented as required; SourceRegion in particular has no useful default,
// since a missing one would silently mean "the destination region".
assertEquals("MissingParameter", assertThrows(AwsException.class,
() -> service.copyImage(WEST, EAST, null, "n", null)).getErrorCode());
assertEquals("MissingParameter", assertThrows(AwsException.class,
() -> service.copyImage(WEST, null, "ami-0abcdef1234567890", "n", null)).getErrorCode());
assertEquals("MissingParameter", assertThrows(AwsException.class,
() -> service.copyImage(WEST, EAST, "ami-0abcdef1234567890", null, null)).getErrorCode());
}
// ─── Concurrency ──────────────────────────────────────────────────────────
//
// Driven through the service rather than over HTTP: requests through the test server are
// serialized enough that the HTTP path does not reliably reproduce a lost update, so an
// HTTP-level test would pass with the locks removed (the same trap as
// Ec2ModifyVpcEndpointTest.concurrentAssociationsAllSurvive).
@Test
void concurrentCopiesUnderOneNameYieldExactlyOneAmi() throws Exception {
// A multi-region promotion job fans out and retries, so the same (region, name) can be
// requested several times at once. The duplicate-name check is a read-modify-write over
// the whole image store: unlocked, every racer sees no duplicate and every racer inserts,
// leaving several AMIs sharing a name that is documented as unique.
//
// The window between the scan and the insert is what has to be hit, so the store is
// padded first: with a few thousand images the scan takes long enough that the race is
// reproducible rather than theoretical. Removing the lock in registerImage fails this
// test; the same test against an empty store passes with or without it.
Image source = padStoreAndRegisterSource();
for (int round = 0; round < RACE_ROUNDS; round++) {
String name = uniqueName("floci-race-dst");
AtomicInteger duplicates = new AtomicInteger();
List<Image> created = runConcurrently(RACE_THREADS, () -> {
try {
return service.copyImage(WEST, EAST, source.getImageId(), name, null);
} catch (AwsException e) {
assertEquals("InvalidAMIName.Duplicate", e.getErrorCode());
duplicates.incrementAndGet();
return null;
}
});
List<Image> winners = created.stream().filter(java.util.Objects::nonNull).toList();
assertEquals(1, winners.size(),
"exactly one copy may claim the name; round " + round + " produced " + winners.size());
assertEquals(RACE_THREADS - 1, duplicates.get());
assertEquals(1, service.describeImages(WEST, List.of(), List.of("self")).stream()
.filter(img -> name.equals(img.getName()))
.count(), "the store must not end up with two AMIs sharing a name");
}
}
@Test
void concurrentDeregistrationsOfOneAmiSucceedExactlyOnce() throws Exception {
// Deregistration is a read-modify-write on one image: read the state, reject if it is
// already a tombstone, write the tombstone. Unlocked, two racers can both observe the AMI
// as available and both report success, so a caller retrying cannot tell which attempt
// actually did the work -- and with DeleteAssociatedSnapshots both would then run the
// deletion pass.
for (int round = 0; round < RACE_ROUNDS; round++) {
Image image = service.registerImage(EAST, uniqueName("floci-race-deregister"), null,
"x86_64", "/dev/xvda", null);
AtomicInteger successes = new AtomicInteger();
AtomicInteger unavailable = new AtomicInteger();
runConcurrently(RACE_THREADS, () -> {
try {
service.deregisterImage(EAST, image.getImageId(), true);
successes.incrementAndGet();
} catch (AwsException e) {
assertEquals("InvalidAMIID.Unavailable", e.getErrorCode());
unavailable.incrementAndGet();
}
return null;
});
assertEquals(1, successes.get(), "round " + round + " deregistered the same AMI twice");
assertEquals(RACE_THREADS - 1, unavailable.get());
assertTrue(service.describeImages(EAST, List.of(image.getImageId()), List.of()).isEmpty());
}
}
@Test
void concurrentCopiesUnderDistinctNamesAllSurvive() throws Exception {
// The name stripe must not swallow unrelated copies: fanning one AMI out under distinct
// names has to leave every one of them in the store.
Image source = service.registerImage(EAST, uniqueName("floci-fanout-src"), null,
"x86_64", "/dev/xvda", null);
String prefix = uniqueName("floci-fanout-dst");
AtomicInteger seq = new AtomicInteger();
List<Image> copies = runConcurrently(24,
() -> service.copyImage(WEST, EAST, source.getImageId(),
prefix + "-" + seq.getAndIncrement(), null));
Set<String> ids = copies.stream().map(Image::getImageId).collect(Collectors.toSet());
assertEquals(24, ids.size(), "every concurrent copy must get a distinct id");
assertEquals(24, service.describeImages(WEST, List.of(), List.of("self")).stream()
.filter(img -> img.getName().startsWith(prefix))
.count(), "every concurrent copy must survive in the store");
}
private static final int RACE_THREADS = 24;
private static final int RACE_ROUNDS = 8;
private static final int STORE_PADDING = 2000;
/**
* Pads the image store so the read-modify-write windows are wide enough to hit, and returns a
* source AMI to copy. The padding is what makes the race reproducible: the duplicate-name
* check scans every image in the store.
*/
private Image padStoreAndRegisterSource() {
String padPrefix = uniqueName("floci-race-pad");
for (int i = 0; i < STORE_PADDING; i++) {
service.registerImage(WEST, padPrefix + "-" + i, null, "x86_64", "/dev/xvda", null);
}
return service.registerImage(EAST, uniqueName("floci-race-src"), null,
"x86_64", "/dev/xvda", null);
}
private <T> List<T> runConcurrently(int threads, Callable<T> body) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch start = new CountDownLatch(1);
List<Future<T>> futures = new ArrayList<>();
for (int i = 0; i < threads; i++) {
futures.add(pool.submit(() -> {
start.await();
return body.call();
}));
}
start.countDown();
List<T> results = new ArrayList<>();
for (Future<T> future : futures) {
results.add(future.get(30, TimeUnit.SECONDS));
}
pool.shutdown();
return results;
}
/**
* A DeregisterImage landing after a launch's first tombstone check must leave nothing behind.
* The rejection used to arrive only once the launch had already persisted its root volume, its
* tags, its subnet IP and, worst of the four, the attachment on a caller-supplied ENI. No
* reservation was ever returned, so no caller had an id to clean any of it up with, and the
* interface stayed "in-use" for good.
*
* <p>The interleaving is made exact rather than raced for. The test holds the registry lock
* the launch has to acquire, which parks the launch at a known point, deregisters the AMI
* while it is parked, and only then releases. Every store write on the launch path lives on
* the far side of that lock, so a launch parked there has written nothing yet.
*/
@Test
void aTombstoneLandingMidLaunchLeavesNoOrphanedResources() throws Exception {
Image image = service.registerImage(EAST, uniqueName("floci-midlaunch"), null,
"x86_64", "/dev/xvda", null);
String subnetId = service.describeSubnets(EAST, List.of(), Map.of()).getFirst().getSubnetId();
NetworkInterface eni = service.createNetworkInterface(EAST, subnetId,
"mid-launch tombstone probe", null, null, null, null);
int volumesBefore = service.describeVolumes(EAST, List.of(), Map.of()).size();
AtomicReference<Throwable> outcome = new AtomicReference<>();
try {
landATombstoneOnAParkedLaunch(image, subnetId, eni, outcome, volumesBefore);
} finally {
// @QuarkusTest classes share one application, and a leftover interface here is visible
// to every other test in the run. Best effort on purpose: if the invariant above broke
// the interface is still attached and undeletable, and the assertion that caught that
// is the news, not the failed cleanup.
try {
service.deleteNetworkInterface(EAST, eni.getNetworkInterfaceId());
} catch (AwsException ignored) {
// reported by the assertions above
}
}
}
private void landATombstoneOnAParkedLaunch(Image image, String subnetId, NetworkInterface eni,
AtomicReference<Throwable> outcome, int volumesBefore)
throws Exception {
Thread launcher = new Thread(() -> {
try {
service.runInstances(EAST, image.getImageId(), "t3.micro", 1, 1, null,
List.of(), subnetId, null, List.of(new Tag("Name", "orphan-probe")),
null, null, null, eni.getNetworkInterfaceId(), 0);
} catch (Throwable t) {
outcome.set(t);
}
}, "mid-launch-tombstone");
synchronized (service.imageRegistryLock()) {
launcher.start();
awaitParkedOnTheRegistryLock(launcher);
service.deregisterImage(EAST, image.getImageId(), false);
}
launcher.join(TimeUnit.SECONDS.toMillis(30));
assertFalse(launcher.isAlive(), "the parked launch never finished");
assertInstanceOf(AwsException.class, outcome.get(), "the launch must be rejected outright");
assertEquals("InvalidAMIID.Unavailable", ((AwsException) outcome.get()).getErrorCode());
assertEquals(volumesBefore, service.describeVolumes(EAST, List.of(), Map.of()).size(),
"a rejected launch must not leave its root volume behind");
NetworkInterface after = service.describeNetworkInterfaces(EAST,
List.of(eni.getNetworkInterfaceId()), Map.of(), 0, null).networkInterfaces().getFirst();
assertNull(after.getAttachment(),
"a rejected launch must not leave the caller's ENI attached to an instance that does not exist");
assertEquals("available", after.getStatus(),
"a rejected launch must return the caller's ENI, not strand it in-use");
}
/**
* Blocks until the launch thread is waiting to enter the registry-lock section of
* {@code runInstances}, which is the only point at which the tombstone can be landed
* mid-launch on purpose. Matching on the frame as well as the state keeps a thread blocked
* somewhere else from being mistaken for a parked launch, which would deregister too early
* and let the launch fail its *first* check instead, proving nothing.
*/
private static void awaitParkedOnTheRegistryLock(Thread thread) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
while (System.nanoTime() - deadline < 0) {
StackTraceElement[] stack = thread.getStackTrace();
if (thread.getState() == Thread.State.BLOCKED && stack.length > 0
&& "runInstances".equals(stack[0].getMethodName())
&& Ec2Service.class.getName().equals(stack[0].getClassName())) {
return;
}
Thread.sleep(1);
}
throw new AssertionError("the launch never parked on the image registry lock");
}
// ─── Helpers ──────────────────────────────────────────────────────────────
private static BlockDeviceMapping mapping(String device, String snapshotId) {
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setSnapshotId(snapshotId);
ebs.setVolumeSize(8);
ebs.setVolumeType("gp3");
ebs.setDeleteOnTermination(true);
BlockDeviceMapping bdm = new BlockDeviceMapping();
bdm.setDeviceName(device);
bdm.setEbs(ebs);
return bdm;
}
private static String snapshotIdOf(Image image) {
return image.getBlockDeviceMappings().getFirst().getEbs().getSnapshotId();
}
private static String hex() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 17);
}
}
@@ -65,6 +65,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
@@ -1051,7 +1052,7 @@ class Ec2ServiceTest {
@Test
void createImageRebootsTheSourceInstanceUnlessNoRebootIsSet() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
Ec2ContainerManager containerManager = capturingContainerManager();
Ec2Service service = liveService(containerManager, mock(AmiImageResolver.class));
String instanceId = runOne(service, "ami-src");
@@ -1066,7 +1067,8 @@ class Ec2ServiceTest {
@Test
void runInstancesOnACreatedImageResolvesTheSourceGuest() {
AmiImageResolver resolver = mock(AmiImageResolver.class);
Ec2Service service = liveService(mock(Ec2ContainerManager.class), resolver);
when(resolver.resolveImage("ami-src")).thenReturn(ResolvedAmiImage.minimal("guest:latest"));
Ec2Service service = liveService(capturingContainerManager(), resolver);
String instanceId = runOne(service, "ami-src");
String createdAmi = service.createImage("us-east-1", instanceId, "captured", null, true)
@@ -1097,7 +1099,7 @@ class Ec2ServiceTest {
when(resolver.resolveImage("ami-arm-source"))
.thenReturn(new ResolvedAmiImage("arm-image", ResolvedAmiImage.DEFAULT_RUNTIME, false,
"linux/arm64"));
Ec2Service service = liveService(mock(Ec2ContainerManager.class), resolver, catalog);
Ec2Service service = liveService(capturingContainerManager(), resolver, catalog);
Reservation sourceReservation = service.runInstances("us-east-1", "ami-arm-source", "t4g.medium",
1, 1, null, List.of(), null, null, List.of(), null, null);
@@ -1143,7 +1145,7 @@ class Ec2ServiceTest {
source.rootDeviceType = "ebs";
source.rootDeviceName = "/dev/xvda";
when(catalog.findByIdOrAlias("ami-src")).thenReturn(Optional.of(source));
Ec2Service service = liveService(mock(Ec2ContainerManager.class), mock(AmiImageResolver.class), catalog);
Ec2Service service = liveService(capturingContainerManager(), mock(AmiImageResolver.class), catalog);
String instanceId = runOne(service, "ami-src");
Image image = service.createImage("us-east-1", instanceId, "captured", null, true);
@@ -1167,7 +1169,7 @@ class Ec2ServiceTest {
@Test
void createImageTakesItsOwnSnapshotRatherThanTheSourceAmisOne() {
Ec2Service service = liveService(mock(Ec2ContainerManager.class), mock(AmiImageResolver.class));
Ec2Service service = liveService(capturingContainerManager(), mock(AmiImageResolver.class));
Image source = service.registerImage("us-east-1", "source-image", null, null, "/dev/sda1",
List.of(blockDeviceMapping("snap-source", 16)));
@@ -1269,6 +1271,19 @@ class Ec2ServiceTest {
}
/** mock=false so the container-manager and resolver interactions actually happen. */
/**
* A container manager whose commit succeeds. Outside mock mode CreateImage captures the
* source instance's file system and rejects the call when it cannot, so a bare mock (whose
* launch never gives the instance a container) would fail every CreateImage here for a
* reason none of these tests are about.
*/
private static Ec2ContainerManager capturingContainerManager() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.commitInstance(any(Instance.class), anyString()))
.thenReturn("floci-ami/test-capture:latest");
return containerManager;
}
private static Ec2Service liveService(Ec2ContainerManager containerManager, AmiImageResolver resolver) {
return liveService(containerManager, resolver, mock(Ec2ImageCatalog.class));
}