mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
ae580974cc
commit
a2285072c9
9 files changed
+1858
-116
No files matched your search
@@ -155,7 +155,8 @@ public class AwsQueryController {
|
||||
"DescribeSecurityGroupRules", "ModifySecurityGroupRules",
|
||||
"UpdateSecurityGroupRuleDescriptionsIngress", "UpdateSecurityGroupRuleDescriptionsEgress",
|
||||
"CreateKeyPair", "DescribeKeyPairs", "DeleteKeyPair", "ImportKeyPair",
|
||||
"DescribeImages", "RegisterImage", "DescribeSnapshots",
|
||||
"DescribeImages", "RegisterImage", "DeregisterImage", "CreateImage", "CopyImage",
|
||||
"DescribeSnapshots",
|
||||
"CreateTags", "DeleteTags", "DescribeTags",
|
||||
"CreateInternetGateway", "DescribeInternetGateways", "DeleteInternetGateway",
|
||||
"AttachInternetGateway", "DetachInternetGateway",
|
||||
|
||||
@@ -1099,6 +1099,76 @@ public class Ec2ContainerManager {
|
||||
return containerId != null && lifecycleManager.isContainerRunning(containerId);
|
||||
}
|
||||
|
||||
/** Signals that an instance's file system could not be captured as a Docker image. */
|
||||
public static class CaptureFailedException extends RuntimeException {
|
||||
public CaptureFailedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures an instance's file system as a new Docker image, so that an AMI created from it
|
||||
* carries what was provisioned rather than pointing back at the base image.
|
||||
*
|
||||
* <p>Returns the image reference, or null when the instance has no container to capture.
|
||||
* A commit that is attempted and fails throws instead of returning null: an AMI with no
|
||||
* captured file system launches its ancestor, so reporting the failure as "no capture" would
|
||||
* hand back an available AMI whose contents are silently not what was asked for.
|
||||
*
|
||||
* @param tag repository:tag to commit to, unique per AMI
|
||||
* @throws CaptureFailedException if the commit was attempted and did not succeed
|
||||
*/
|
||||
public String commitInstance(Instance instance, String tag) {
|
||||
String containerId = instance.getDockerContainerId();
|
||||
if (containerId == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// Committing a running container is what AWS does for CreateImage without
|
||||
// NoReboot; docker quiesces nothing either way, so the semantics match closely
|
||||
// enough. The container is left running -- CreateImage does not terminate its
|
||||
// source instance.
|
||||
String imageId = dockerClient.commitCmd(containerId)
|
||||
.withRepository(tag.contains(":") ? tag.substring(0, tag.indexOf(':')) : tag)
|
||||
.withTag(tag.contains(":") ? tag.substring(tag.indexOf(':') + 1) : "latest")
|
||||
.exec();
|
||||
LOG.infov("Captured EC2 instance {0} as Docker image {1} ({2})",
|
||||
instance.getInstanceId(), tag, imageId);
|
||||
return tag;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not capture EC2 instance {0} as an image: {1}",
|
||||
instance.getInstanceId(), e.getMessage());
|
||||
throw new CaptureFailedException("could not commit container " + containerId
|
||||
+ " of instance " + instance.getInstanceId() + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an image previously produced by {@link #commitInstance}. Called when the AMI that
|
||||
* owns it is deregistered, so captures do not accumulate on disk indefinitely.
|
||||
*
|
||||
* @return true when the layer is known to be gone, either removed now or already absent;
|
||||
* false when the daemon refused, in which case the caller must keep the reference
|
||||
* so the layer can still be found and removed later
|
||||
*/
|
||||
public boolean removeCommittedImage(String tag) {
|
||||
if (tag == null) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
dockerClient.removeImageCmd(tag).withForce(true).exec();
|
||||
LOG.infov("Removed captured Docker image {0}", tag);
|
||||
return true;
|
||||
} catch (NotFoundException e) {
|
||||
// Already gone: deregistering twice, or the daemon was pruned. Not an error.
|
||||
LOG.debugv("Captured Docker image {0} was already absent", tag);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not remove captured Docker image {0}: {1}", tag, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void injectSshKey(String containerId, String publicKey) {
|
||||
try {
|
||||
// Ensure .ssh directory exists with correct permissions
|
||||
|
||||
@@ -171,6 +171,8 @@ public class Ec2QueryHandler {
|
||||
case "DescribeImages" -> handleDescribeImages(params, region);
|
||||
case "CreateImage" -> handleCreateImage(params, region);
|
||||
case "RegisterImage" -> handleRegisterImage(params, region);
|
||||
case "DeregisterImage" -> handleDeregisterImage(params, region);
|
||||
case "CopyImage" -> handleCopyImage(params, region);
|
||||
case "DescribeSnapshots" -> handleDescribeSnapshots(params, region);
|
||||
// Tags
|
||||
case "CreateTags" -> handleCreateTags(params, region);
|
||||
@@ -3150,6 +3152,57 @@ public class Ec2QueryHandler {
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* DeregisterImage. The documented response is requestId plus {@code return} ("Returns true if
|
||||
* the request succeeds; otherwise, it returns an error"), with deleteSnapshotResultSet present
|
||||
* only when DeleteAssociatedSnapshots was requested.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeregisterImage.html">DeregisterImage</a>
|
||||
*/
|
||||
private Response handleDeregisterImage(MultivaluedMap<String, String> p, String region) {
|
||||
List<Ec2Service.SnapshotDeletion> deletions = service.deregisterImage(
|
||||
region,
|
||||
p.getFirst("ImageId"),
|
||||
Boolean.parseBoolean(p.getFirst("DeleteAssociatedSnapshots")));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DeregisterImageResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.elem("return", "true");
|
||||
if (!deletions.isEmpty()) {
|
||||
xml.start("deleteSnapshotResultSet");
|
||||
for (Ec2Service.SnapshotDeletion deletion : deletions) {
|
||||
xml.start("item")
|
||||
.elem("snapshotId", deletion.snapshotId())
|
||||
.elem("returnCode", deletion.returnCode())
|
||||
.end("item");
|
||||
}
|
||||
xml.end("deleteSnapshotResultSet");
|
||||
}
|
||||
xml.end("DeregisterImageResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* CopyImage. "The copy operation must be initiated in the destination Region", so the
|
||||
* request's own region is the destination and SourceRegion names where the source AMI lives.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopyImage.html">CopyImage</a>
|
||||
*/
|
||||
private Response handleCopyImage(MultivaluedMap<String, String> p, String region) {
|
||||
Image image = service.copyImage(
|
||||
region,
|
||||
p.getFirst("SourceRegion"),
|
||||
p.getFirst("SourceImageId"),
|
||||
p.getFirst("Name"),
|
||||
p.getFirst("Description"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CopyImageResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.elem("imageId", image.getImageId())
|
||||
.end("CopyImageResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleDescribeSnapshots(MultivaluedMap<String, String> p, String region) {
|
||||
List<String> ids = getList(p, "SnapshotId");
|
||||
List<String> owners = getList(p, "Owner", "OwnerId", "OwnerIds");
|
||||
|
||||
@@ -1150,6 +1150,39 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
private static final int LOCK_STRIPES = 512;
|
||||
private final Object[] resourceLocks = newLockStripes();
|
||||
|
||||
/** The AMI state a deregistered image is tombstoned with; one of EC2's documented ImageState values. */
|
||||
private static final String DEREGISTERED_STATE = "deregistered";
|
||||
|
||||
/**
|
||||
* Guards the registered-image set. The invariants here span the whole set rather than one
|
||||
* image, so no per-image stripe can express them, and each is decided by a scan that must not
|
||||
* observe a half-applied change from another caller:
|
||||
*
|
||||
* <ul>
|
||||
* <li>AMI names are unique per region, so registration is a scan-then-insert.</li>
|
||||
* <li>A snapshot is deleted on deregistration only when no other AMI references it, so
|
||||
* deletion is a scan-then-delete that must exclude a registration in flight.</li>
|
||||
* <li>A captured layer is released only when nothing can still launch from it, so the
|
||||
* decision and the removal must exclude a launch that has resolved the layer but has
|
||||
* not yet stored its instance.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>One monitor rather than a per-region one, because the last of those invariants is not
|
||||
* region-scoped: Docker image references are global to the daemon, so a copy of an AMI in
|
||||
* another region shares the layer with its source.
|
||||
*/
|
||||
private final Object imageRegistryLock = new Object();
|
||||
|
||||
/**
|
||||
* The monitor guarding the AMI registry against a launch and a deregistration interleaving.
|
||||
* Exposed package-private so a test can hold it and land a tombstone at a chosen point in a
|
||||
* launch, which is the only deterministic way to exercise that race. A method rather than a
|
||||
* field because the injected bean is a client proxy, through which a field read sees null.
|
||||
*/
|
||||
Object imageRegistryLock() {
|
||||
return imageRegistryLock;
|
||||
}
|
||||
|
||||
private static Object[] newLockStripes() {
|
||||
Object[] stripes = new Object[LOCK_STRIPES];
|
||||
for (int i = 0; i < stripes.length; i++) {
|
||||
@@ -2415,6 +2448,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
|
||||
}
|
||||
// "A deregistered AMI can't be used to launch new instances" (DeregisterImage). The
|
||||
// tombstone stays in the store so instances already launched from it keep resolving
|
||||
// their ancestry, so the launch path has to reject it explicitly.
|
||||
requireNotDeregistered(region, imageId);
|
||||
validateMetadataOptions(metadataOptions);
|
||||
LaunchTemplateData.MetadataOptions launchMetadataOptions = LaunchTemplateData.MetadataOptions.merge(
|
||||
LaunchTemplateData.MetadataOptions.launchDefaults(), metadataOptions);
|
||||
@@ -2487,118 +2524,149 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
validateArchitectureCompatibility(region, imageId, effectiveInstanceType);
|
||||
int count = Math.min(maxCount, Math.max(minCount, 1));
|
||||
String architecture = architectureFor(region, imageId, effectiveInstanceType);
|
||||
List<Instance> launched = new ArrayList<>();
|
||||
// Resolving the AMI, building the instances that depend on it and publishing them is one
|
||||
// step. A DeregisterImage releases the captured layer only when no live instance resolves
|
||||
// to it, so a launch that had resolved the layer but not yet stored its instance would
|
||||
// otherwise have that layer removed underneath it and start a container from a reference
|
||||
// that no longer exists. Re-checking the tombstone here is part of the same invariant: a
|
||||
// launch that loses the race must be rejected, not quietly demoted to the ancestor image.
|
||||
//
|
||||
// Everything the launch persists lives inside this block, because the check is only
|
||||
// meaningful if nothing has been written before it. A tombstone landing mid-launch used to
|
||||
// leave the rejected launch's root volumes, tags, subnet IP and caller-supplied ENI
|
||||
// attachment behind, since the reservation was never returned and nothing rolled them
|
||||
// back. Building under the lock costs nothing that rollback would not cost more: the work
|
||||
// is in-memory record construction, and the slow part, the container launch, still runs
|
||||
// outside.
|
||||
ResolvedAmiImage dockerImage = null;
|
||||
if (!config.services().ec2().mock()) {
|
||||
// A CreateImage AMI is not in the catalog, so resolve through its source.
|
||||
dockerImage = amiImageResolver.resolveImage(resolveLaunchableImageId(region, imageId));
|
||||
}
|
||||
for (int i = 0; i < count; i++) {
|
||||
String instanceId = "i-" + randomHex(17);
|
||||
String privateIp = suppliedEni != null
|
||||
? suppliedEni.getPrivateIpAddress()
|
||||
: assignPrivateIp(region, finalSubnetId);
|
||||
|
||||
Instance inst = new Instance();
|
||||
inst.setInstanceId(instanceId);
|
||||
inst.setImageId(imageId);
|
||||
inst.setState(InstanceState.pending());
|
||||
inst.setInstanceType(effectiveInstanceType);
|
||||
inst.setPlacement(new Placement(az));
|
||||
inst.setSubnetId(finalSubnetId);
|
||||
inst.setVpcId(vpcId);
|
||||
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
|
||||
// override wins in both directions; the subnet's MapPublicIpOnLaunch
|
||||
// attribute is only the default when the launch does not specify it.
|
||||
inst.setAssociatePublicIp(associatePublicIp != null
|
||||
? associatePublicIp
|
||||
: subnet != null && subnet.isMapPublicIpOnLaunch());
|
||||
inst.setPrivateIpAddress(privateIp);
|
||||
inst.setPrivateDnsName("ip-" + privateIp.replace('.', '-') + ".ec2.internal");
|
||||
inst.setKeyName(keyName);
|
||||
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
|
||||
inst.setArchitecture(architecture);
|
||||
inst.setLaunchTime(Instant.now());
|
||||
inst.setAmiLaunchIndex(i);
|
||||
inst.setClientToken(clientToken);
|
||||
inst.setRegion(region);
|
||||
inst.setUserData(userData);
|
||||
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
inst.setTags(new ArrayList<>(instanceTags));
|
||||
tags.put(instanceId, new ArrayList<>(instanceTags));
|
||||
}
|
||||
|
||||
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
|
||||
// floci-kt9) or a freshly-minted implicit primary interface.
|
||||
InstanceNetworkInterface eni = new InstanceNetworkInterface();
|
||||
eni.setNetworkInterfaceId(suppliedEni != null ? suppliedEni.getNetworkInterfaceId() : "eni-" + randomHex(17));
|
||||
eni.setSubnetId(finalSubnetId);
|
||||
eni.setVpcId(vpcId);
|
||||
eni.setOwnerId(accountId);
|
||||
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
|
||||
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
|
||||
eni.setPrivateIpAddress(privateIp);
|
||||
eni.setPrivateDnsName(inst.getPrivateDnsName());
|
||||
eni.setGroups(new ArrayList<>(sgIdentifiers));
|
||||
eni.setAttachmentId("eni-attach-" + randomHex(17));
|
||||
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
|
||||
if (inst.getLaunchTime() != null) {
|
||||
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
|
||||
}
|
||||
inst.getNetworkInterfaces().add(eni);
|
||||
if (suppliedEni != null) {
|
||||
// The standalone record stays authoritative rather than being folded into the
|
||||
// instance: AWS defaults deleteOnTermination to false for an interface the caller
|
||||
// created and handed to a launch, so it outlives the instance and returns to
|
||||
// "available" on termination instead of vanishing with it. Double-counting is
|
||||
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
|
||||
// id the standalone store owns.
|
||||
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
|
||||
launchAttachment.setAttachmentId(eni.getAttachmentId());
|
||||
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
|
||||
launchAttachment.setStatus("attached");
|
||||
launchAttachment.setInstanceId(instanceId);
|
||||
launchAttachment.setInstanceOwnerId(accountId);
|
||||
launchAttachment.setAttachTime(eni.getAttachTime());
|
||||
launchAttachment.setDeleteOnTermination(false);
|
||||
suppliedEni.setAttachment(launchAttachment);
|
||||
suppliedEni.setStatus("in-use");
|
||||
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
|
||||
}
|
||||
|
||||
// Root EBS volume
|
||||
String rootVolId = "vol-" + randomHex(17);
|
||||
inst.setRootVolumeId(rootVolId);
|
||||
Volume rootVol = new Volume();
|
||||
rootVol.setVolumeId(rootVolId);
|
||||
rootVol.setAvailabilityZone(az);
|
||||
rootVol.setVolumeType(DEFAULT_ROOT_VOLUME_TYPE);
|
||||
rootVol.setSize(DEFAULT_ROOT_VOLUME_SIZE_GIB);
|
||||
rootVol.setState("in-use");
|
||||
rootVol.setRegion(region);
|
||||
rootVol.setCreateTime(Instant.now());
|
||||
VolumeAttachment att = new VolumeAttachment();
|
||||
att.setVolumeId(rootVolId);
|
||||
att.setInstanceId(instanceId);
|
||||
att.setDevice(inst.getRootDeviceName());
|
||||
att.setState("attached");
|
||||
att.setDeleteOnTermination(true);
|
||||
att.setAttachTime(Instant.now());
|
||||
rootVol.getAttachments().add(att);
|
||||
volumes.put(key(region, rootVolId), rootVol);
|
||||
|
||||
instances.put(key(region, instanceId), inst);
|
||||
reservation.getInstances().add(inst);
|
||||
|
||||
synchronized (imageRegistryLock) {
|
||||
requireNotDeregistered(region, imageId);
|
||||
if (!config.services().ec2().mock()) {
|
||||
String publicKey = null;
|
||||
if (keyName != null) {
|
||||
KeyPair kp = findKeyPair(region, keyName);
|
||||
if (kp != null) {
|
||||
publicKey = kp.getPublicKey();
|
||||
}
|
||||
// A CreateImage AMI is not in the catalog, so resolve through its source. The
|
||||
// ancestor supplies the guest runtime (systemd vs minimal, cloud-init), which a
|
||||
// committed layer does not change; the captured file system, when there is one,
|
||||
// then replaces the image to actually run.
|
||||
dockerImage = amiImageResolver.resolveImage(resolveLaunchableImageId(region, imageId));
|
||||
String captured = capturedImageFor(region, imageId);
|
||||
if (captured != null) {
|
||||
dockerImage = new ResolvedAmiImage(captured, dockerImage.guestRuntime(),
|
||||
dockerImage.cloudInit(), dockerImage.dockerPlatform());
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < count; i++) {
|
||||
String instanceId = "i-" + randomHex(17);
|
||||
String privateIp = suppliedEni != null
|
||||
? suppliedEni.getPrivateIpAddress()
|
||||
: assignPrivateIp(region, finalSubnetId);
|
||||
|
||||
Instance inst = new Instance();
|
||||
inst.setInstanceId(instanceId);
|
||||
inst.setImageId(imageId);
|
||||
inst.setState(InstanceState.pending());
|
||||
inst.setInstanceType(effectiveInstanceType);
|
||||
inst.setPlacement(new Placement(az));
|
||||
inst.setSubnetId(finalSubnetId);
|
||||
inst.setVpcId(vpcId);
|
||||
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
|
||||
// override wins in both directions; the subnet's MapPublicIpOnLaunch
|
||||
// attribute is only the default when the launch does not specify it.
|
||||
inst.setAssociatePublicIp(associatePublicIp != null
|
||||
? associatePublicIp
|
||||
: subnet != null && subnet.isMapPublicIpOnLaunch());
|
||||
inst.setPrivateIpAddress(privateIp);
|
||||
inst.setPrivateDnsName("ip-" + privateIp.replace('.', '-') + ".ec2.internal");
|
||||
inst.setKeyName(keyName);
|
||||
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
|
||||
inst.setArchitecture(architecture);
|
||||
inst.setLaunchTime(Instant.now());
|
||||
inst.setAmiLaunchIndex(i);
|
||||
inst.setClientToken(clientToken);
|
||||
inst.setRegion(region);
|
||||
inst.setUserData(userData);
|
||||
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
inst.setTags(new ArrayList<>(instanceTags));
|
||||
tags.put(instanceId, new ArrayList<>(instanceTags));
|
||||
}
|
||||
|
||||
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
|
||||
// floci-kt9) or a freshly-minted implicit primary interface.
|
||||
InstanceNetworkInterface eni = new InstanceNetworkInterface();
|
||||
eni.setNetworkInterfaceId(suppliedEni != null ? suppliedEni.getNetworkInterfaceId() : "eni-" + randomHex(17));
|
||||
eni.setSubnetId(finalSubnetId);
|
||||
eni.setVpcId(vpcId);
|
||||
eni.setOwnerId(accountId);
|
||||
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
|
||||
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
|
||||
eni.setPrivateIpAddress(privateIp);
|
||||
eni.setPrivateDnsName(inst.getPrivateDnsName());
|
||||
eni.setGroups(new ArrayList<>(sgIdentifiers));
|
||||
eni.setAttachmentId("eni-attach-" + randomHex(17));
|
||||
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
|
||||
if (inst.getLaunchTime() != null) {
|
||||
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
|
||||
}
|
||||
inst.getNetworkInterfaces().add(eni);
|
||||
if (suppliedEni != null) {
|
||||
// The standalone record stays authoritative rather than being folded into the
|
||||
// instance: AWS defaults deleteOnTermination to false for an interface the caller
|
||||
// created and handed to a launch, so it outlives the instance and returns to
|
||||
// "available" on termination instead of vanishing with it. Double-counting is
|
||||
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
|
||||
// id the standalone store owns.
|
||||
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
|
||||
launchAttachment.setAttachmentId(eni.getAttachmentId());
|
||||
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
|
||||
launchAttachment.setStatus("attached");
|
||||
launchAttachment.setInstanceId(instanceId);
|
||||
launchAttachment.setInstanceOwnerId(accountId);
|
||||
launchAttachment.setAttachTime(eni.getAttachTime());
|
||||
launchAttachment.setDeleteOnTermination(false);
|
||||
suppliedEni.setAttachment(launchAttachment);
|
||||
suppliedEni.setStatus("in-use");
|
||||
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
|
||||
}
|
||||
|
||||
// Root EBS volume
|
||||
String rootVolId = "vol-" + randomHex(17);
|
||||
inst.setRootVolumeId(rootVolId);
|
||||
Volume rootVol = new Volume();
|
||||
rootVol.setVolumeId(rootVolId);
|
||||
rootVol.setAvailabilityZone(az);
|
||||
rootVol.setVolumeType(DEFAULT_ROOT_VOLUME_TYPE);
|
||||
rootVol.setSize(DEFAULT_ROOT_VOLUME_SIZE_GIB);
|
||||
rootVol.setState("in-use");
|
||||
rootVol.setRegion(region);
|
||||
rootVol.setCreateTime(Instant.now());
|
||||
VolumeAttachment att = new VolumeAttachment();
|
||||
att.setVolumeId(rootVolId);
|
||||
att.setInstanceId(instanceId);
|
||||
att.setDevice(inst.getRootDeviceName());
|
||||
att.setState("attached");
|
||||
att.setDeleteOnTermination(true);
|
||||
att.setAttachTime(Instant.now());
|
||||
rootVol.getAttachments().add(att);
|
||||
volumes.put(key(region, rootVolId), rootVol);
|
||||
|
||||
instances.put(key(region, instanceId), inst);
|
||||
launched.add(inst);
|
||||
reservation.getInstances().add(inst);
|
||||
}
|
||||
}
|
||||
|
||||
// Outside the lock: the containers are what the lock protects a reference to, not part of
|
||||
// the registry, and a launch is slow.
|
||||
if (!config.services().ec2().mock()) {
|
||||
String publicKey = null;
|
||||
if (keyName != null) {
|
||||
KeyPair kp = findKeyPair(region, keyName);
|
||||
if (kp != null) {
|
||||
publicKey = kp.getPublicKey();
|
||||
}
|
||||
}
|
||||
for (Instance inst : launched) {
|
||||
containerManager.launch(inst, dockerImage, publicKey, region, desiredPublishedPorts(region, inst));
|
||||
}
|
||||
}
|
||||
@@ -2842,6 +2910,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
}
|
||||
releaseStandaloneInterfacesOnTermination(region, inst);
|
||||
instances.put(key(region, id), inst);
|
||||
// The last instance depending on a deregistered AMI's capture has just gone away.
|
||||
reclaimCapturesPinnedBy(region, inst);
|
||||
Map<String, String> entry = new LinkedHashMap<>();
|
||||
entry.put("instanceId", id);
|
||||
entry.put("previousState", prev.getName());
|
||||
@@ -4217,6 +4287,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
.collect(Collectors.toList());
|
||||
List<Image> createdImages = registeredImages.scan(k -> true).stream()
|
||||
.filter(img -> region.equals(img.getRegion()))
|
||||
// A deregistered AMI is retained only as a tombstone, so that ancestry and
|
||||
// repeat-deregistration still resolve; DescribeImages must not report it.
|
||||
.filter(img -> !DEREGISTERED_STATE.equals(img.getState()))
|
||||
.filter(img -> matchesImageIds(img, imageIds))
|
||||
.filter(img -> matchesImageOwners(img, owners))
|
||||
.filter(img -> matchesRegisteredImageFilters(img, filters))
|
||||
@@ -4287,12 +4360,61 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
captureBlockDeviceMappings(region, source, sourceImage));
|
||||
|
||||
// Carry the launchable ancestor so RunInstances on this AMI starts the same guest instead
|
||||
// of falling through to the catalog default.
|
||||
// of falling through to the catalog default. This is also the fallback when the file
|
||||
// system cannot be captured below.
|
||||
image.setSourceImageId(resolveLaunchableImageId(region, source.getImageId()));
|
||||
|
||||
// Capture the instance's file system. Without this the AMI is a metadata record that
|
||||
// launches the *base* image, so everything provisioned on the source instance is
|
||||
// silently discarded -- a Packer build reports success and produces an empty artifact.
|
||||
//
|
||||
// A capture that cannot be made fails the call rather than producing an AMI that reports
|
||||
// itself available and boots the ancestor: Floci commits inline, so there is no later
|
||||
// state transition a caller could observe, and an accepted-but-empty AMI is the exact
|
||||
// silent wrongness this capture exists to remove. The half-built AMI is dropped first, so
|
||||
// a retry is not met with InvalidAMIName.Duplicate against a record nobody can see.
|
||||
if (!config.services().ec2().mock()) {
|
||||
image.setDockerImage(captureFileSystem(region, source, image));
|
||||
}
|
||||
|
||||
registeredImages.put(key(region, image.getImageId()), image);
|
||||
return image;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits the source instance's container for a CreateImage, discarding the AMI record and
|
||||
* failing the call if it cannot be done.
|
||||
*/
|
||||
private String captureFileSystem(String region, Instance source, Image image) {
|
||||
String captured;
|
||||
try {
|
||||
captured = containerManager.commitInstance(source, committedImageTag(image.getImageId()));
|
||||
} catch (Ec2ContainerManager.CaptureFailedException e) {
|
||||
registeredImages.delete(key(region, image.getImageId()));
|
||||
throw new AwsException("InternalError", "Could not create image '" + image.getName()
|
||||
+ "' from instance " + source.getInstanceId()
|
||||
+ ": capturing its file system failed (" + e.getMessage() + ")", 500);
|
||||
}
|
||||
if (captured == null) {
|
||||
// No container: the instance never launched one, or its launch has not got that far.
|
||||
// AWS requires a running or stopped instance for CreateImage and reports anything
|
||||
// else as IncorrectInstanceState, which is the same condition seen from here.
|
||||
registeredImages.delete(key(region, image.getImageId()));
|
||||
throw new AwsException("IncorrectInstanceState", "The instance '"
|
||||
+ source.getInstanceId() + "' is not in a state from which an image can be"
|
||||
+ " created: it has no running container to capture", 400);
|
||||
}
|
||||
return captured;
|
||||
}
|
||||
|
||||
/**
|
||||
* Docker reference for an AMI's captured file system. Keyed by AMI id so it is unique, and
|
||||
* namespaced so these are distinguishable from images Floci did not create.
|
||||
*/
|
||||
static String committedImageTag(String imageId) {
|
||||
return "floci-ami/" + imageId + ":latest";
|
||||
}
|
||||
|
||||
/**
|
||||
* The devices the captured AMI reports. AWS captures what the source AMI describes plus any
|
||||
* volume attached to the instance afterwards, so a data volume added post-launch is part of
|
||||
@@ -4398,6 +4520,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The captured file system to launch for an AMI, following the CreateImage chain so an image
|
||||
* captured from an instance that was itself launched from a capture still resolves. Null when
|
||||
* no ancestor in the chain was ever captured, which is the case for catalog and
|
||||
* RegisterImage AMIs.
|
||||
*/
|
||||
private String capturedImageFor(String region, String imageId) {
|
||||
String current = imageId;
|
||||
for (int hops = 0; hops < 16 && current != null; hops++) {
|
||||
Image registered = registeredImages.get(key(region, current)).orElse(null);
|
||||
if (registered == null) {
|
||||
return null;
|
||||
}
|
||||
if (registered.getDockerImage() != null) {
|
||||
return registered.getDockerImage();
|
||||
}
|
||||
current = registered.getSourceImageId();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows CreateImage ancestry back to an id the AMI resolver can map to a guest image.
|
||||
* Images from RegisterImage have no source and stop the walk, as does a catalog id.
|
||||
@@ -4419,8 +4562,26 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter Name", 400);
|
||||
}
|
||||
// The duplicate-name check is a read-modify-write over the whole image store, so two
|
||||
// registrations of the same name racing each other would both see no duplicate and both
|
||||
// insert. Registration also publishes this image's snapshot references, which is what
|
||||
// DeregisterImage scans before deleting a snapshot; both run under the registry lock so
|
||||
// a registration cannot slip between that scan and the delete.
|
||||
synchronized (imageRegistryLock) {
|
||||
return registerImageLocked(region, name, description, architecture, rootDeviceName,
|
||||
blockDeviceMappings);
|
||||
}
|
||||
}
|
||||
|
||||
private Image registerImageLocked(String region, String name, String description, String architecture,
|
||||
String rootDeviceName, List<BlockDeviceMapping> blockDeviceMappings) {
|
||||
boolean duplicateName = registeredImages.scan(k -> true).stream()
|
||||
.filter(img -> region.equals(img.getRegion()))
|
||||
// A deregistered AMI no longer holds its name: "If you have recently deregistered
|
||||
// an AMI with the same name, allow enough time for the change to propagate"
|
||||
// (InvalidAMIName.Duplicate). Floci has no propagation delay, so the name is free
|
||||
// immediately -- which is what Packer's force_deregister then rebuild relies on.
|
||||
.filter(img -> !DEREGISTERED_STATE.equals(img.getState()))
|
||||
.anyMatch(img -> name.equals(img.getName()));
|
||||
if (duplicateName) {
|
||||
throw new AwsException("InvalidAMIName.Duplicate",
|
||||
@@ -4454,6 +4615,246 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
return image;
|
||||
}
|
||||
|
||||
/**
|
||||
* DeregisterImage. AWS: "Deregisters the specified AMI. A deregistered AMI can't be used to
|
||||
* launch new instances", and explicitly does not delete "Instances already launched from the
|
||||
* AMI". The image is therefore tombstoned with the AMI state {@code deregistered} rather than
|
||||
* dropped from the store: DescribeImages stops reporting it and its name is released, while
|
||||
* an instance launched from it keeps resolving its ancestry to a guest image (so a stop/start
|
||||
* still comes back on the right image) and a second deregistration can be told apart from a
|
||||
* never-existed id.
|
||||
*
|
||||
* <p>Snapshots are kept by default -- "Default: The snapshots are not deleted" -- and deleted
|
||||
* only when {@code DeleteAssociatedSnapshots} is set, minus any snapshot still referenced by
|
||||
* another AMI: "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."
|
||||
*
|
||||
* @return the per-snapshot deletion results, empty when deletion was not requested
|
||||
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeregisterImage.html">DeregisterImage</a>
|
||||
*/
|
||||
public List<SnapshotDeletion> deregisterImage(String region, String imageId,
|
||||
boolean deleteAssociatedSnapshots) {
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
|
||||
}
|
||||
synchronized (imageRegistryLock) {
|
||||
Image image = registeredImages.get(key(region, imageId)).orElse(null);
|
||||
if (image == null) {
|
||||
// A catalog AMI is owned by amazon, not by the caller. AWS reports an attempt to
|
||||
// act on someone else's AMI as AuthFailure ("trying to use an AMI for which you do
|
||||
// not have permissions"), not as a missing image.
|
||||
if (imageCatalog.findByIdOrAlias(imageId).isPresent()) {
|
||||
throw new AwsException("AuthFailure",
|
||||
"Not authorized for images: [" + imageId + "]", 400);
|
||||
}
|
||||
throw new AwsException("InvalidAMIID.NotFound",
|
||||
"The image id '[" + imageId + "]' does not exist", 400);
|
||||
}
|
||||
if (DEREGISTERED_STATE.equals(image.getState())) {
|
||||
throw new AwsException("InvalidAMIID.Unavailable",
|
||||
"The image id '[" + imageId + "]' has been deregistered and is no longer available", 400);
|
||||
}
|
||||
image.setState(DEREGISTERED_STATE);
|
||||
reclaimCapturedImage(image, null);
|
||||
registeredImages.put(key(region, imageId), image);
|
||||
return deleteAssociatedSnapshots ? deleteSnapshotsOf(region, image) : List.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the Docker image holding a deregistered AMI's captured file system, so repeated
|
||||
* builds of the same AMI name do not accumulate one committed layer each.
|
||||
*
|
||||
* <p>Skipped while any live instance still resolves to that capture, and while any other AMI
|
||||
* still carries the same reference (a CopyImage of a captured AMI shares the layer with its
|
||||
* source). AWS keeps instances launched from a deregistered AMI running and lets them stop
|
||||
* and start again, so the layer has to outlive the AMI record whenever something can still
|
||||
* boot from it. The tombstone keeps its dockerImage in that case, and the capture is simply
|
||||
* not reclaimed -- correctness before disk.
|
||||
*
|
||||
* <p>Both scans cross regions, because a Docker reference is global to the daemon: an AMI
|
||||
* copied to another region, and instances launched from that copy, share this layer.
|
||||
*
|
||||
* <p>Callers must hold {@link #imageRegistryLock}.
|
||||
*
|
||||
* @param excludedInstanceId an instance not to count as a live dependant, used by the
|
||||
* terminate path where the store still reads the instance as
|
||||
* running while its container is being torn down; null to count
|
||||
* every live instance
|
||||
* @return true when the reference was released, so the caller knows to store the change
|
||||
*/
|
||||
private boolean reclaimCapturedImage(Image image, String excludedInstanceId) {
|
||||
String captured = image.getDockerImage();
|
||||
if (captured == null || config.services().ec2().mock()) {
|
||||
return false;
|
||||
}
|
||||
boolean sharedWithAnotherImage = registeredImages.scan(k -> true).stream()
|
||||
.filter(other -> !image.getImageId().equals(other.getImageId()))
|
||||
.filter(other -> !DEREGISTERED_STATE.equals(other.getState()))
|
||||
.anyMatch(other -> captured.equals(other.getDockerImage()));
|
||||
if (sharedWithAnotherImage) {
|
||||
LOG.infov("Keeping captured image {0}: another AMI still carries it", captured);
|
||||
return false;
|
||||
}
|
||||
boolean stillLaunchable = instances.scan(i -> true).stream()
|
||||
.filter(i -> i.getRegion() != null && !i.getInstanceId().equals(excludedInstanceId))
|
||||
.filter(i -> i.getState() != null && !"terminated".equals(i.getState().getName()))
|
||||
.anyMatch(i -> captured.equals(capturedImageFor(i.getRegion(), i.getImageId())));
|
||||
if (stillLaunchable) {
|
||||
LOG.infov("Keeping captured image {0}: an instance can still be launched from it", captured);
|
||||
return false;
|
||||
}
|
||||
// Only forget the reference once the layer is actually gone. Deregistration is rejected
|
||||
// the second time and nothing else can rediscover the tag, so clearing it after a failed
|
||||
// removal would leak the layer for the lifetime of the emulator.
|
||||
if (!containerManager.removeCommittedImage(captured)) {
|
||||
return false;
|
||||
}
|
||||
image.setDockerImage(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a capture once the instance that was pinning it goes away. Deregistration is the
|
||||
* only other place this runs and it is rejected the second time, so without this a capture
|
||||
* retained for a live instance would never be reclaimed at all.
|
||||
*
|
||||
* <p>Only tombstoned AMIs are considered: while the AMI is still registered its capture is
|
||||
* needed for the next launch.
|
||||
*/
|
||||
private void reclaimCapturesPinnedBy(String region, Instance terminated) {
|
||||
if (config.services().ec2().mock()) {
|
||||
return;
|
||||
}
|
||||
String captured = capturedImageFor(region, terminated.getImageId());
|
||||
if (captured == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (imageRegistryLock) {
|
||||
Image holder = registeredImages.scan(k -> true).stream()
|
||||
.filter(img -> captured.equals(img.getDockerImage()))
|
||||
.filter(img -> DEREGISTERED_STATE.equals(img.getState()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (holder != null && reclaimCapturedImage(holder, terminated.getInstanceId())) {
|
||||
registeredImages.put(key(holder.getRegion(), holder.getImageId()), holder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The deletion outcome DeregisterImage reports for one of the AMI's backing snapshots. */
|
||||
public record SnapshotDeletion(String snapshotId, String returnCode) {}
|
||||
|
||||
private List<SnapshotDeletion> deleteSnapshotsOf(String region, Image image) {
|
||||
List<SnapshotDeletion> results = new ArrayList<>();
|
||||
for (BlockDeviceMapping mapping : image.getBlockDeviceMappings()) {
|
||||
EbsBlockDevice ebs = mapping.getEbs();
|
||||
if (ebs == null || ebs.getSnapshotId() == null) {
|
||||
continue;
|
||||
}
|
||||
String snapshotId = ebs.getSnapshotId();
|
||||
if (snapshotIsSharedWithAnotherImage(region, image.getImageId(), snapshotId)) {
|
||||
results.add(new SnapshotDeletion(snapshotId, "skipped"));
|
||||
continue;
|
||||
}
|
||||
snapshots.delete(key(region, snapshotId));
|
||||
results.add(new SnapshotDeletion(snapshotId, "success"));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private boolean snapshotIsSharedWithAnotherImage(String region, String imageId, String snapshotId) {
|
||||
return registeredImages.scan(k -> true).stream()
|
||||
.filter(other -> region.equals(other.getRegion()))
|
||||
.filter(other -> !imageId.equals(other.getImageId()))
|
||||
.filter(other -> !DEREGISTERED_STATE.equals(other.getState()))
|
||||
.flatMap(other -> other.getBlockDeviceMappings().stream())
|
||||
.map(BlockDeviceMapping::getEbs)
|
||||
.filter(Objects::nonNull)
|
||||
.anyMatch(ebs -> snapshotId.equals(ebs.getSnapshotId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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" -- so {@code destinationRegion} is the request's own region and only the source
|
||||
* is looked up under {@code SourceRegion}. The result is an independent AMI: its own id, its
|
||||
* own snapshots, owned by the caller.
|
||||
*
|
||||
* <p>State: AWS reports the new AMI as {@code pending} until the backing snapshots finish
|
||||
* copying. Floci's store is in-memory and the copy completes within the call, so the copy is
|
||||
* {@code available} immediately, consistent with what CreateImage and RegisterImage already
|
||||
* report. A caller that waits for {@code available} therefore returns on its first poll.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopyImage.html">CopyImage</a>
|
||||
*/
|
||||
public Image copyImage(String destinationRegion, String sourceRegion, String sourceImageId,
|
||||
String name, String description) {
|
||||
if (sourceImageId == null || sourceImageId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter SourceImageId", 400);
|
||||
}
|
||||
if (sourceRegion == null || sourceRegion.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter SourceRegion", 400);
|
||||
}
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter Name", 400);
|
||||
}
|
||||
|
||||
// Resolving the source, reading its capture and publishing the copy happen under one
|
||||
// lock, so a DeregisterImage of the source cannot reclaim the captured layer in between
|
||||
// and leave the copy pointing at a Docker reference that no longer exists.
|
||||
synchronized (imageRegistryLock) {
|
||||
// Registered AMIs are keyed by (region, id) and are visible only in their own region,
|
||||
// so the source is resolved against SourceRegion rather than the request's region.
|
||||
// Catalog AMIs are region-independent in Floci and so resolve from either side.
|
||||
Image source = registeredImages.get(key(sourceRegion, sourceImageId)).orElse(null);
|
||||
if (source != null && DEREGISTERED_STATE.equals(source.getState())) {
|
||||
throw new AwsException("InvalidAMIID.Unavailable",
|
||||
"The image id '[" + sourceImageId + "]' has been deregistered and is no longer available", 400);
|
||||
}
|
||||
if (source == null) {
|
||||
source = imageCatalog.findByIdOrAlias(sourceImageId)
|
||||
.map(Ec2ImageCatalog.CatalogImage::toImage)
|
||||
.orElse(null);
|
||||
}
|
||||
if (source == null) {
|
||||
throw new AwsException("InvalidAMIID.NotFound",
|
||||
"The image id '[" + sourceImageId + "]' does not exist in region " + sourceRegion, 400);
|
||||
}
|
||||
|
||||
// Fresh snapshot ids: two AMIs sharing one snapshot would make deleting either appear
|
||||
// to take the other's backing with it, and the copy's snapshots live in the
|
||||
// destination region anyway.
|
||||
Image copy = registerImage(destinationRegion, name, description, source.getArchitecture(),
|
||||
source.getRootDeviceName(), sourceImageMappings(source));
|
||||
copy.setVirtualizationType(source.getVirtualizationType());
|
||||
copy.setRootDeviceType(source.getRootDeviceType());
|
||||
copy.setPlatform(source.getPlatform());
|
||||
// The launchable ancestor is resolved in the SOURCE region, since that is where the
|
||||
// chain of CreateImage parents lives; it bottoms out at a catalog id, which is
|
||||
// region-agnostic.
|
||||
copy.setSourceImageId(resolveLaunchableImageId(sourceRegion, sourceImageId));
|
||||
// The captured file system is the point of a CreateImage AMI, and the ancestry the
|
||||
// copy inherits does not carry it: sourceImageId is flattened to a launchable catalog
|
||||
// id, and the chain in between lives in the source region where the copy cannot see
|
||||
// it. Without this the copy launches the base image, which is the same silent
|
||||
// emptiness CreateImage itself used to produce. The layer is shared rather than
|
||||
// duplicated; reclamation accounts for that.
|
||||
copy.setDockerImage(capturedImageFor(sourceRegion, sourceImageId));
|
||||
registeredImages.put(key(destinationRegion, copy.getImageId()), copy);
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects an AMI id that has been deregistered; unknown ids fall through to the resolver. */
|
||||
private void requireNotDeregistered(String region, String imageId) {
|
||||
Image image = registeredImages.get(key(region, imageId)).orElse(null);
|
||||
if (image != null && DEREGISTERED_STATE.equals(image.getState())) {
|
||||
throw new AwsException("InvalidAMIID.Unavailable",
|
||||
"The image id '[" + imageId + "]' has been deregistered and is no longer available", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Snapshot> describeSnapshots(String region, List<String> snapshotIds,
|
||||
List<String> ownerIds, Map<String, List<String>> filters) {
|
||||
if (snapshotIds != null && !snapshotIds.isEmpty()) {
|
||||
|
||||
@@ -31,6 +31,15 @@ public class Image {
|
||||
* not in the catalog and would otherwise fall back to the default guest.
|
||||
*/
|
||||
private String sourceImageId;
|
||||
|
||||
/**
|
||||
* For images produced by CreateImage: the Docker image the source container was committed
|
||||
* to, which is what actually captures the instance's file system. Not an EC2 field. Null
|
||||
* when no capture could be made (mock mode, or an instance with no container), in which
|
||||
* case launching falls back to {@link #sourceImageId} and the AMI is only a metadata
|
||||
* record of its ancestor.
|
||||
*/
|
||||
private String dockerImage;
|
||||
private List<BlockDeviceMapping> blockDeviceMappings = new ArrayList<>();
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
|
||||
@@ -84,6 +93,9 @@ public class Image {
|
||||
public String getSourceImageId() { return sourceImageId; }
|
||||
public void setSourceImageId(String sourceImageId) { this.sourceImageId = sourceImageId; }
|
||||
|
||||
public String getDockerImage() { return dockerImage; }
|
||||
public void setDockerImage(String dockerImage) { this.dockerImage = dockerImage; }
|
||||
|
||||
public List<BlockDeviceMapping> getBlockDeviceMappings() { return blockDeviceMappings; }
|
||||
public void setBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) { this.blockDeviceMappings = blockDeviceMappings; }
|
||||
|
||||
|
||||
+400
@@ -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"));
|
||||
}
|
||||
}
|
||||
+613
@@ -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));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user