mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(elasticache): IncreaseReplicaCount, DecreaseReplicaCount and TestFailover (#7881)
* feat(elasticache): IncreaseReplicaCount, DecreaseReplicaCount and TestFailover * fix(elasticache): refuse a replica count change or failover without a ReplicationGroupId * fix(elasticache): number a group's members so a decrease keeps the primary
This commit is contained in:
1 parent
edb42cebf1
commit
fdbcbb68ec
9 files changed
+508
-41
No files matched your search
@@ -79,6 +79,9 @@ without user associations retain their existing behavior.
|
||||
| `CreateReplicationGroup` | Start a new Redis/Valkey cluster; `AtRestEncryptionEnabled`, `KmsKeyId` (resolved to the key ARN), `SnapshotRetentionLimit`, `SnapshotWindow`, `Tags` and `UserGroupIds` are kept and returned, with the group `ARN`. `UserGroupIds` needs `TransitEncryptionEnabled` or an `AuthToken` |
|
||||
| `DescribeReplicationGroups` | List clusters and their connection info |
|
||||
| `ModifyReplicationGroup` | Modify `SnapshotRetentionLimit` and `SnapshotWindow`, and the associated user groups (`UserGroupIdsToAdd`, `UserGroupIdsToRemove`, `RemoveUserGroups`). A cache with user groups no longer takes its AUTH token, `AuthTokenUpdateStrategy=DELETE` removes the token when adding a user group, and removing the last user group leaves the cache without access control. Changing the AUTH token (`ROTATE`, `SET`) is not supported |
|
||||
| `IncreaseReplicaCount` | Raise a cluster-mode-disabled group's replicas to `NewReplicaCount` (up to 5), with `ApplyImmediately=true`. See [Replicas and failover](#replicas-and-failover) |
|
||||
| `DecreaseReplicaCount` | Lower a cluster-mode-disabled group's replicas to `NewReplicaCount`, with `ApplyImmediately=true`; `ReplicasToRemove` is not supported |
|
||||
| `TestFailover` | Promote the next member of node group `0001` of a cluster-mode-disabled group with automatic failover enabled |
|
||||
| `DeleteReplicationGroup` | Stop and remove a cluster |
|
||||
| `CreateUser` | Create a user with password, no-password-required or IAM authentication, set through `AuthenticationMode` or the top-level `Passwords` and `NoPasswordRequired` |
|
||||
| `DescribeUsers` | List ElastiCache users |
|
||||
@@ -331,6 +334,18 @@ 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.
|
||||
|
||||
## Replicas and failover
|
||||
|
||||
The members of a cluster-mode-disabled replication group share one backend, so a replica is a
|
||||
member cache cluster the group reports (`MemberClusters`, `NodeGroupMembers`), not a second server.
|
||||
`IncreaseReplicaCount` and `DecreaseReplicaCount` change the members at once, so `ApplyImmediately`
|
||||
must be `true` (AWS does not support `false` either), between 0 and 5 replicas, and at least one
|
||||
while Multi-AZ is enabled. New members take the next numbers, and a decrease removes the
|
||||
highest-numbered replicas, never the primary. `TestFailover` with `NodeGroupId` `0001` makes the next
|
||||
member the primary and the old primary a replica, as each `CurrentRole` then reports; the data and
|
||||
the endpoints stay as they are. It needs automatic failover enabled and at least one replica.
|
||||
Cluster-mode-enabled groups are refused with `InvalidParameterValue`.
|
||||
|
||||
## Snapshots
|
||||
|
||||
`CreateSnapshot` saves the backend's dataset (`SAVE`) and keeps the RDB file with the snapshot
|
||||
|
||||
@@ -65,7 +65,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 | 35 |
|
||||
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 38 |
|
||||
| [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 | 121 |
|
||||
|
||||
@@ -72,6 +72,9 @@ public class ElastiCacheQueryHandler {
|
||||
case "CreateReplicationGroup" -> handleCreateReplicationGroup(params, region);
|
||||
case "DescribeReplicationGroups" -> handleDescribeReplicationGroups(params);
|
||||
case "ModifyReplicationGroup" -> handleModifyReplicationGroup(params);
|
||||
case "IncreaseReplicaCount" -> handleReplicaCount(params, true);
|
||||
case "DecreaseReplicaCount" -> handleReplicaCount(params, false);
|
||||
case "TestFailover" -> handleTestFailover(params);
|
||||
case "DeleteReplicationGroup" -> handleDeleteReplicationGroup(params);
|
||||
case "CreateUser" -> handleCreateUser(params);
|
||||
case "DescribeUsers" -> handleDescribeUsers(params);
|
||||
@@ -267,6 +270,32 @@ public class ElastiCacheQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleReplicaCount(MultivaluedMap<String, String> params, boolean increase) {
|
||||
String action = increase ? "IncreaseReplicaCount" : "DecreaseReplicaCount";
|
||||
try {
|
||||
if (!increase && !extractMemberList(params, "ReplicasToRemove.member.").isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Floci decreases the replica count by NewReplicaCount only, not by ReplicasToRemove.", 400);
|
||||
}
|
||||
ReplicationGroup group = service.changeReplicaCount(params.getFirst("ReplicationGroupId"),
|
||||
intParam(params, "NewReplicaCount"), boolParam(params, "ApplyImmediately"), increase);
|
||||
return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.EC, replicationGroupXml(group))).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleTestFailover(MultivaluedMap<String, String> params) {
|
||||
try {
|
||||
ReplicationGroup group = service.testFailover(params.getFirst("ReplicationGroupId"),
|
||||
params.getFirst("NodeGroupId"));
|
||||
return Response.ok(AwsQueryResponse.envelope("TestFailover", AwsNamespaces.EC,
|
||||
replicationGroupXml(group))).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── Users ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateUser(MultivaluedMap<String, String> params) {
|
||||
|
||||
@@ -2126,14 +2126,137 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
return members;
|
||||
}
|
||||
for (int i = 1; i <= group.getNumCacheClusters(); i++) {
|
||||
List<Integer> numbers = memberNumbers(group);
|
||||
int primary = primaryMember(group, numbers);
|
||||
for (int number : numbers) {
|
||||
members.add(new MemberCacheCluster(group,
|
||||
group.getReplicationGroupId() + "-" + String.format("%03d", i),
|
||||
group.getProxyPort(), i == 1));
|
||||
group.getReplicationGroupId() + "-" + String.format("%03d", number),
|
||||
group.getProxyPort(), number == primary));
|
||||
}
|
||||
return members;
|
||||
}
|
||||
|
||||
/** A cluster-mode-disabled group's member numbers, in order: 1 to NumCacheClusters until a count change. */
|
||||
private static List<Integer> memberNumbers(ReplicationGroup group) {
|
||||
if (!group.getMemberNumbers().isEmpty()) {
|
||||
return group.getMemberNumbers();
|
||||
}
|
||||
List<Integer> numbers = new ArrayList<>();
|
||||
for (int number = 1; number <= group.getNumCacheClusters(); number++) {
|
||||
numbers.add(number);
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
/** The member a cluster-mode-disabled group reports as primary: the first, unless TestFailover moved it. */
|
||||
private static int primaryMember(ReplicationGroup group, List<Integer> numbers) {
|
||||
return numbers.contains(group.getPrimaryMemberNumber()) ? group.getPrimaryMemberNumber() : numbers.getFirst();
|
||||
}
|
||||
|
||||
// ── Replicas and failover ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* IncreaseReplicaCount and DecreaseReplicaCount for a cluster-mode-disabled group. Its members
|
||||
* share one backend, so a replica is a member cache cluster the group reports, added or removed at
|
||||
* once, since {@code ApplyImmediately=False} is not supported. Up to five replicas, and at least one
|
||||
* while Multi-AZ is enabled. New members take the next numbers; a decrease removes the
|
||||
* highest-numbered replicas and never the primary, which AWS does not delete.
|
||||
*/
|
||||
public ReplicationGroup changeReplicaCount(String groupId, Integer newReplicaCount, Boolean applyImmediately,
|
||||
boolean increase) {
|
||||
requireGroupId(groupId);
|
||||
if (applyImmediately == null) {
|
||||
throw new AwsException("InvalidParameterValue", "The parameter ApplyImmediately must be provided.", 400);
|
||||
}
|
||||
if (!applyImmediately) {
|
||||
throw new AwsException("InvalidParameterValue", "ApplyImmediately=False is not currently supported.", 400);
|
||||
}
|
||||
if (newReplicaCount == null) {
|
||||
throw new AwsException("InvalidParameterValue", "The parameter NewReplicaCount must be provided.", 400);
|
||||
}
|
||||
synchronized (lockFor("rg:" + groupId)) {
|
||||
ReplicationGroup group = requireFailoverCapable(groupId,
|
||||
increase ? "IncreaseReplicaCount" : "DecreaseReplicaCount");
|
||||
validateRange("NewReplicaCount", newReplicaCount, group.isMultiAzEnabled() ? 1 : 0, 5);
|
||||
List<Integer> numbers = new ArrayList<>(memberNumbers(group));
|
||||
int primary = primaryMember(group, numbers);
|
||||
int current = numbers.size() - 1;
|
||||
if (increase ? newReplicaCount <= current : newReplicaCount >= current) {
|
||||
throw new AwsException("InvalidParameterValue", "NewReplicaCount " + newReplicaCount + " must be "
|
||||
+ (increase ? "greater" : "less") + " than the " + current + " replica(s) replication group "
|
||||
+ groupId + " has.", 400);
|
||||
}
|
||||
if (increase) {
|
||||
int next = numbers.getLast();
|
||||
while (numbers.size() < newReplicaCount + 1) {
|
||||
numbers.add(++next);
|
||||
}
|
||||
} else {
|
||||
for (int i = numbers.size() - 1; i >= 0 && numbers.size() > newReplicaCount + 1; i--) {
|
||||
if (numbers.get(i) != primary) {
|
||||
numbers.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
group.setMemberNumbers(numbers);
|
||||
group.setNumCacheClusters(numbers.size());
|
||||
group.setPrimaryMemberNumber(primary);
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Replication group {0} now has {1} replica(s)", groupId, String.valueOf(newReplicaCount));
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TestFailover on a cluster-mode-disabled group, whose only node group is 0001: the next member
|
||||
* becomes primary and the old primary a replica. The members share one backend, so the data and
|
||||
* the endpoints stay as they are; the roles every API reports change.
|
||||
*/
|
||||
public ReplicationGroup testFailover(String groupId, String nodeGroupId) {
|
||||
requireGroupId(groupId);
|
||||
if (nodeGroupId == null || nodeGroupId.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "The parameter NodeGroupId must be provided.", 400);
|
||||
}
|
||||
synchronized (lockFor("rg:" + groupId)) {
|
||||
ReplicationGroup group = requireFailoverCapable(groupId, "TestFailover");
|
||||
if (!"0001".equals(nodeGroupId)) {
|
||||
throw new AwsException("NodeGroupNotFoundFault", "Node group " + nodeGroupId
|
||||
+ " not found in replication group " + groupId + ".", 404);
|
||||
}
|
||||
List<Integer> numbers = memberNumbers(group);
|
||||
if (!group.isAutomaticFailoverEnabled() || numbers.size() < 2) {
|
||||
throw new AwsException("InvalidReplicationGroupState", "Replication group " + groupId
|
||||
+ " needs automatic failover enabled and at least one replica to fail over.", 400);
|
||||
}
|
||||
int primary = primaryMember(group, numbers);
|
||||
group.setPrimaryMemberNumber(numbers.get((numbers.indexOf(primary) + 1) % numbers.size()));
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Replication group {0} failed over to member {1}", groupId,
|
||||
String.valueOf(group.getPrimaryMemberNumber()));
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireGroupId(String groupId) {
|
||||
if (groupId == null || groupId.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "The parameter ReplicationGroupId must be provided.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The group, read under its monitor by the caller: available and cluster-mode disabled. */
|
||||
private ReplicationGroup requireFailoverCapable(String groupId, String operation) {
|
||||
ReplicationGroup group = getReplicationGroup(groupId);
|
||||
if (group.isClusterEnabled()) {
|
||||
throw new AwsException("InvalidParameterValue", "Floci supports " + operation
|
||||
+ " on cluster-mode-disabled replication groups only; " + groupId + " is cluster-mode enabled.", 400);
|
||||
}
|
||||
if (group.getStatus() != ReplicationGroupStatus.AVAILABLE) {
|
||||
throw new AwsException("InvalidReplicationGroupState",
|
||||
"Replication group " + groupId + " is not available.", 400);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
public ReplicationGroup modifyReplicationGroup(String groupId, List<String> userGroupIdsToAdd,
|
||||
List<String> userGroupIdsToRemove) {
|
||||
return modifyReplicationGroup(groupId, userGroupIdsToAdd, userGroupIdsToRemove,
|
||||
|
||||
@@ -43,6 +43,13 @@ public class ReplicationGroup {
|
||||
private int numNodeGroups = 1;
|
||||
private int replicasPerNodeGroup;
|
||||
private int numCacheClusters = 1;
|
||||
/**
|
||||
* The numbers of a cluster-mode-disabled group's members, {@code <id>-001} upward, once a replica count
|
||||
* change has added or removed one. Empty until then, while the members are 1 to {@link #numCacheClusters}.
|
||||
*/
|
||||
private List<Integer> memberNumbers = new ArrayList<>();
|
||||
/** The number of the member a cluster-mode-disabled group reports as primary; TestFailover moves it. */
|
||||
private int primaryMemberNumber = 1;
|
||||
private String engine;
|
||||
private String engineVersion;
|
||||
private String cacheNodeType;
|
||||
@@ -170,6 +177,14 @@ public class ReplicationGroup {
|
||||
public int getNumCacheClusters() { return numCacheClusters; }
|
||||
public void setNumCacheClusters(int numCacheClusters) { this.numCacheClusters = numCacheClusters; }
|
||||
|
||||
public List<Integer> getMemberNumbers() { return memberNumbers; }
|
||||
public void setMemberNumbers(List<Integer> memberNumbers) {
|
||||
this.memberNumbers = memberNumbers == null ? new ArrayList<>() : new ArrayList<>(memberNumbers);
|
||||
}
|
||||
|
||||
public int getPrimaryMemberNumber() { return primaryMemberNumber; }
|
||||
public void setPrimaryMemberNumber(int primaryMemberNumber) { this.primaryMemberNumber = primaryMemberNumber; }
|
||||
|
||||
public String getEngine() { return engine; }
|
||||
public void setEngine(String engine) { this.engine = engine; }
|
||||
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.floci.aws.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.elasticache.ElastiCacheClient;
|
||||
import software.amazon.awssdk.services.elasticache.model.ElastiCacheException;
|
||||
import software.amazon.awssdk.services.elasticache.model.NodeGroupMember;
|
||||
import software.amazon.awssdk.services.elasticache.model.ReplicationGroup;
|
||||
import software.amazon.awssdk.services.elasticache.model.ReplicationGroupNotFoundException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** IncreaseReplicaCount, DecreaseReplicaCount and TestFailover through the SDK, on a cluster-mode-disabled group. */
|
||||
@QuarkusTest
|
||||
class ElastiCacheReplicaFailoverIntegrationTest {
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@InjectMock
|
||||
ElastiCacheContainerManager containerManager;
|
||||
|
||||
@BeforeEach
|
||||
void stubOnlyBackendProvisioning() {
|
||||
when(containerManager.tryStart(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(invocation -> new ElastiCacheContainerHandle("stub-" + invocation.getArgument(0),
|
||||
invocation.getArgument(0), "127.0.0.1", 16379));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replicasAndTheFailedOverPrimaryAreWhatEveryDescribeReports() {
|
||||
String groupId = "replicas-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
try (ElastiCacheClient client = AwsTestClients.create(ElastiCacheClient.builder(), "000000000000",
|
||||
Region.US_EAST_1, endpoint)) {
|
||||
try {
|
||||
client.createReplicationGroup(request -> request.replicationGroupId(groupId)
|
||||
.replicationGroupDescription("replicas and failover").engine("valkey")
|
||||
.numCacheClusters(2).automaticFailoverEnabled(true).multiAZEnabled(true));
|
||||
|
||||
ReplicationGroup increased = client.increaseReplicaCount(request -> request
|
||||
.replicationGroupId(groupId).newReplicaCount(3).applyImmediately(true)).replicationGroup();
|
||||
assertEquals(List.of(groupId + "-001", groupId + "-002", groupId + "-003", groupId + "-004"),
|
||||
increased.memberClusters());
|
||||
|
||||
ReplicationGroup failedOver = client.testFailover(request -> request
|
||||
.replicationGroupId(groupId).nodeGroupId("0001")).replicationGroup();
|
||||
assertEquals(groupId + "-002", primary(failedOver));
|
||||
|
||||
ReplicationGroup decreased = client.decreaseReplicaCount(request -> request
|
||||
.replicationGroupId(groupId).newReplicaCount(1).applyImmediately(true)).replicationGroup();
|
||||
assertEquals(List.of(groupId + "-001", groupId + "-002"), decreased.memberClusters());
|
||||
|
||||
ReplicationGroup described = client.describeReplicationGroups(request -> request
|
||||
.replicationGroupId(groupId)).replicationGroups().getFirst();
|
||||
assertEquals(groupId + "-002", primary(described));
|
||||
assertEquals(1, client.describeCacheClusters(request -> request
|
||||
.cacheClusterId(groupId + "-002")).cacheClusters().size());
|
||||
|
||||
assertEquals("InvalidParameterValue", assertThrows(ElastiCacheException.class,
|
||||
() -> client.decreaseReplicaCount(request -> request.replicationGroupId(groupId)
|
||||
.newReplicaCount(0).applyImmediately(true))).awsErrorDetails().errorCode());
|
||||
assertEquals("InvalidParameterValue", assertThrows(ElastiCacheException.class,
|
||||
() -> client.increaseReplicaCount(request -> request.replicationGroupId(groupId)
|
||||
.newReplicaCount(2).applyImmediately(false))).awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
try {
|
||||
client.deleteReplicationGroup(request -> request.replicationGroupId(groupId));
|
||||
} catch (ReplicationGroupNotFoundException expected) {
|
||||
// A failed create may not have stored the group; there is then nothing to clean up.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String primary(ReplicationGroup group) {
|
||||
return group.nodeGroups().getFirst().nodeGroupMembers().stream()
|
||||
.filter(member -> "primary".equals(member.currentRole()))
|
||||
.map(NodeGroupMember::cacheClusterId).findFirst().orElseThrow();
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.elasticache.model.AuthMode;
|
||||
import io.floci.aws.services.elasticache.model.ReplicationGroup;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* IncreaseReplicaCount, DecreaseReplicaCount and TestFailover on cluster-mode-disabled groups, whose
|
||||
* members share one backend: the numbered members and the member reported as primary are what change.
|
||||
*/
|
||||
class ElastiCacheReplicaFailoverServiceTest {
|
||||
|
||||
private ElastiCacheService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new ElastiCacheServiceFixture().service;
|
||||
}
|
||||
|
||||
@Test
|
||||
void replicasAreAddedAndRemovedAsMemberCacheClusters() {
|
||||
group("cache", 2, false, false);
|
||||
|
||||
service.changeReplicaCount("cache", 4, true, true);
|
||||
assertEquals(List.of("cache-001", "cache-002", "cache-003", "cache-004", "cache-005"), memberIds("cache"));
|
||||
|
||||
service.changeReplicaCount("cache", 0, true, false);
|
||||
assertEquals(List.of("cache-001"), memberIds("cache"));
|
||||
assertEquals(1, service.getReplicationGroup("cache").getNumCacheClusters());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCountThatDoesNotMoveTheRightWayOrLeavesTheRangeIsRefused() {
|
||||
group("cache", 2, false, false);
|
||||
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", 1, true, true)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", 2, true, false)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", 6, true, true)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", null, true, true)));
|
||||
assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.changeReplicaCount("nope", 2, true, true)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount(null, 3, true, true)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount(" ", 1, true, false)));
|
||||
assertEquals(2, service.getReplicationGroup("cache").getNumCacheClusters());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCountChangeMustBeAppliedImmediately() {
|
||||
group("cache", 2, false, false);
|
||||
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", 3, null, true)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", 3, false, true)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("cache", 0, false, false)));
|
||||
assertEquals(List.of("cache-001", "cache-002"), memberIds("cache"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiAzKeepsAReplicaWhereAutomaticFailoverAloneDoesNot() {
|
||||
group("multi-az", 2, true, true);
|
||||
group("failover", 2, true, false);
|
||||
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.changeReplicaCount("multi-az", 0, true, false)));
|
||||
assertEquals(List.of("multi-az-001", "multi-az-002"), memberIds("multi-az"));
|
||||
|
||||
service.changeReplicaCount("failover", 0, true, false);
|
||||
assertEquals(List.of("failover-001"), memberIds("failover"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failoverMovesThePrimaryToTheNextMemberAndBackRound() {
|
||||
group("cache", 3, true, false);
|
||||
|
||||
service.testFailover("cache", "0001");
|
||||
assertEquals("cache-002", primaryId("cache"));
|
||||
service.testFailover("cache", "0001");
|
||||
assertEquals("cache-003", primaryId("cache"));
|
||||
service.testFailover("cache", "0001");
|
||||
assertEquals("cache-001", primaryId("cache"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDecreaseRemovesReplicasAndKeepsThePrimary() {
|
||||
group("cache", 3, true, false);
|
||||
service.testFailover("cache", "0001");
|
||||
service.testFailover("cache", "0001");
|
||||
|
||||
service.changeReplicaCount("cache", 1, true, false);
|
||||
|
||||
assertEquals(List.of("cache-001", "cache-003"), memberIds("cache"));
|
||||
assertEquals("cache-003", primaryId("cache"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void newReplicasTakeTheNextNumbersAndFailoverFollowsTheMembers() {
|
||||
group("cache", 3, true, false);
|
||||
service.testFailover("cache", "0001");
|
||||
service.testFailover("cache", "0001");
|
||||
service.changeReplicaCount("cache", 1, true, false);
|
||||
|
||||
service.changeReplicaCount("cache", 3, true, true);
|
||||
assertEquals(List.of("cache-001", "cache-003", "cache-004", "cache-005"), memberIds("cache"));
|
||||
assertEquals("cache-003", primaryId("cache"));
|
||||
|
||||
service.testFailover("cache", "0001");
|
||||
assertEquals("cache-004", primaryId("cache"));
|
||||
service.testFailover("cache", "0001");
|
||||
service.testFailover("cache", "0001");
|
||||
assertEquals("cache-001", primaryId("cache"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failoverNeedsAutomaticFailoverAReplicaAndNodeGroup0001() {
|
||||
group("manual", 2, false, false);
|
||||
group("lonely", 1, false, false);
|
||||
group("cache", 2, true, false);
|
||||
|
||||
assertEquals("InvalidReplicationGroupState", fault(() -> service.testFailover("manual", "0001")));
|
||||
assertEquals("InvalidReplicationGroupState", fault(() -> service.testFailover("lonely", "0001")));
|
||||
assertEquals("NodeGroupNotFoundFault", fault(() -> service.testFailover("cache", "0002")));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.testFailover("cache", null)));
|
||||
assertEquals("InvalidParameterValue", fault(() -> service.testFailover(null, "0001")));
|
||||
assertEquals("cache-001", primaryId("cache"));
|
||||
}
|
||||
|
||||
private void group(String id, int numCacheClusters, boolean automaticFailover, boolean multiAz) {
|
||||
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(id, "group " + id,
|
||||
AuthMode.NO_AUTH, null, "us-east-1", null, null, null, null, null, null, null, null,
|
||||
numCacheClusters, automaticFailover, multiAz, null, null, Map.of(), null, null));
|
||||
}
|
||||
|
||||
private List<String> memberIds(String groupId) {
|
||||
ReplicationGroup group = service.getReplicationGroup(groupId);
|
||||
return service.memberCacheClusters(group).stream()
|
||||
.map(ElastiCacheService.MemberCacheCluster::cacheClusterId).toList();
|
||||
}
|
||||
|
||||
private String primaryId(String groupId) {
|
||||
ReplicationGroup group = service.getReplicationGroup(groupId);
|
||||
return service.memberCacheClusters(group).stream().filter(ElastiCacheService.MemberCacheCluster::primary)
|
||||
.map(ElastiCacheService.MemberCacheCluster::cacheClusterId).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private static String fault(Runnable call) {
|
||||
return assertThrows(AwsException.class, call::run).getErrorCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
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.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.proxy.ElastiCacheProxyManager;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* An {@link ElastiCacheService} over in-memory stores, with the container, proxy and KMS layers mocked:
|
||||
* every group gets a container named after it, its proxy starts, and no KMS key resolves.
|
||||
*/
|
||||
final class ElastiCacheServiceFixture {
|
||||
|
||||
final ElastiCacheContainerManager containerManager = mock(ElastiCacheContainerManager.class);
|
||||
final ElastiCacheProxyManager proxyManager = mock(ElastiCacheProxyManager.class);
|
||||
/** The in-memory store behind each storage file, by file name. */
|
||||
final Map<String, AccountAwareStorageBackend<?>> backendsByFile = new ConcurrentHashMap<>();
|
||||
final ElastiCacheService service;
|
||||
|
||||
ElastiCacheServiceFixture() {
|
||||
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")));
|
||||
when(containerManager.tryStart(anyString(), anyString(), any()))
|
||||
.thenAnswer(inv -> containerHandle(inv.getArgument(0)));
|
||||
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());
|
||||
}
|
||||
|
||||
/** The container the group {@code groupId} gets. */
|
||||
static ElastiCacheContainerHandle containerHandle(String groupId) {
|
||||
return new ElastiCacheContainerHandle("container-" + groupId, groupId, "localhost", 6379);
|
||||
}
|
||||
}
|
||||
+9
-37
@@ -1,27 +1,18 @@
|
||||
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;
|
||||
@@ -34,10 +25,8 @@ 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;
|
||||
@@ -54,37 +43,20 @@ class ElastiCacheSnapshotServiceTest {
|
||||
private ElastiCacheService service;
|
||||
private ElastiCacheContainerManager containerManager;
|
||||
private ElastiCacheProxyManager proxyManager;
|
||||
private final Map<String, AccountAwareStorageBackend<?>> backendsByFile = new ConcurrentHashMap<>();
|
||||
private Map<String, AccountAwareStorageBackend<?>> backendsByFile;
|
||||
|
||||
@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")));
|
||||
ElastiCacheServiceFixture fixture = new ElastiCacheServiceFixture();
|
||||
service = fixture.service;
|
||||
containerManager = fixture.containerManager;
|
||||
proxyManager = fixture.proxyManager;
|
||||
backendsByFile = fixture.backendsByFile;
|
||||
// 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));
|
||||
doAnswer(inv -> "headless".equals(inv.getArgument(0)) ? null
|
||||
: ElastiCacheServiceFixture.containerHandle(inv.getArgument(0)))
|
||||
.when(containerManager).tryStart(anyString(), anyString(), any());
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user