mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(elasticache): support snapshots of cluster-mode-disabled replication groups (#7744)
This commit is contained in:
1 parent
46f0d91716
commit
42b28be218
8 files changed
+843
-10
No files matched your search
@@ -107,6 +107,9 @@ without user associations retain their existing behavior.
|
||||
| `AddTagsToResource` | - |
|
||||
| `RemoveTagsFromResource` | - |
|
||||
| `ListTagsForResource` | Read stored tags for supported ElastiCache resource ARNs |
|
||||
| `CreateSnapshot` | Take a manual snapshot of a cluster-mode-disabled replication group, named by `ReplicationGroupId` or by one of its `CacheClusterId`s: the RDB file of its backend, `available` as soon as the call returns. See [Snapshots](#snapshots) |
|
||||
| `DescribeSnapshots` | List manual snapshots matching every one of `SnapshotName`, `ReplicationGroupId`, `CacheClusterId` and `SnapshotSource`, paged by `MaxRecords` and `Marker` |
|
||||
| `DeleteSnapshot` | Delete a snapshot and its RDB archive |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
### Serverless caches and user groups
|
||||
@@ -141,8 +144,8 @@ security-group placement, KMS encryption and snapshot schedules are metadata; th
|
||||
autoscaling, VPC networking, encryption or snapshot storage. Snapshot restore and final snapshots
|
||||
are rejected explicitly. Engine/version transitions are rejected; supported major versions are
|
||||
Valkey 8, Redis 7 and Memcached 1.6. With Docker unavailable, metadata operations still work and
|
||||
connections require a reachable Docker daemon and a runtime restart. Snapshot APIs and serverless
|
||||
pagination are not implemented.
|
||||
connections require a reachable Docker daemon and a runtime restart. Serverless snapshot APIs and
|
||||
serverless pagination are not implemented.
|
||||
|
||||
### Single-node Redis/Valkey clusters
|
||||
|
||||
@@ -328,6 +331,28 @@ replication group is gone. The reference counts from the moment `CreateReplicati
|
||||
the name, not from when the group is stored, so a delete that lands while that create is still
|
||||
provisioning its container is refused too.
|
||||
|
||||
## Snapshots
|
||||
|
||||
`CreateSnapshot` saves the backend's dataset (`SAVE`) and keeps the RDB file with the snapshot
|
||||
record, so the snapshot is `available` when the call returns; a `SAVE` the server refuses, as
|
||||
it does while another save runs, fails the call with `InvalidReplicationGroupState`. `CreateReplicationGroup` with
|
||||
`SnapshotName` starts a new cluster-mode-disabled group and loads that file into its backend
|
||||
before the group is listed or its endpoint accepts connections; a group the file could not be
|
||||
loaded into is rolled back like any failed create. A snapshot whose file is missing is refused
|
||||
with `InvalidSnapshotState` before any group is created. A group cannot be deleted or modified
|
||||
while its snapshot is being taken, and a `CacheClusterId` given with a `ReplicationGroupId`
|
||||
must be one of that group's members. `CreateSnapshot` keeps its `Tags`, which
|
||||
`ListTagsForResource`, `AddTagsToResource` and `RemoveTagsFromResource` read and change through the
|
||||
snapshot's ARN. `DescribeSnapshots` returns snapshots in name order, `MaxRecords` (20 to 50, default
|
||||
50) at a time, with a `Marker` for the next page.
|
||||
|
||||
Snapshots outlive the group they were taken from, as on AWS. They are taken of
|
||||
cluster-mode-disabled replication groups only: a cluster-mode-enabled group, a standalone cache
|
||||
cluster or a group without a running backend is refused, as is seeding a cluster-mode-enabled
|
||||
group. Automatic snapshots, `CopySnapshot` and `FinalSnapshotIdentifier` are not modeled. To
|
||||
reload the dataset, the backend runs with `--enable-debug-command local`, which allows `DEBUG`
|
||||
only for connections from inside its own container; clients always connect through the proxy.
|
||||
|
||||
## Engine version and backend image
|
||||
|
||||
`EngineVersion` is control-plane metadata. For Redis/Valkey replication groups and
|
||||
|
||||
@@ -64,7 +64,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
|
||||
| [Amazon AppIntegrations](appintegrations.md) | `/eventIntegrations/*`, `/dataIntegrations/*`, `/tags/*` | REST JSON | 14 |
|
||||
| [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 |
|
||||
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 32 |
|
||||
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 35 |
|
||||
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |
|
||||
| [Aurora DSQL](dsql.md) | `/cluster`, `/cluster/{identifier}`, `/cluster/{identifier}/policy` + TLS endpoint | REST JSON + wire | 9 |
|
||||
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 117 |
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsNamespaces;
|
||||
import io.floci.aws.core.common.AwsQueryResponse;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.BackupWindows;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.XmlBuilder;
|
||||
import io.floci.aws.services.elasticache.model.AuthMode;
|
||||
@@ -13,6 +14,7 @@ import io.floci.aws.services.elasticache.model.CacheCluster;
|
||||
import io.floci.aws.services.elasticache.model.CacheParameterGroup;
|
||||
import io.floci.aws.services.elasticache.model.CacheSubnetGroup;
|
||||
import io.floci.aws.services.elasticache.model.ClusterNode;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheSnapshot;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheUser;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheUserGroup;
|
||||
import io.floci.aws.services.elasticache.model.Endpoint;
|
||||
@@ -96,6 +98,9 @@ public class ElastiCacheQueryHandler {
|
||||
case "AddTagsToResource" -> handleAddTagsToResource(params, region);
|
||||
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params, region);
|
||||
case "ListTagsForResource" -> handleListTagsForResource(params);
|
||||
case "CreateSnapshot" -> handleCreateSnapshot(params);
|
||||
case "DescribeSnapshots" -> handleDescribeSnapshots(params);
|
||||
case "DeleteSnapshot" -> handleDeleteSnapshot(params);
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported.", AwsNamespaces.EC, 400);
|
||||
};
|
||||
@@ -122,7 +127,8 @@ public class ElastiCacheQueryHandler {
|
||||
}
|
||||
|
||||
try {
|
||||
ReplicationGroup group = service.createReplicationGroup(
|
||||
String snapshotName = params.getFirst("SnapshotName");
|
||||
ElastiCacheService.CreateReplicationGroupRequest request =
|
||||
new ElastiCacheService.CreateReplicationGroupRequest(
|
||||
groupId,
|
||||
description != null ? description : "",
|
||||
@@ -144,7 +150,10 @@ public class ElastiCacheQueryHandler {
|
||||
replicationGroupSettings(params),
|
||||
parseTags(params),
|
||||
extractMemberList(params, "UserGroupIds.member."),
|
||||
parseSecurityGroupIds(params)));
|
||||
parseSecurityGroupIds(params));
|
||||
ReplicationGroup group = snapshotName != null && !snapshotName.isBlank()
|
||||
? service.createReplicationGroupFromSnapshot(request, snapshotName)
|
||||
: service.createReplicationGroup(request);
|
||||
String result = replicationGroupXml(group);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateReplicationGroup", AwsNamespaces.EC, result)).build();
|
||||
} catch (AwsException e) {
|
||||
@@ -599,6 +608,72 @@ public class ElastiCacheQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleCreateSnapshot(MultivaluedMap<String, String> params) {
|
||||
try {
|
||||
ElastiCacheSnapshot snapshot = service.createSnapshot(params.getFirst("SnapshotName"),
|
||||
params.getFirst("ReplicationGroupId"), params.getFirst("CacheClusterId"), parseTags(params));
|
||||
XmlBuilder xml = new XmlBuilder();
|
||||
appendSnapshot(xml, snapshot);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateSnapshot", AwsNamespaces.EC, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDescribeSnapshots(MultivaluedMap<String, String> params) {
|
||||
try {
|
||||
PaginatedResult<ElastiCacheSnapshot> page = service.describeSnapshots(params.getFirst("SnapshotName"),
|
||||
params.getFirst("ReplicationGroupId"), params.getFirst("CacheClusterId"),
|
||||
params.getFirst("SnapshotSource"), intParam(params, "MaxRecords"), params.getFirst("Marker"));
|
||||
XmlBuilder xml = new XmlBuilder().start("Snapshots");
|
||||
page.items().forEach(snapshot -> appendSnapshot(xml, snapshot));
|
||||
xml.end("Snapshots");
|
||||
if (page.nextToken() != null) {
|
||||
xml.elem("Marker", page.nextToken());
|
||||
}
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeSnapshots", AwsNamespaces.EC, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDeleteSnapshot(MultivaluedMap<String, String> params) {
|
||||
try {
|
||||
ElastiCacheSnapshot snapshot = service.deleteSnapshot(params.getFirst("SnapshotName"));
|
||||
XmlBuilder xml = new XmlBuilder();
|
||||
appendSnapshot(xml, snapshot);
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteSnapshot", AwsNamespaces.EC, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendSnapshot(XmlBuilder xml, ElastiCacheSnapshot s) {
|
||||
String created = s.getCreatedAt() != null ? s.getCreatedAt().toString() : "";
|
||||
xml.start("Snapshot")
|
||||
.elem("SnapshotName", s.getSnapshotName())
|
||||
.elem("ReplicationGroupId", s.getReplicationGroupId())
|
||||
.elem("ReplicationGroupDescription", s.getReplicationGroupDescription());
|
||||
if (s.getCacheClusterId() != null) {
|
||||
xml.elem("CacheClusterId", s.getCacheClusterId());
|
||||
}
|
||||
xml.elem("SnapshotStatus", s.getSnapshotStatus())
|
||||
.elem("SnapshotSource", s.getSnapshotSource())
|
||||
.elem("CacheNodeType", s.getCacheNodeType())
|
||||
.elem("Engine", s.getEngine())
|
||||
.elem("EngineVersion", s.getEngineVersion())
|
||||
.elem("NumNodeGroups", 1)
|
||||
.elem("ARN", s.getArn())
|
||||
.start("NodeSnapshots")
|
||||
.start("NodeSnapshot")
|
||||
.elem("NodeGroupId", "0001")
|
||||
.elem("CacheSize", s.getSizeBytes() + " bytes")
|
||||
.elem("SnapshotCreateTime", created)
|
||||
.end("NodeSnapshot")
|
||||
.end("NodeSnapshots")
|
||||
.end("Snapshot");
|
||||
}
|
||||
|
||||
private Response handleDescribeCacheSubnetGroups(MultivaluedMap<String, String> params) {
|
||||
try {
|
||||
List<CacheSubnetGroup> groups =
|
||||
@@ -837,6 +912,13 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
|
||||
}
|
||||
tags = user.getTags();
|
||||
}
|
||||
if ("snapshot".equals(arn[5])) {
|
||||
ElastiCacheSnapshot snapshot = service.getSnapshot(arn[6]);
|
||||
if (snapshot.getArn() != null && !snapshot.getArn().equalsIgnoreCase(resourceName)) {
|
||||
throw new AwsException("SnapshotNotFoundFault", "Snapshot " + arn[6] + " not found.", 404);
|
||||
}
|
||||
tags = snapshot.getTags();
|
||||
}
|
||||
if ("usergroup".equals(arn[5])) {
|
||||
ElastiCacheUserGroup userGroup = service.getUserGroup(arn[6]);
|
||||
if (userGroup.getArn() != null && !userGroup.getArn().equalsIgnoreCase(resourceName)) {
|
||||
|
||||
@@ -5,6 +5,8 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.BackupWindows;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
import io.floci.aws.core.resource.ResourceProvider;
|
||||
@@ -26,6 +28,7 @@ import io.floci.aws.services.elasticache.model.CacheClusterStatus;
|
||||
import io.floci.aws.services.elasticache.model.CacheParameterGroup;
|
||||
import io.floci.aws.services.elasticache.model.CacheSubnetGroup;
|
||||
import io.floci.aws.services.elasticache.model.ClusterNode;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheSnapshot;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheUser;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheUserGroup;
|
||||
import io.floci.aws.services.elasticache.model.Endpoint;
|
||||
@@ -49,6 +52,7 @@ import java.net.UnknownHostException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -88,6 +92,9 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
private final AccountAwareStorageBackend<ElastiCacheUserGroup> userGroups;
|
||||
private final AccountAwareStorageBackend<CacheParameterGroup> parameterGroups;
|
||||
private final StorageBackend<String, CacheSubnetGroup> subnetGroups;
|
||||
private final AccountAwareStorageBackend<ElastiCacheSnapshot> snapshots;
|
||||
/** RDB archives, base64 encoded, keyed like the snapshot records they belong to. */
|
||||
private final AccountAwareStorageBackend<String> snapshotArchives;
|
||||
private final ElastiCacheContainerManager containerManager;
|
||||
private final ElastiCacheProxyManager proxyManager;
|
||||
private final ValkeyClusterFormation clusterFormation;
|
||||
@@ -177,6 +184,10 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
new TypeReference<Map<String, CacheParameterGroup>>() {});
|
||||
this.subnetGroups = storageFactory.create("elasticache", "elasticache-subnet-groups.json",
|
||||
new TypeReference<Map<String, CacheSubnetGroup>>() {});
|
||||
this.snapshots = storageFactory.create("elasticache", "elasticache-snapshots.json",
|
||||
new TypeReference<Map<String, ElastiCacheSnapshot>>() {});
|
||||
this.snapshotArchives = storageFactory.create("elasticache", "elasticache-snapshot-data.json",
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,6 +234,17 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public ReplicationGroup createReplicationGroup(CreateReplicationGroupRequest request) {
|
||||
return createReplicationGroup(request, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot's RDB a new group is created holding: loaded into its backend before the group is
|
||||
* stored or its proxy started, so no client sees the group before its data.
|
||||
*/
|
||||
private record SnapshotSeed(String snapshotName, String rdbBase64) {
|
||||
}
|
||||
|
||||
private ReplicationGroup createReplicationGroup(CreateReplicationGroupRequest request, SnapshotSeed seed) {
|
||||
ReplicationGroupSettings settings = request.settings() != null
|
||||
? request.settings() : ReplicationGroupSettings.defaults();
|
||||
settings.validate();
|
||||
@@ -236,7 +258,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
settings.withKmsKeyId(resolveKmsKeyArn(settings.kmsKeyId(), request.region()));
|
||||
List<String> userGroupReservation = reserveUserGroups(request);
|
||||
try {
|
||||
return createReplicationGroupWithSettings(request, resolvedSettings);
|
||||
return createReplicationGroupWithSettings(request, resolvedSettings, seed);
|
||||
} finally {
|
||||
releaseUserGroups(userGroupReservation);
|
||||
}
|
||||
@@ -301,7 +323,8 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private ReplicationGroup createReplicationGroupWithSettings(CreateReplicationGroupRequest request,
|
||||
ReplicationGroupSettings resolvedSettings) {
|
||||
ReplicationGroupSettings resolvedSettings,
|
||||
SnapshotSeed seed) {
|
||||
String groupId = request.replicationGroupId();
|
||||
// Held until the group is persisted (or the attempt fails) so a concurrent
|
||||
// DeleteCacheParameterGroup sees the dependency before the stored-groups scan can.
|
||||
@@ -334,7 +357,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
if (resolveClusterEnabled(request)) {
|
||||
return provisionClusterModeGroup(request, resolvedSettings);
|
||||
}
|
||||
return provisionSingleNodeGroup(request, resolvedSettings);
|
||||
return provisionSingleNodeGroup(request, resolvedSettings, seed);
|
||||
} finally {
|
||||
provisioningIds.release(groupId);
|
||||
}
|
||||
@@ -380,7 +403,8 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private ReplicationGroup provisionSingleNodeGroup(CreateReplicationGroupRequest request,
|
||||
ReplicationGroupSettings resolvedSettings) {
|
||||
ReplicationGroupSettings resolvedSettings,
|
||||
SnapshotSeed seed) {
|
||||
String groupId = request.replicationGroupId();
|
||||
AuthMode authMode = request.authMode();
|
||||
int proxyPort = allocateProxyPort(request.port());
|
||||
@@ -396,6 +420,9 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
// 'available' even when no daemon is reachable. Only connecting to the cache needs
|
||||
// the container.
|
||||
handle = containerManager.tryStart(groupId, image, request.region());
|
||||
if (seed != null) {
|
||||
loadSnapshot(groupId, handle, seed);
|
||||
}
|
||||
|
||||
String endpointHost = resolveEndpointHost();
|
||||
Endpoint endpoint = new Endpoint(endpointHost, proxyPort);
|
||||
@@ -1323,6 +1350,207 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Snapshots ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Takes a manual snapshot of a cluster-mode-disabled replication group: the RDB file of its
|
||||
* backend, complete when this returns, so the snapshot is {@code available} straight away.
|
||||
* A cache cluster id names the group it is a member of.
|
||||
*/
|
||||
public ElastiCacheSnapshot createSnapshot(String snapshotName, String groupId, String cacheClusterId) {
|
||||
return createSnapshot(snapshotName, groupId, cacheClusterId, Map.of());
|
||||
}
|
||||
|
||||
public ElastiCacheSnapshot createSnapshot(String snapshotName, String groupId, String cacheClusterId,
|
||||
Map<String, String> tags) {
|
||||
if (snapshotName == null || snapshotName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "The parameter SnapshotName must be provided.", 400);
|
||||
}
|
||||
ReplicationGroup group = snapshotSource(groupId, cacheClusterId);
|
||||
String sourceId = group.getReplicationGroupId();
|
||||
if (group.isClusterEnabled()) {
|
||||
throw new AwsException("InvalidParameterValue", "Floci takes snapshots of cluster-mode-disabled"
|
||||
+ " replication groups only; " + sourceId + " is cluster-mode enabled.", 400);
|
||||
}
|
||||
// The group's monitor, which delete and modify take, is held while its RDB is read, so the
|
||||
// backend cannot be stopped under the SAVE; the group is read again under it.
|
||||
synchronized (lockFor("snapshot:" + snapshotName)) {
|
||||
synchronized (lockFor("rg:" + sourceId)) {
|
||||
return createSnapshotOf(snapshotName, getReplicationGroup(sourceId), cacheClusterId, tags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ElastiCacheSnapshot createSnapshotOf(String snapshotName, ReplicationGroup group, String cacheClusterId,
|
||||
Map<String, String> tags) {
|
||||
String sourceId = group.getReplicationGroupId();
|
||||
if (snapshots.get(snapshotName).isPresent()) {
|
||||
throw new AwsException("SnapshotAlreadyExistsFault",
|
||||
"Snapshot " + snapshotName + " already exists.", 400);
|
||||
}
|
||||
if (group.getStatus() != ReplicationGroupStatus.AVAILABLE) {
|
||||
throw new AwsException("InvalidReplicationGroupState",
|
||||
"Replication group " + sourceId + " is not available.", 400);
|
||||
}
|
||||
if (group.getContainerId() == null) {
|
||||
throw new AwsException("InvalidReplicationGroupState",
|
||||
"Replication group " + sourceId + " has no running backend to snapshot.", 400);
|
||||
}
|
||||
String archive;
|
||||
try {
|
||||
archive = containerManager.snapshot(group.getContainerId());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Failed to snapshot replication group {0}", sourceId);
|
||||
throw new AwsException("InvalidReplicationGroupState",
|
||||
"Failed to read the data of replication group " + sourceId + ": " + e.getMessage(), 400);
|
||||
}
|
||||
if (archive == null || archive.isEmpty()) {
|
||||
throw new AwsException("InvalidReplicationGroupState",
|
||||
"Replication group " + sourceId + " returned no data to snapshot.", 400);
|
||||
}
|
||||
ElastiCacheSnapshot snapshot = new ElastiCacheSnapshot();
|
||||
snapshot.setSnapshotName(snapshotName);
|
||||
snapshot.setReplicationGroupId(sourceId);
|
||||
snapshot.setReplicationGroupDescription(group.getDescription());
|
||||
snapshot.setCacheClusterId(cacheClusterId == null || cacheClusterId.isBlank() ? null : cacheClusterId);
|
||||
snapshot.setSnapshotStatus("available");
|
||||
snapshot.setSnapshotSource("manual");
|
||||
snapshot.setEngine(group.getEngine());
|
||||
snapshot.setEngineVersion(group.getEngineVersion());
|
||||
snapshot.setCacheNodeType(group.getCacheNodeType());
|
||||
snapshot.setNumCacheClusters(group.getNumCacheClusters());
|
||||
snapshot.setArn(regionResolver.buildArn("elasticache", regionOf(group.getArn()),
|
||||
"snapshot:" + snapshotName));
|
||||
snapshot.setCreatedAt(Instant.now());
|
||||
snapshot.setSizeBytes(archive.length() * 3L / 4L);
|
||||
snapshot.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());
|
||||
snapshotArchives.put(snapshotName, archive);
|
||||
snapshots.put(snapshotName, snapshot);
|
||||
LOG.infov("ElastiCache snapshot {0} of {1} created ({2} bytes)",
|
||||
snapshotName, sourceId, String.valueOf(snapshot.getSizeBytes()));
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** The replication group a CreateSnapshot names, directly or through one of its cache clusters. */
|
||||
private ReplicationGroup snapshotSource(String groupId, String cacheClusterId) {
|
||||
boolean namesGroup = groupId != null && !groupId.isBlank();
|
||||
if (cacheClusterId == null || cacheClusterId.isBlank()) {
|
||||
if (namesGroup) {
|
||||
return getReplicationGroup(groupId);
|
||||
}
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Either ReplicationGroupId or CacheClusterId must be provided.", 400);
|
||||
}
|
||||
Optional<ReplicationGroup> member = listMemberCacheClusters(cacheClusterId).stream()
|
||||
.findFirst().map(MemberCacheCluster::group);
|
||||
if (namesGroup) {
|
||||
ReplicationGroup group = getReplicationGroup(groupId);
|
||||
if (member.isEmpty() || !groupId.equals(member.get().getReplicationGroupId())) {
|
||||
throw new AwsException("InvalidParameterCombination", "Cache cluster " + cacheClusterId
|
||||
+ " is not a member of replication group " + groupId + ".", 400);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
if (member.isPresent()) {
|
||||
return member.get();
|
||||
}
|
||||
if (cacheClusters.get(cacheClusterId).isPresent() || memcachedClusters.get(cacheClusterId).isPresent()) {
|
||||
throw new AwsException("InvalidParameterValue", "Floci takes snapshots of replication groups;"
|
||||
+ " " + cacheClusterId + " is a standalone cache cluster.", 400);
|
||||
}
|
||||
throw new AwsException("CacheClusterNotFound", "Cache cluster " + cacheClusterId + " not found.", 404);
|
||||
}
|
||||
|
||||
public ElastiCacheSnapshot getSnapshot(String snapshotName) {
|
||||
return snapshots.get(snapshotName).orElseThrow(() ->
|
||||
new AwsException("SnapshotNotFoundFault", "Snapshot " + snapshotName + " not found.", 404));
|
||||
}
|
||||
|
||||
/**
|
||||
* A page of {@link #describeSnapshots(String, String, String, String)}, in snapshot name order:
|
||||
* {@code MaxRecords} 20 to 50, 50 when not given, and a {@code Marker} from the previous page.
|
||||
*/
|
||||
public PaginatedResult<ElastiCacheSnapshot> describeSnapshots(String snapshotName, String groupId,
|
||||
String cacheClusterId, String snapshotSource,
|
||||
Integer maxRecords, String marker) {
|
||||
if (maxRecords != null && (maxRecords < 20 || maxRecords > 50)) {
|
||||
throw new AwsException("InvalidParameterValue", "MaxRecords must be between 20 and 50.", 400);
|
||||
}
|
||||
List<ElastiCacheSnapshot> matching = describeSnapshots(snapshotName, groupId, cacheClusterId, snapshotSource)
|
||||
.stream().sorted(Comparator.comparing(ElastiCacheSnapshot::getSnapshotName)).toList();
|
||||
return Pagination.paginate(matching, ElastiCacheSnapshot::getSnapshotName,
|
||||
maxRecords != null ? maxRecords : 50, marker, "elasticache-snapshots",
|
||||
token -> new AwsException("InvalidParameterValue", "Invalid Marker.", 400));
|
||||
}
|
||||
|
||||
/** Snapshots matching every one of the name, replication group, cache cluster and source given. */
|
||||
public List<ElastiCacheSnapshot> describeSnapshots(String snapshotName, String groupId, String cacheClusterId,
|
||||
String snapshotSource) {
|
||||
List<ElastiCacheSnapshot> candidates = snapshotName != null && !snapshotName.isBlank()
|
||||
? List.of(getSnapshot(snapshotName))
|
||||
: snapshots.scan(k -> true);
|
||||
return candidates.stream()
|
||||
.filter(s -> groupId == null || groupId.isBlank() || groupId.equals(s.getReplicationGroupId()))
|
||||
.filter(s -> cacheClusterId == null || cacheClusterId.isBlank()
|
||||
|| cacheClusterId.equals(s.getCacheClusterId()))
|
||||
.filter(s -> snapshotSource == null || snapshotSource.isBlank()
|
||||
|| snapshotSource.equals(s.getSnapshotSource()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public ElastiCacheSnapshot deleteSnapshot(String snapshotName) {
|
||||
if (snapshotName == null || snapshotName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "The parameter SnapshotName must be provided.", 400);
|
||||
}
|
||||
synchronized (lockFor("snapshot:" + snapshotName)) {
|
||||
ElastiCacheSnapshot snapshot = getSnapshot(snapshotName);
|
||||
snapshots.delete(snapshotName);
|
||||
snapshotArchives.delete(snapshotName);
|
||||
snapshot.setSnapshotStatus("deleting");
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateReplicationGroup with a SnapshotName: a new cluster-mode-disabled group holding the
|
||||
* snapshot's data. The snapshot and its archive are read together, under the lock delete takes,
|
||||
* and checked before the group exists, so a snapshot whose archive is gone is refused rather than
|
||||
* restored as an empty group. The archive is loaded before the group is stored or its proxy
|
||||
* started, and a group it cannot be loaded into is rolled back like any failed create.
|
||||
*/
|
||||
public ReplicationGroup createReplicationGroupFromSnapshot(CreateReplicationGroupRequest request,
|
||||
String snapshotName) {
|
||||
String archive;
|
||||
synchronized (lockFor("snapshot:" + snapshotName)) {
|
||||
getSnapshot(snapshotName);
|
||||
archive = snapshotArchives.get(snapshotName).orElse(null);
|
||||
if (archive == null || archive.isEmpty()) {
|
||||
throw new AwsException("InvalidSnapshotState",
|
||||
"Snapshot " + snapshotName + " has no data to restore.", 400);
|
||||
}
|
||||
}
|
||||
if (resolveClusterEnabled(request)) {
|
||||
throw new AwsException("InvalidParameterCombination", "Snapshot " + snapshotName
|
||||
+ " is of a cluster-mode-disabled replication group and cannot seed the cluster-mode-enabled"
|
||||
+ " group " + request.replicationGroupId() + ".", 400);
|
||||
}
|
||||
return createReplicationGroup(request, new SnapshotSeed(snapshotName, archive));
|
||||
}
|
||||
|
||||
private void loadSnapshot(String groupId, ElastiCacheContainerHandle handle, SnapshotSeed seed) {
|
||||
if (handle == null) {
|
||||
throw new AwsException("InvalidReplicationGroupState", "Replication group " + groupId
|
||||
+ " has no running backend to restore snapshot " + seed.snapshotName() + " into.", 400);
|
||||
}
|
||||
try {
|
||||
containerManager.restore(handle.getContainerId(), seed.rdbBase64());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Failed to restore snapshot {0} into replication group {1}", seed.snapshotName(), groupId);
|
||||
throw new AwsException("InvalidSnapshotState", "Failed to restore snapshot " + seed.snapshotName()
|
||||
+ " into replication group " + groupId + ": " + e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cache Clusters (single-node Redis/Valkey) ─────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -2096,6 +2324,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
case "cluster" -> updateCacheClusterTags(ref, tags);
|
||||
case "subnetgroup" -> updateCacheSubnetGroupTags(ref, tags);
|
||||
case "parametergroup" -> updateCacheParameterGroupTags(ref, tags);
|
||||
case "snapshot" -> updateSnapshotTags(ref, tags, null);
|
||||
default -> throw ElastiCacheTagResourceArn.invalid(resourceArn);
|
||||
};
|
||||
}
|
||||
@@ -2110,6 +2339,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
case "cluster" -> removeCacheClusterTags(ref, tagKeys);
|
||||
case "subnetgroup" -> removeCacheSubnetGroupTags(ref, tagKeys);
|
||||
case "parametergroup" -> removeCacheParameterGroupTags(ref, tagKeys);
|
||||
case "snapshot" -> updateSnapshotTags(ref, Map.of(), tagKeys);
|
||||
default -> throw ElastiCacheTagResourceArn.invalid(resourceArn);
|
||||
};
|
||||
}
|
||||
@@ -2230,6 +2460,20 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds {@code tags} to a snapshot and removes {@code tagKeys}, under the lock its create and delete take. */
|
||||
private Map<String, String> updateSnapshotTags(TagResourceRef ref, Map<String, String> tags, List<String> tagKeys) {
|
||||
synchronized (lockFor("snapshot:" + ref.id())) {
|
||||
ElastiCacheSnapshot snapshot = getSnapshot(ref.id());
|
||||
requireResourceArn(snapshot.getArn(), ref.resourceArn(), "SnapshotNotFoundFault", ref.id());
|
||||
snapshot.getTags().putAll(tags);
|
||||
if (tagKeys != null) {
|
||||
tagKeys.forEach(snapshot.getTags()::remove);
|
||||
}
|
||||
snapshots.put(ref.id(), snapshot);
|
||||
return new LinkedHashMap<>(snapshot.getTags());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> updateCacheParameterGroupTags(TagResourceRef ref, Map<String, String> tags) {
|
||||
synchronized (lockFor(ref.id())) {
|
||||
CacheParameterGroup group = parameterGroups.get(ref.id()).orElseThrow(() ->
|
||||
|
||||
+40
-1
@@ -4,12 +4,14 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.RetryingTarCopier;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -21,6 +23,7 @@ import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -136,7 +139,9 @@ public class ElastiCacheContainerManager {
|
||||
// Remove any stale container with the same name
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
|
||||
StringBuilder serverFlags = new StringBuilder("--loglevel verbose");
|
||||
// DEBUG is enabled for connections from inside the container only, so a snapshot restore
|
||||
// can reload the dataset (DEBUG RELOAD NOSAVE); clients reach the server through the proxy.
|
||||
StringBuilder serverFlags = new StringBuilder("--loglevel verbose --enable-debug-command local");
|
||||
for (String flag : extraServerFlags) {
|
||||
serverFlags.append(' ').append(flag);
|
||||
}
|
||||
@@ -232,6 +237,40 @@ public class ElastiCacheContainerManager {
|
||||
+ " within " + BACKEND_READY_DEADLINE_MS + "ms");
|
||||
}
|
||||
|
||||
/** The server's own CLI, valkey-cli or redis-cli, run inside its container against the local server. */
|
||||
private static final String CLI = "C=$(command -v valkey-cli || command -v redis-cli); ";
|
||||
|
||||
/**
|
||||
* A snapshot of the dataset: the server's RDB file, written by SAVE, base64 encoded so it
|
||||
* travels through the exec's text output. The CLI exits 0 on an error reply too, so the reply
|
||||
* itself must be OK: a SAVE refused while a BGSAVE runs would otherwise hand back the previous
|
||||
* RDB file.
|
||||
*/
|
||||
public String snapshot(String containerId) {
|
||||
String[] cmd = {"sh", "-c", CLI + "R=$($C SAVE); if [ \"$R\" != OK ]; then echo \"SAVE: $R\" >&2; exit 1; fi;"
|
||||
+ " base64 -w0 \"$($C CONFIG GET dir | sed -n 2p)/$($C CONFIG GET dbfilename | sed -n 2p)\""};
|
||||
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 300);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new IllegalStateException("SAVE failed with exit code " + result.exitCode() + ": " + result.stderr());
|
||||
}
|
||||
return result.stdout().trim();
|
||||
}
|
||||
|
||||
/** Replaces the dataset with a {@link #snapshot} RDB file and reloads it without saving first. */
|
||||
public void restore(String containerId, String rdbBase64) {
|
||||
byte[] rdb = Base64.getDecoder().decode(rdbBase64);
|
||||
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/tmp",
|
||||
"floci-restore.rdb", rdb, 0644);
|
||||
String[] cmd = {"sh", "-c", CLI + "D=$($C CONFIG GET dir | sed -n 2p); F=$($C CONFIG GET dbfilename | sed -n 2p);"
|
||||
+ " cp /tmp/floci-restore.rdb \"$D/$F\" && rm -f /tmp/floci-restore.rdb"
|
||||
+ " && $C DEBUG RELOAD NOSAVE | grep -q OK"};
|
||||
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 300);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new IllegalStateException("restore failed with exit code " + result.exitCode() + ": "
|
||||
+ result.stderr() + result.stdout());
|
||||
}
|
||||
}
|
||||
|
||||
public void stop(ElastiCacheContainerHandle handle) {
|
||||
if (handle == null) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package io.floci.aws.services.elasticache.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A manual snapshot of a cluster-mode-disabled replication group: the record CreateSnapshot and
|
||||
* DescribeSnapshots answer with. The RDB archive it restores from is stored apart from it.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ElastiCacheSnapshot {
|
||||
|
||||
private String snapshotName;
|
||||
private String replicationGroupId;
|
||||
private String replicationGroupDescription;
|
||||
private String cacheClusterId;
|
||||
private String snapshotStatus;
|
||||
private String snapshotSource;
|
||||
private String engine;
|
||||
private String engineVersion;
|
||||
private String cacheNodeType;
|
||||
private int numCacheClusters;
|
||||
private String arn;
|
||||
private Instant createdAt;
|
||||
private long sizeBytes;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public ElastiCacheSnapshot() {
|
||||
}
|
||||
|
||||
public String getSnapshotName() { return snapshotName; }
|
||||
public void setSnapshotName(String snapshotName) { this.snapshotName = snapshotName; }
|
||||
|
||||
public String getReplicationGroupId() { return replicationGroupId; }
|
||||
public void setReplicationGroupId(String replicationGroupId) { this.replicationGroupId = replicationGroupId; }
|
||||
|
||||
public String getReplicationGroupDescription() { return replicationGroupDescription; }
|
||||
public void setReplicationGroupDescription(String description) { this.replicationGroupDescription = description; }
|
||||
|
||||
public String getCacheClusterId() { return cacheClusterId; }
|
||||
public void setCacheClusterId(String cacheClusterId) { this.cacheClusterId = cacheClusterId; }
|
||||
|
||||
public String getSnapshotStatus() { return snapshotStatus; }
|
||||
public void setSnapshotStatus(String snapshotStatus) { this.snapshotStatus = snapshotStatus; }
|
||||
|
||||
public String getSnapshotSource() { return snapshotSource; }
|
||||
public void setSnapshotSource(String snapshotSource) { this.snapshotSource = snapshotSource; }
|
||||
|
||||
public String getEngine() { return engine; }
|
||||
public void setEngine(String engine) { this.engine = engine; }
|
||||
|
||||
public String getEngineVersion() { return engineVersion; }
|
||||
public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
|
||||
|
||||
public String getCacheNodeType() { return cacheNodeType; }
|
||||
public void setCacheNodeType(String cacheNodeType) { this.cacheNodeType = cacheNodeType; }
|
||||
|
||||
public int getNumCacheClusters() { return numCacheClusters; }
|
||||
public void setNumCacheClusters(int numCacheClusters) { this.numCacheClusters = numCacheClusters; }
|
||||
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
|
||||
public Instant getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public long getSizeBytes() { return sizeBytes; }
|
||||
public void setSizeBytes(long sizeBytes) { this.sizeBytes = sizeBytes; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); }
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
@@ -847,6 +848,72 @@ class ElastiCacheIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(21)
|
||||
void snapshotCarriesTheDatasetIntoAGroupCreatedFromIt() throws Exception {
|
||||
String sourceId = "it-ec-snap-src";
|
||||
String restoredId = "it-ec-snap-dst";
|
||||
String snapshotName = "it-ec-snap";
|
||||
try {
|
||||
int sourcePort = createNoAuthGroup(sourceId, null);
|
||||
assertEquals("+OK\r\n", sendCommand(sourcePort, respArray("SET", "snapshot-key", "kept")));
|
||||
|
||||
given()
|
||||
.formParam("Action", "CreateSnapshot")
|
||||
.formParam("SnapshotName", snapshotName)
|
||||
.formParam("ReplicationGroupId", sourceId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateSnapshotResponse.CreateSnapshotResult.Snapshot.SnapshotStatus", equalTo("available"));
|
||||
// Written after the snapshot: the restored group must not see it.
|
||||
sendCommand(sourcePort, respArray("SET", "later-key", "after"));
|
||||
|
||||
int restoredPort = createNoAuthGroup(restoredId, snapshotName);
|
||||
try (Socket socket = openSocket(restoredPort)) {
|
||||
write(socket, respArray("GET", "snapshot-key"));
|
||||
assertEquals("$4\r\n", readLine(socket));
|
||||
assertEquals("kept\r\n", readLine(socket));
|
||||
}
|
||||
assertEquals("$-1\r\n", sendCommand(restoredPort, respArray("GET", "later-key")));
|
||||
} finally {
|
||||
for (String groupId : List.of(restoredId, sourceId)) {
|
||||
given()
|
||||
.formParam("Action", "DeleteReplicationGroup")
|
||||
.formParam("ReplicationGroupId", groupId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.post("/");
|
||||
}
|
||||
given()
|
||||
.formParam("Action", "DeleteSnapshot")
|
||||
.formParam("SnapshotName", snapshotName)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates a group without auth, from {@code snapshotName} when given, and returns its proxy port. */
|
||||
private static int createNoAuthGroup(String groupId, String snapshotName) {
|
||||
RequestSpecification request = given()
|
||||
.formParam("Action", "CreateReplicationGroup")
|
||||
.formParam("ReplicationGroupId", groupId)
|
||||
.formParam("ReplicationGroupDescription", "snapshot round trip")
|
||||
.header("Authorization", AUTH_HEADER);
|
||||
if (snapshotName != null) {
|
||||
request = request.formParam("SnapshotName", snapshotName);
|
||||
}
|
||||
return request
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.xmlPath()
|
||||
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.NodeGroups.NodeGroup.PrimaryEndpoint.Port");
|
||||
}
|
||||
|
||||
static boolean isDockerAvailable() {
|
||||
try {
|
||||
Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.floci.aws.services.elasticache.container.ValkeyClusterFormation;
|
||||
import io.floci.aws.services.elasticache.model.AuthMode;
|
||||
import io.floci.aws.services.elasticache.model.ElastiCacheSnapshot;
|
||||
import io.floci.aws.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.floci.aws.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Snapshots of a cluster-mode-disabled replication group, with the container layer mocked: what a
|
||||
* snapshot reads from its group's backend is what a group created from it loads, and the failure
|
||||
* paths leave neither a snapshot nor a group behind.
|
||||
*/
|
||||
class ElastiCacheSnapshotServiceTest {
|
||||
|
||||
private static final String RDB = "UkVESVMwMDEx+gl2YWxrZXktdmVyBTguMC4x/w==";
|
||||
|
||||
private ElastiCacheService service;
|
||||
private ElastiCacheContainerManager containerManager;
|
||||
private ElastiCacheProxyManager proxyManager;
|
||||
private final Map<String, AccountAwareStorageBackend<?>> backendsByFile = new ConcurrentHashMap<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
containerManager = mock(ElastiCacheContainerManager.class);
|
||||
proxyManager = mock(ElastiCacheProxyManager.class);
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.ElastiCacheServiceConfig ecConfig = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.elasticache()).thenReturn(ecConfig);
|
||||
when(ecConfig.proxyBasePort()).thenReturn(16379);
|
||||
when(ecConfig.proxyMaxPort()).thenReturn(16399);
|
||||
when(ecConfig.defaultImage()).thenReturn("valkey/valkey:8");
|
||||
when(config.hostname()).thenReturn(Optional.of("localhost"));
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
|
||||
backendsByFile.computeIfAbsent(inv.getArgument(1),
|
||||
file -> AccountAwareStorageBackend.inMemory("000000000000")));
|
||||
// Every group gets a container named after it, except "headless", which gets none.
|
||||
when(containerManager.tryStart(anyString(), anyString(), any())).thenAnswer(inv ->
|
||||
"headless".equals(inv.getArgument(0)) ? null
|
||||
: new ElastiCacheContainerHandle("container-" + inv.getArgument(0),
|
||||
inv.getArgument(0), "localhost", 6379));
|
||||
when(containerManager.snapshot("container-source")).thenReturn(RDB);
|
||||
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
|
||||
KmsService kmsService = mock(KmsService.class);
|
||||
when(kmsService.describeKey(any(), any())).thenThrow(new AwsException("NotFoundException", "Key not found", 404));
|
||||
service = new ElastiCacheService(containerManager, proxyManager, mock(ValkeyClusterFormation.class),
|
||||
storageFactory, config, mock(Ec2Service.class), new RegionResolver("us-east-1", "000000000000"),
|
||||
kmsService, new ElastiCacheProvisioningIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSnapshotsRdbSeedsAGroupCreatedFromIt() {
|
||||
group("source");
|
||||
|
||||
ElastiCacheSnapshot snapshot = service.createSnapshot("snap", "source", null);
|
||||
service.createReplicationGroupFromSnapshot(request("restored", null), "snap");
|
||||
|
||||
assertEquals("available", snapshot.getSnapshotStatus());
|
||||
assertEquals("manual", snapshot.getSnapshotSource());
|
||||
assertEquals("source", snapshot.getReplicationGroupId());
|
||||
assertEquals("arn:aws:elasticache:us-east-1:000000000000:snapshot:snap", snapshot.getArn());
|
||||
verify(containerManager).restore("container-restored", RDB);
|
||||
assertEquals("restored", service.getReplicationGroup("restored").getReplicationGroupId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRdbIsLoadedBeforeTheGroupIsPublishedOrReachable() {
|
||||
group("source");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
AtomicReference<String> duringLoad = new AtomicReference<>();
|
||||
doAnswer(inv -> {
|
||||
duringLoad.set(fault(() -> service.getReplicationGroup("restored")));
|
||||
return null;
|
||||
}).when(containerManager).restore("container-restored", RDB);
|
||||
|
||||
service.createReplicationGroupFromSnapshot(request("restored", null), "snap");
|
||||
|
||||
assertEquals("ReplicationGroupNotFoundFault", duringLoad.get());
|
||||
InOrder order = inOrder(containerManager, proxyManager);
|
||||
order.verify(containerManager).restore("container-restored", RDB);
|
||||
order.verify(proxyManager).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCacheClusterIdNamesTheGroupItBelongsTo() {
|
||||
group("source");
|
||||
String member = service.memberCacheClusters(service.getReplicationGroup("source")).getFirst().cacheClusterId();
|
||||
|
||||
ElastiCacheSnapshot snapshot = service.createSnapshot("snap", null, member);
|
||||
|
||||
assertEquals("source", snapshot.getReplicationGroupId());
|
||||
assertEquals(member, snapshot.getCacheClusterId());
|
||||
assertEquals("CacheClusterNotFound", fault(() -> service.createSnapshot("other", null, "no-such-cluster")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCacheClusterNamedWithAGroupMustBeOneOfItsMembers() {
|
||||
group("source");
|
||||
group("another");
|
||||
String member = service.memberCacheClusters(service.getReplicationGroup("source")).getFirst().cacheClusterId();
|
||||
String stranger = service.memberCacheClusters(service.getReplicationGroup("another")).getFirst().cacheClusterId();
|
||||
|
||||
assertEquals("InvalidParameterCombination", fault(() -> service.createSnapshot("snap", "source", stranger)));
|
||||
assertEquals(member, service.createSnapshot("snap", "source", member).getCacheClusterId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGroupCannotBeDeletedWhileItsRdbIsRead() throws Exception {
|
||||
group("source");
|
||||
AtomicReference<Thread> deleter = new AtomicReference<>();
|
||||
AtomicReference<Throwable> deleteFailure = new AtomicReference<>();
|
||||
when(containerManager.snapshot("container-source")).thenAnswer(inv -> {
|
||||
Thread thread = new Thread(() -> {
|
||||
try {
|
||||
service.deleteReplicationGroup("source");
|
||||
} catch (Throwable t) {
|
||||
deleteFailure.set(t);
|
||||
}
|
||||
});
|
||||
deleter.set(thread);
|
||||
thread.start();
|
||||
awaitBlockedOrDone(thread);
|
||||
assertTrue(thread.isAlive(), "the delete ran while the RDB was being read");
|
||||
return RDB;
|
||||
});
|
||||
|
||||
assertEquals("available", service.createSnapshot("snap", "source", null).getSnapshotStatus());
|
||||
deleter.get().join(10_000);
|
||||
|
||||
assertNull(deleteFailure.get());
|
||||
assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("source")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTakenNameIsRefused() {
|
||||
group("source");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
|
||||
assertEquals("SnapshotAlreadyExistsFault", fault(() -> service.createSnapshot("snap", "source", null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGroupWithoutARunningBackendCannotBeSnapshotted() {
|
||||
group("headless");
|
||||
|
||||
assertEquals("InvalidReplicationGroupState", fault(() -> service.createSnapshot("snap", "headless", null)));
|
||||
assertTrue(service.describeSnapshots(null, null, null, null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBackendThatCannotBeReadLeavesNoSnapshot() {
|
||||
group("source");
|
||||
when(containerManager.snapshot("container-source")).thenThrow(new IllegalStateException("SAVE exited 1"));
|
||||
|
||||
assertEquals("InvalidReplicationGroupState", fault(() -> service.createSnapshot("snap", "source", null)));
|
||||
assertEquals("SnapshotNotFoundFault", fault(() -> service.getSnapshot("snap")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotWhoseArchiveIsLostIsRefusedBeforeAnyGroupExists() {
|
||||
group("source");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
backendsByFile.get("elasticache-snapshot-data.json").clear();
|
||||
|
||||
assertEquals("InvalidSnapshotState",
|
||||
fault(() -> service.createReplicationGroupFromSnapshot(request("restored", null), "snap")));
|
||||
assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("restored")));
|
||||
verify(containerManager, never()).tryStart(eq("restored"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGroupTheRdbCannotBeLoadedIntoIsRemoved() {
|
||||
group("source");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
doThrow(new IllegalStateException("DEBUG RELOAD failed"))
|
||||
.when(containerManager).restore("container-restored", RDB);
|
||||
|
||||
assertEquals("InvalidSnapshotState",
|
||||
fault(() -> service.createReplicationGroupFromSnapshot(request("restored", null), "snap")));
|
||||
assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("restored")));
|
||||
verify(proxyManager, never()).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any());
|
||||
verify(containerManager).stop(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterModeGroupCannotBeSeededAndIsNeverStarted() {
|
||||
group("source");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
|
||||
assertEquals("InvalidParameterCombination",
|
||||
fault(() -> service.createReplicationGroupFromSnapshot(request("sharded", "enabled"), "snap")));
|
||||
verify(containerManager, never()).tryStart(eq("sharded"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeMatchesEveryFilterAndDeleteRemovesTheSnapshot() {
|
||||
group("source");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
|
||||
assertEquals(1, service.describeSnapshots("snap", "source", null, "manual").size());
|
||||
assertTrue(service.describeSnapshots("snap", "another-group", null, null).isEmpty());
|
||||
assertTrue(service.describeSnapshots(null, null, null, "automated").isEmpty());
|
||||
|
||||
assertEquals("deleting", service.deleteSnapshot("snap").getSnapshotStatus());
|
||||
assertEquals("SnapshotNotFoundFault", fault(() -> service.describeSnapshots("snap", null, null, null)));
|
||||
assertEquals("SnapshotNotFoundFault", fault(() -> service.deleteSnapshot("snap")));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.deleteSnapshot(null)));
|
||||
assertEquals("SnapshotNotFoundFault",
|
||||
fault(() -> service.createReplicationGroupFromSnapshot(request("restored", null), "snap")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsGivenAtCreateAreKeptAndCanBeChanged() {
|
||||
group("source");
|
||||
String arn = service.createSnapshot("snap", "source", null, Map.of("team", "cache")).getArn();
|
||||
|
||||
assertEquals(Map.of("team", "cache"), service.getSnapshot("snap").getTags());
|
||||
assertEquals(Map.of("team", "cache", "env", "test"),
|
||||
service.addTagsToResource(arn, Map.of("env", "test"), "us-east-1"));
|
||||
assertEquals(Map.of("env", "test"), service.removeTagsFromResource(arn, List.of("team"), "us-east-1"));
|
||||
assertEquals(Map.of("env", "test"), service.getSnapshot("snap").getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeSnapshotsPagesByNameWithMaxRecordsAndMarker() {
|
||||
group("source");
|
||||
for (int i = 0; i < 25; i++) {
|
||||
service.createSnapshot(String.format("snap-%02d", i), "source", null);
|
||||
}
|
||||
|
||||
PaginatedResult<ElastiCacheSnapshot> first = service.describeSnapshots(null, null, null, null, 20, null);
|
||||
PaginatedResult<ElastiCacheSnapshot> second =
|
||||
service.describeSnapshots(null, null, null, null, 20, first.nextToken());
|
||||
|
||||
assertEquals(20, first.items().size());
|
||||
assertEquals("snap-00", first.items().getFirst().getSnapshotName());
|
||||
assertEquals(List.of("snap-20", "snap-21", "snap-22", "snap-23", "snap-24"),
|
||||
second.items().stream().map(ElastiCacheSnapshot::getSnapshotName).toList());
|
||||
assertNull(second.nextToken());
|
||||
assertEquals(25, service.describeSnapshots(null, null, null, null, null, null).items().size());
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.describeSnapshots(null, null, null, null, 19, null)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.describeSnapshots(null, null, null, null, 51, null)));
|
||||
assertEquals("InvalidParameterValue",
|
||||
fault(() -> service.describeSnapshots(null, null, null, null, null, "not-a-marker")));
|
||||
}
|
||||
|
||||
private void group(String id) {
|
||||
service.createReplicationGroup(id, "group " + id, AuthMode.NO_AUTH, null, "us-east-1");
|
||||
}
|
||||
|
||||
private static ElastiCacheService.CreateReplicationGroupRequest request(String id, String clusterMode) {
|
||||
return new ElastiCacheService.CreateReplicationGroupRequest(id, "group " + id, AuthMode.NO_AUTH, null,
|
||||
"us-east-1", null, null, null, null, null, clusterMode,
|
||||
"enabled".equals(clusterMode) ? 2 : null, null, null, null, null, null, null, Map.of(), null, null);
|
||||
}
|
||||
|
||||
private static String fault(Runnable call) {
|
||||
return assertThrows(AwsException.class, call::run).getErrorCode();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user