diff --git a/docs/services/ec2.md b/docs/services/ec2.md index d3a0ccab09..24f72bfe13 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1297,6 +1297,11 @@ Validation matches AWS behavior: | Action | Description | |--------|-------------| | DescribeSnapshots | Lists or returns stored snapshots, filterable by id and owner. | +| CreateSnapshot | Snapshots a volume. The snapshot takes the volume's size and encryption, is owned by the caller and accepts `snapshot` tags from `TagSpecification`. | +| DeleteSnapshot | Deletes a snapshot and its tags. A snapshot a registered AMI still uses fails with `InvalidSnapshot.InUse`. | +| CopySnapshot | Copies a snapshot from `SourceRegion` into the request's region as a new snapshot the caller owns. | + +`CreateSnapshot` answers `pending`, as AWS does, and the copy completes within the call, so `DescribeSnapshots` reports the snapshot `completed` on the first poll. Snapshots hold no volume data: a volume created from one gets its size and encryption, not its contents. A copy reports `vol-ffffffff` as its volume, stays encrypted when its source is, and is encrypted when `Encrypted=true` or the destination region's encryption by default says so. The source's tags are not copied. All three actions honor `DryRun`: a request the real call would refuse keeps that error, and one that would succeed returns `DryRunOperation` and changes nothing. ### Flow Logs diff --git a/docs/services/index.md b/docs/services/index.md index 3c946ce967..11e24e5dd3 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -89,7 +89,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | | [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 | | [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 | -| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 225 | +| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 228 | | [EC2 Instance Connect](ec2-instance-connect.md) | `POST /` + `X-Amz-Target: AWSEC2InstanceConnectService.*` | JSON 1.1 | 2 | | [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions | | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 | diff --git a/src/main/java/io/floci/aws/core/common/AwsQueryController.java b/src/main/java/io/floci/aws/core/common/AwsQueryController.java index 20caeef483..00df07d098 100644 --- a/src/main/java/io/floci/aws/core/common/AwsQueryController.java +++ b/src/main/java/io/floci/aws/core/common/AwsQueryController.java @@ -513,6 +513,8 @@ public class AwsQueryController { Map.entry("DescribeEventCategories", "redshift"), Map.entry("DescribeAccountAttributes", "ec2"), Map.entry("DescribeSnapshots", "ec2"), + // ElastiCache defines it too, but Floci's ElastiCache does not serve it. + Map.entry("CopySnapshot", "ec2"), Map.entry("DescribeAccountLimits", "elasticloadbalancing"), Map.entry("CreateIntegration", "redshift"), Map.entry("DeleteIntegration", "redshift"), diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index 6beeaa0486..4bec25efdf 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -264,6 +264,9 @@ public class Ec2QueryHandler { case "DeregisterImage" -> handleDeregisterImage(params, region); case "CopyImage" -> handleCopyImage(params, region); case "DescribeSnapshots" -> handleDescribeSnapshots(params, region); + case "CreateSnapshot" -> handleCreateSnapshot(params, region); + case "DeleteSnapshot" -> handleDeleteSnapshot(params, region); + case "CopySnapshot" -> handleCopySnapshot(params, region); // Tags case "CreateTags" -> handleCreateTags(params, region); case "DeleteTags" -> handleDeleteTags(params, region); @@ -4217,6 +4220,42 @@ public class Ec2QueryHandler { return xmlResponse(xml.build()); } + /** + * CreateSnapshot. The response reports {@code pending} with no progress yet, as AWS does for + * a snapshot it has just started; DescribeSnapshots then reports it {@code completed}. + */ + private Response handleCreateSnapshot(MultivaluedMap p, String region) { + List snapshotTags = parseTagsForResource(p, "snapshot", Set.of("snapshot")); + Snapshot snapshot = service.createSnapshot(region, p.getFirst("VolumeId"), + p.getFirst("Description"), snapshotTags, dryRun(p)); + XmlBuilder xml = new XmlBuilder() + .start("CreateSnapshotResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .raw(snapshotXml(snapshot, "pending", "")) + .end("CreateSnapshotResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDeleteSnapshot(MultivaluedMap p, String region) { + service.deleteSnapshot(region, p.getFirst("SnapshotId"), dryRun(p)); + return booleanResponse("DeleteSnapshot"); + } + + private Response handleCopySnapshot(MultivaluedMap p, String region) { + List snapshotTags = parseTagsForResource(p, "snapshot", Set.of("snapshot")); + boolean encrypted = Boolean.TRUE.equals(parseOptionalBoolean(p.getFirst("Encrypted"), "Encrypted")); + Snapshot copy = service.copySnapshot(region, p.getFirst("SourceRegion"), + p.getFirst("SourceSnapshotId"), p.getFirst("Description"), encrypted, snapshotTags, + dryRun(p)); + XmlBuilder xml = new XmlBuilder() + .start("CopySnapshotResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .elem("snapshotId", copy.getSnapshotId()) + .raw(tagSetXml(copy.getTags())) + .end("CopySnapshotResponse"); + return xmlResponse(xml.build()); + } + // ─── Tag handlers ───────────────────────────────────────────────────────── // AWS stores a tag created without a Value as an empty string. DeleteTags is the exception: @@ -6748,11 +6787,15 @@ public class Ec2QueryHandler { } private String snapshotXml(Snapshot snapshot) { + return snapshotXml(snapshot, snapshot.getState(), snapshot.getProgress()); + } + + private String snapshotXml(Snapshot snapshot, String status, String progress) { XmlBuilder xml = new XmlBuilder() .elem("snapshotId", snapshot.getSnapshotId()) .elem("ownerId", snapshot.getOwnerId()) - .elem("status", snapshot.getState()) - .elem("progress", snapshot.getProgress()) + .elem("status", status) + .elem("progress", progress) .elem("encrypted", String.valueOf(snapshot.isEncrypted())) .elem("description", snapshot.getDescription()); if (snapshot.getVolumeId() != null) { diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 495aa2bdf4..8d417bc878 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -2253,6 +2253,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab */ private final Object imageRegistryLock = new Object(); + /** The volume id AWS reports on a snapshot made by CopySnapshot, which has no source volume. */ + private static final String COPIED_SNAPSHOT_VOLUME_ID = "vol-ffffffff"; + /** * 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 @@ -9819,6 +9822,139 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .collect(Collectors.toList()); } + /** + * CreateSnapshot of an EBS volume. The snapshot takes the volume's size and encryption and is + * owned by the caller. AWS reports it as {@code pending} until the data is copied; Floci's + * copy completes within the call, so the stored snapshot is {@code completed} and a caller + * that waits for that state returns on its first poll. With {@code dryRun} the volume must + * still exist, and the request is then answered with DryRunOperation, nothing created. + * + * @see CreateSnapshot + */ + public Snapshot createSnapshot(String region, String volumeId, String description, List snapshotTags, + boolean dryRun) { + if (volumeId == null || volumeId.isBlank()) { + throw new AwsException("MissingParameter", "The request must contain the parameter VolumeId", 400); + } + return withVolumeLock(volumeId, () -> { + Volume volume = volumes.get(key(region, volumeId)).flatMap(v -> settleEndedHolders(region, v)) + .orElseThrow(() -> new AwsException("InvalidVolume.NotFound", + "The volume '" + volumeId + "' does not exist.", 400)); + if (dryRun) { + throw dryRunOperation(); + } + Snapshot snapshot = newSnapshot(region, "snap-" + randomHex(17), volumeId, volume.getSize(), + description, volume.isEncrypted()); + storeSnapshot(region, snapshot, snapshotTags); + return snapshot; + }); + } + + /** + * DeleteSnapshot. A snapshot backing a registered AMI is refused with InvalidSnapshot.InUse: + * "You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. + * You must first deregister the AMI before you can delete the snapshot." With {@code dryRun} + * the snapshot must still exist and be unused, and the request is then answered with + * DryRunOperation, the snapshot and its tags left in place. + * + * @see DeleteSnapshot + */ + public void deleteSnapshot(String region, String snapshotId, boolean dryRun) { + if (snapshotId == null || snapshotId.isBlank()) { + throw new AwsException("MissingParameter", "The request must contain the parameter SnapshotId", 400); + } + // Under the lock registration publishes snapshot references under, so an AMI being + // registered on this snapshot is either seen here or sees the snapshot gone, and under the + // snapshot's own lock, which a tag write holds, so CreateTags cannot tag it after it is gone. + synchronized (imageRegistryLock) { + synchronized (lockFor(key(region, snapshotId))) { + deleteSnapshotLocked(region, snapshotId, dryRun); + } + } + } + + private void deleteSnapshotLocked(String region, String snapshotId, boolean dryRun) { + if (snapshots.get(key(region, snapshotId)).isEmpty()) { + throw new AwsException("InvalidSnapshot.NotFound", + "The snapshot '" + snapshotId + "' does not exist.", 400); + } + Optional user = registeredImages.scan(k -> true).stream() + .filter(image -> region.equals(image.getRegion())) + .filter(image -> !DEREGISTERED_STATE.equals(image.getState())) + .filter(image -> image.getBlockDeviceMappings().stream() + .map(BlockDeviceMapping::getEbs) + .filter(Objects::nonNull) + .anyMatch(ebs -> snapshotId.equals(ebs.getSnapshotId()))) + .findFirst(); + if (user.isPresent()) { + throw new AwsException("InvalidSnapshot.InUse", + "The snapshot " + snapshotId + " is currently in use by " + user.get().getImageId(), 400); + } + if (dryRun) { + throw dryRunOperation(); + } + snapshots.delete(key(region, snapshotId)); + removeTags(region, snapshotId); + } + + /** + * CopySnapshot. As with CopyImage the request's own region is the destination and + * {@code SourceRegion} names where the source lives. The copy is an independent snapshot with + * its own id, owned by the caller; it stays encrypted when the source is, and becomes + * encrypted when the request or the destination's encryption by default says so. Tags are not + * copied: "User-defined tags are not copied from the source snapshot to the snapshot copy." + * With {@code dryRun} the source must still exist, and the request is then answered with + * DryRunOperation, nothing copied. + * + * @see CopySnapshot + */ + public Snapshot copySnapshot(String destinationRegion, String sourceRegion, String sourceSnapshotId, + String description, boolean encrypted, List snapshotTags, + boolean dryRun) { + if (sourceRegion == null || sourceRegion.isBlank()) { + throw new AwsException("MissingParameter", "The request must contain the parameter SourceRegion", 400); + } + if (sourceSnapshotId == null || sourceSnapshotId.isBlank()) { + throw new AwsException("MissingParameter", + "The request must contain the parameter SourceSnapshotId", 400); + } + Snapshot source = snapshots.get(key(sourceRegion, sourceSnapshotId)) + .orElseThrow(() -> new AwsException("InvalidSnapshot.NotFound", + "The snapshot '" + sourceSnapshotId + "' does not exist.", 400)); + if (dryRun) { + throw dryRunOperation(); + } + Snapshot copy = newSnapshot(destinationRegion, "snap-" + randomHex(17), COPIED_SNAPSHOT_VOLUME_ID, + source.getVolumeSize(), description, + source.isEncrypted() || encrypted || ebsEncryptionByDefault(destinationRegion)); + storeSnapshot(destinationRegion, copy, snapshotTags); + return copy; + } + + /** A completed snapshot record owned by the caller, not yet stored. */ + private Snapshot newSnapshot(String region, String snapshotId, String volumeId, Integer volumeSize, + String description, boolean encrypted) { + Snapshot snapshot = new Snapshot(); + snapshot.setSnapshotId(snapshotId); + snapshot.setVolumeId(volumeId); + snapshot.setVolumeSize(volumeSize); + snapshot.setOwnerId(callerAccountId()); + snapshot.setState("completed"); + snapshot.setDescription(description != null ? description : ""); + snapshot.setStartTime(Instant.now()); + snapshot.setEncrypted(encrypted); + snapshot.setRegion(region); + return snapshot; + } + + private void storeSnapshot(String region, Snapshot snapshot, List snapshotTags) { + if (snapshotTags != null && !snapshotTags.isEmpty()) { + snapshot.setTags(new ArrayList<>(snapshotTags)); + putTags(region, snapshot.getSnapshotId(), new ArrayList<>(snapshotTags)); + } + snapshots.put(key(region, snapshot.getSnapshotId()), snapshot); + } + // ─── Launch Templates ───────────────────────────────────────────────────── public LaunchTemplate createLaunchTemplate(String region, String name, LaunchTemplateData data, @@ -10580,16 +10716,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private Snapshot snapshotFrom(String region, String snapshotId, Image image, BlockDeviceMapping mapping) { EbsBlockDevice ebs = mapping.getEbs(); - Snapshot snapshot = new Snapshot(); - snapshot.setSnapshotId(snapshotId); - snapshot.setOwnerId(callerAccountId()); - snapshot.setState("completed"); - snapshot.setDescription("Created by RegisterImage for " + image.getName()); - snapshot.setStartTime(Instant.now()); - snapshot.setVolumeSize(ebs.getVolumeSize()); - snapshot.setEncrypted(Boolean.TRUE.equals(ebs.getEncrypted())); - snapshot.setRegion(region); - return snapshot; + return newSnapshot(region, snapshotId, null, ebs.getVolumeSize(), + "Created by RegisterImage for " + image.getName(), Boolean.TRUE.equals(ebs.getEncrypted())); } private boolean matchesSnapshotFilters(Snapshot snapshot, List>> filters) { @@ -10679,6 +10807,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // it and then together exceed it, and a rejected request writes nothing. withTagWriteLocks(region, resourceIds, () -> { for (String resourceId : resourceIds) { + // Checked again under the lock DeleteSnapshot deletes under, so a snapshot deleted + // since the check above is not left with tags and no resource. + if (resourceId.startsWith("snap-")) { + requireFound(snapshots.get(key(region, resourceId)).isPresent(), + "InvalidSnapshot.NotFound", "The snapshot '" + resourceId + "' does not exist."); + } requireWithinTagLimit(region, resourceId, tagList); } if (dryRun) { diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2SnapshotIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2SnapshotIntegrationTest.java new file mode 100644 index 0000000000..cfd3cbb5ab --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2SnapshotIntegrationTest.java @@ -0,0 +1,290 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.Ec2Requests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.CreateSnapshotResponse; +import software.amazon.awssdk.services.ec2.model.ResourceType; +import software.amazon.awssdk.services.ec2.model.Snapshot; +import software.amazon.awssdk.services.ec2.model.SnapshotState; +import software.amazon.awssdk.services.ec2.model.Tag; + +import java.util.List; + +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * CreateSnapshot, DeleteSnapshot and CopySnapshot for EBS volumes, through the AWS SDK. + * + *

Runs in its own regions so the snapshots other test classes leave behind in the same + * application do not show up in its listings.

+ */ +@QuarkusTest +class Ec2SnapshotIntegrationTest { + + private static final String REGION = "eu-south-2"; + private static final String COPY_REGION = "eu-central-2"; + + private static Ec2Client client(String region) { + return AwsTestClients.create(Ec2Client.builder(), "test", Region.of(region)); + } + + private static String createVolume(Ec2Client ec2, int size, boolean encrypted) { + return ec2.createVolume(request -> request + .availabilityZone(REGION + "a").size(size).encrypted(encrypted)).volumeId(); + } + + private static Snapshot describe(Ec2Client ec2, String snapshotId) { + return ec2.describeSnapshots(request -> request.snapshotIds(snapshotId)).snapshots().getFirst(); + } + + /** A raw Query request to {@code region}, for requests the SDK would not send. */ + private static RequestSpecification ec2(String region, String action, String... params) { + RequestSpecification request = Ec2Requests.ec2(action, "test", region); + for (int i = 0; i + 1 < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + return request; + } + + private static String createSnapshot(Ec2Client ec2) { + return ec2.createSnapshot(request -> request.volumeId(createVolume(ec2, 1, false))).snapshotId(); + } + + @ParameterizedTest + @CsvSource({ + "CreateSnapshot, Description, none", + "DeleteSnapshot, DryRun, false", + "CopySnapshot, SourceSnapshotId, snap-0123456789abcdef0", + "CopySnapshot, SourceRegion, eu-south-2" + }) + void aRequestMissingARequiredParameterIsRefused(String action, String otherParam, String otherValue) { + ec2(COPY_REGION, action, otherParam, otherValue).post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("MissingParameter")); + } + + @ParameterizedTest + @CsvSource({ + "CreateSnapshot, VolumeId, vol-0123456789abcdef0, InvalidVolume.NotFound", + "DeleteSnapshot, SnapshotId, snap-0123456789abcdef0, InvalidSnapshot.NotFound", + "CopySnapshot, SourceSnapshotId, snap-0123456789abcdef0, InvalidSnapshot.NotFound" + }) + void aDryRunTheRealCallWouldRefuseKeepsItsError(String action, String idParam, String id, String errorCode) { + ec2(REGION, action, idParam, id, "SourceRegion", REGION, "DryRun", "true").post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo(errorCode)); + } + + @Test + void aDryRunDeleteOfASnapshotAnImageUsesKeepsInUse() { + try (Ec2Client ec2 = client(REGION)) { + String snapshotId = createSnapshot(ec2); + ec2.registerImage(request -> request + .name("snapshot-dry-run-" + snapshotId) + .rootDeviceName("/dev/xvda") + .blockDeviceMappings(mapping -> mapping.deviceName("/dev/xvda") + .ebs(ebs -> ebs.snapshotId(snapshotId)))); + + assertAwsError("InvalidSnapshot.InUse", 400, + () -> ec2.deleteSnapshot(request -> request.snapshotId(snapshotId).dryRun(true))); + } + } + + @Test + void aDryRunDeleteOrCopyChangesNothing() { + try (Ec2Client ec2 = client(REGION)) { + String snapshotId = createSnapshot(ec2); + int before = ec2.describeSnapshots(request -> request.ownerIds("self")).snapshots().size(); + + ec2(REGION, "DeleteSnapshot", "SnapshotId", snapshotId, "DryRun", "true").post("/").then() + .statusCode(412) + .body("Response.Errors.Error.Code", equalTo("DryRunOperation")); + ec2(REGION, "CopySnapshot", "SourceSnapshotId", snapshotId, "SourceRegion", REGION, "DryRun", "true") + .post("/").then() + .statusCode(412) + .body("Response.Errors.Error.Code", equalTo("DryRunOperation")); + + assertEquals(snapshotId, describe(ec2, snapshotId).snapshotId()); + assertEquals(before, ec2.describeSnapshots(request -> request.ownerIds("self")).snapshots().size()); + } + } + + @Test + void copySnapshotWithAMalformedEncryptedIsRefused() { + try (Ec2Client ec2 = client(REGION)) { + String snapshotId = createSnapshot(ec2); + + ec2(REGION, "CopySnapshot", "SourceSnapshotId", snapshotId, "SourceRegion", REGION, + "Encrypted", "invalid").post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")); + } + } + + @Test + void tagsCannotBeCreatedOnADeletedSnapshot() { + try (Ec2Client ec2 = client(REGION)) { + String snapshotId = createSnapshot(ec2); + ec2.deleteSnapshot(request -> request.snapshotId(snapshotId)); + + assertAwsError("InvalidSnapshot.NotFound", 400, () -> ec2.createTags(request -> request + .resources(snapshotId).tags(Tag.builder().key("Name").value("late").build()))); + + assertTrue(ec2.describeTags(request -> request.filters(filter -> filter + .name("resource-id").values(snapshotId))).tags().isEmpty()); + } + } + + @Test + void createSnapshotIsPendingThenCompletedWithTheVolumeSize() { + try (Ec2Client ec2 = client(REGION)) { + String volumeId = createVolume(ec2, 3, false); + + CreateSnapshotResponse created = ec2.createSnapshot(request -> request + .volumeId(volumeId) + .description("nightly") + .tagSpecifications(spec -> spec.resourceType(ResourceType.SNAPSHOT) + .tags(Tag.builder().key("Name").value("backup").build()))); + + assertTrue(created.snapshotId().startsWith("snap-"), created.snapshotId()); + assertEquals(SnapshotState.PENDING, created.state()); + assertEquals(volumeId, created.volumeId()); + assertEquals(3, created.volumeSize()); + assertEquals("nightly", created.description()); + assertFalse(created.encrypted()); + assertEquals(List.of(Tag.builder().key("Name").value("backup").build()), created.tags()); + + Snapshot described = describe(ec2, created.snapshotId()); + assertEquals(SnapshotState.COMPLETED, described.state()); + assertEquals("100%", described.progress()); + assertEquals(volumeId, described.volumeId()); + assertEquals(3, described.volumeSize()); + assertEquals(created.ownerId(), described.ownerId()); + assertEquals(created.tags(), described.tags()); + + List owned = ec2.describeSnapshots(request -> request.ownerIds("self")).snapshots(); + assertTrue(owned.stream().anyMatch(snapshot -> created.snapshotId().equals(snapshot.snapshotId()))); + } + } + + @Test + void createSnapshotOfAnEncryptedVolumeIsEncrypted() { + try (Ec2Client ec2 = client(REGION)) { + String volumeId = createVolume(ec2, 1, true); + + CreateSnapshotResponse created = ec2.createSnapshot(request -> request.volumeId(volumeId)); + + assertTrue(created.encrypted()); + assertTrue(describe(ec2, created.snapshotId()).encrypted()); + } + } + + @Test + void createSnapshotOfAnUnknownVolumeFails() { + try (Ec2Client ec2 = client(REGION)) { + assertAwsError("InvalidVolume.NotFound", 400, + () -> ec2.createSnapshot(request -> request.volumeId("vol-0123456789abcdef0"))); + } + } + + @Test + void createSnapshotDryRunCreatesNothing() { + try (Ec2Client ec2 = client(REGION)) { + String volumeId = createVolume(ec2, 1, false); + + assertAwsError("DryRunOperation", 412, + () -> ec2.createSnapshot(request -> request.volumeId(volumeId).dryRun(true))); + + assertTrue(ec2.describeSnapshots(request -> request.filters(filter -> filter + .name("volume-id").values(volumeId))).snapshots().isEmpty()); + } + } + + @Test + void deleteSnapshotRemovesIt() { + try (Ec2Client ec2 = client(REGION)) { + String snapshotId = ec2.createSnapshot(request -> request + .volumeId(createVolume(ec2, 1, false))).snapshotId(); + + ec2.deleteSnapshot(request -> request.snapshotId(snapshotId)); + + assertAwsError("InvalidSnapshot.NotFound", 400, () -> describe(ec2, snapshotId)); + assertAwsError("InvalidSnapshot.NotFound", 400, + () -> ec2.deleteSnapshot(request -> request.snapshotId(snapshotId))); + } + } + + @Test + void deleteSnapshotInUseByAnImageFailsUntilTheImageIsDeregistered() { + try (Ec2Client ec2 = client(REGION)) { + String snapshotId = ec2.createSnapshot(request -> request + .volumeId(createVolume(ec2, 1, false))).snapshotId(); + String imageId = ec2.registerImage(request -> request + .name("snapshot-in-use-" + snapshotId) + .rootDeviceName("/dev/xvda") + .blockDeviceMappings(mapping -> mapping.deviceName("/dev/xvda") + .ebs(ebs -> ebs.snapshotId(snapshotId)))).imageId(); + + assertAwsError("InvalidSnapshot.InUse", 400, + () -> ec2.deleteSnapshot(request -> request.snapshotId(snapshotId))); + + ec2.deregisterImage(request -> request.imageId(imageId)); + ec2.deleteSnapshot(request -> request.snapshotId(snapshotId)); + assertAwsError("InvalidSnapshot.NotFound", 400, () -> describe(ec2, snapshotId)); + } + } + + @Test + void copySnapshotAcrossRegionsCreatesAnIndependentSnapshot() { + try (Ec2Client source = client(REGION); Ec2Client destination = client(COPY_REGION)) { + String sourceId = source.createSnapshot(request -> request + .volumeId(createVolume(source, 2, true)).description("source")).snapshotId(); + + // A raw request: the SDK presigns a cross-Region copy against the source Region's + // endpoint and cannot derive that from a localhost endpoint override. + String copyId = ec2(COPY_REGION, "CopySnapshot", + "SourceRegion", REGION, + "SourceSnapshotId", sourceId, + "Description", "copy", + "TagSpecification.1.ResourceType", "snapshot", + "TagSpecification.1.Tag.1.Key", "Name", + "TagSpecification.1.Tag.1.Value", "copy") + .post("/").then() + .statusCode(200) + .body("CopySnapshotResponse.tagSet.item.key", equalTo("Name")) + .extract().xmlPath().getString("CopySnapshotResponse.snapshotId"); + + assertNotEquals(sourceId, copyId); + Snapshot copy = describe(destination, copyId); + assertEquals(SnapshotState.COMPLETED, copy.state()); + assertEquals(2, copy.volumeSize()); + assertEquals("vol-ffffffff", copy.volumeId()); + assertEquals("copy", copy.description()); + assertTrue(copy.encrypted()); + assertEquals(List.of(Tag.builder().key("Name").value("copy").build()), copy.tags()); + + source.deleteSnapshot(request -> request.snapshotId(sourceId)); + assertEquals(copyId, describe(destination, copyId).snapshotId()); + } + } + + @Test + void copySnapshotOfAnUnknownSnapshotFails() { + ec2(COPY_REGION, "CopySnapshot", "SourceRegion", REGION, "SourceSnapshotId", "snap-0123456789abcdef0") + .post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidSnapshot.NotFound")); + } +}