mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(elasticache): support cluster-mode replication groups (#2633)
* feat(elasticache): support cluster-mode replication groups CreateReplicationGroup now provisions a real sharded Valkey cluster when the request asks for one (NumNodeGroups > 1, a cluster.on parameter group, or ClusterMode=enabled): one cluster-enabled container per node, formed via config epochs, MEET, slot assignment and replica attachment, each fronted by its own auth-proxy port announced to clients via cluster-announce-client-ipv4/cluster-announce-port so CLUSTER SLOTS and MOVED redirects point at reachable addresses. DescribeReplicationGroups reports the topology honestly (ClusterEnabled, NodeGroups with Slots, MemberClusters, Engine, ARN, AutomaticFailover), and replication-group members answer DescribeCacheClusters, which is where terraform-provider-aws reads node type, engine version and port from. Adds a terraform compatibility test that applies an aws_elasticache_replication_group with num_node_groups and replicas_per_node_group, asserts the data plane is a formed cluster running in cluster mode (INFO cluster / CLUSTER INFO over RESP through the proxy), and that a re-plan straight after apply is clean. * fix(elasticache): address cluster-mode review feedback and compat CI failure - bump compat-terraform aws-cli image to 2.34.32 so botocore models include ReplicationGroup.Engine (old pin silently dropped the field) - restore cluster-mode runtime state (ports, containers, proxies, cluster formation) after restart; mark groups create-failed on error - announce configured hostname to Valkey nodes so MOVED redirects and CLUSTER SLOTS return client-reachable endpoints - log swallowed socket-close failures in cluster formation * fix(elasticache): report restore-failed members and modeled node-group quota fault Review follow-up for cluster-mode support: - Member cache clusters mirror their group's status instead of a hardcoded "available", so a group marked create-failed by a failed restore no longer contradicts its own members in DescribeCacheClusters. CacheClusterStatus has no create-failed value, so failed members report the documented restore-failed. - NumNodeGroups above the 500 ceiling surfaces the modeled NodeGroupsPerReplicationGroupQuotaExceeded fault instead of a generic InvalidParameterValue. - Javadoc names ClusterMode=compatible handling and the cluster-mode-only restore scope as deliberate. * fix(elasticache): announce a client-resolvable hostname for cluster mode Cluster-mode nodes announced FLOCI_HOSTNAME verbatim, so the shipped Docker Compose deployment baked the Compose-only name 'floci' into MOVED/ASK redirects and topology responses, breaking cluster-aware clients connecting from outside the Compose network. Add FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME (default: FLOCI_HOSTNAME) used for the announced name and the reported ConfigurationEndpoint, and set it to localhost.floci.io in docker-compose.yml — public DNS resolves it to 127.0.0.1 on the host while the network alias and Floci's embedded DNS resolve it to the Floci container from inside Docker. * fix(elasticache): restore cluster-mode groups without blocking startup Restoring persisted cluster-mode groups ran serially in the synchronous startup path, so a slow or unavailable Docker daemon could hold up emulator readiness by a container-readiness plus cluster-formation timeout per group, timing out readiness-dependent clients such as Testcontainers. restorePersistedRuntime now reserves each node's proxy port and marks groups creating synchronously - so no request can claim a persisted port or see a stale available status - then brings containers, cluster formation and proxies back in the background, flipping each group to available or create-failed as its restore finishes. --------- Co-authored-by: kurtmc <2661907+kurtmc@users.noreply.github.com>
This commit is contained in:
1 parent
eb5134da2d
commit
97ff0bc3e9
22 files changed
+2170
-69
No files matched your search
@@ -1063,6 +1063,14 @@ public interface EmulatorConfig {
|
||||
|
||||
/** Docker network to attach ElastiCache containers to. Empty = default bridge. */
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* Hostname cluster-mode nodes announce in MOVED/ASK redirects and cluster topology,
|
||||
* and that is reported as the ConfigurationEndpoint. Must resolve to Floci from every
|
||||
* client location; set it when the main hostname only resolves inside Floci's Docker
|
||||
* network. Empty = the main hostname.
|
||||
*/
|
||||
Optional<String> clusterAnnounceHostname();
|
||||
}
|
||||
|
||||
interface MemoryDbServiceConfig {
|
||||
|
||||
+10
@@ -593,6 +593,16 @@ public class ContainerLifecycleManager {
|
||||
return resolveEndpoint(inspect, containerPort);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the container's IP on its Docker network, independent of whether Floci runs
|
||||
* natively or in a container. Used for addresses that sibling containers (not Floci itself)
|
||||
* must dial — e.g. ElastiCache cluster-bus peering between Valkey nodes.
|
||||
*/
|
||||
public String resolveContainerNetworkIp(String containerId, String preferredNetwork) {
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
return resolveContainerIp(inspect, preferredNetwork);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying DockerClient for operations not covered by this manager.
|
||||
* Prefer using manager methods when available.
|
||||
|
||||
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.floci.ui.FlociUiManager;
|
||||
import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager;
|
||||
import io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
@@ -66,6 +67,7 @@ public class EmulatorLifecycle {
|
||||
private final ServiceRegistry serviceRegistry;
|
||||
private final EmulatorConfig config;
|
||||
private final IamService iamService;
|
||||
private final ElastiCacheService elastiCacheService;
|
||||
private final ElastiCacheContainerManager elastiCacheContainerManager;
|
||||
private final ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager;
|
||||
private final ElastiCacheProxyManager elastiCacheProxyManager;
|
||||
@@ -97,6 +99,7 @@ public class EmulatorLifecycle {
|
||||
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
|
||||
EmulatorConfig config,
|
||||
IamService iamService,
|
||||
ElastiCacheService elastiCacheService,
|
||||
ElastiCacheContainerManager elastiCacheContainerManager,
|
||||
ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager,
|
||||
ElastiCacheProxyManager elastiCacheProxyManager,
|
||||
@@ -127,6 +130,7 @@ public class EmulatorLifecycle {
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
this.config = config;
|
||||
this.iamService = iamService;
|
||||
this.elastiCacheService = elastiCacheService;
|
||||
this.elastiCacheContainerManager = elastiCacheContainerManager;
|
||||
this.elastiCacheMemcachedContainerManager = elastiCacheMemcachedContainerManager;
|
||||
this.elastiCacheProxyManager = elastiCacheProxyManager;
|
||||
@@ -189,6 +193,12 @@ public class EmulatorLifecycle {
|
||||
dynamodbStreamsPoller.startPersistedPollers();
|
||||
pipesService.startPersistedPollers();
|
||||
rdsService.restorePersistedRuntime();
|
||||
if (config.services().elasticache().enabled()) {
|
||||
elastiCacheService.restorePersistedRuntime().exceptionally(ex -> {
|
||||
LOG.warnv("ElastiCache cluster-mode restore failed: {0}", ex.getMessage());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
if (config.services().elbv2().enabled()) {
|
||||
elbV2Service.restorePersistedRuntime();
|
||||
}
|
||||
|
||||
+189
-7
@@ -9,11 +9,13 @@ import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.CacheParameterGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.CacheSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -106,8 +108,25 @@ public class ElastiCacheQueryHandler {
|
||||
|
||||
try {
|
||||
ReplicationGroup group = service.createReplicationGroup(
|
||||
groupId, description != null ? description : "", authMode, authToken, region,
|
||||
replicationGroupSettings(params), parseTags(params));
|
||||
new ElastiCacheService.CreateReplicationGroupRequest(
|
||||
groupId,
|
||||
description != null ? description : "",
|
||||
authMode,
|
||||
authToken,
|
||||
region,
|
||||
params.getFirst("Engine"),
|
||||
params.getFirst("EngineVersion"),
|
||||
params.getFirst("CacheNodeType"),
|
||||
params.getFirst("CacheParameterGroupName"),
|
||||
params.getFirst("CacheSubnetGroupName"),
|
||||
params.getFirst("ClusterMode"),
|
||||
intParam(params, "NumNodeGroups"),
|
||||
intParam(params, "ReplicasPerNodeGroup"),
|
||||
intParam(params, "NumCacheClusters"),
|
||||
boolParam(params, "AutomaticFailoverEnabled"),
|
||||
boolParam(params, "MultiAZEnabled"),
|
||||
replicationGroupSettings(params),
|
||||
parseTags(params)));
|
||||
String result = replicationGroupXml(group);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateReplicationGroup", AwsNamespaces.EC, result)).build();
|
||||
} catch (AwsException e) {
|
||||
@@ -137,6 +156,28 @@ public class ElastiCacheQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer intParam(MultivaluedMap<String, String> params, String name) {
|
||||
String value = params.getFirst(name);
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.valueOf(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"The parameter " + name + " must be an integer.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static Boolean boolParam(MultivaluedMap<String, String> params, String name) {
|
||||
String value = params.getFirst(name);
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return Boolean.parseBoolean(value.trim());
|
||||
}
|
||||
|
||||
|
||||
private Response handleDescribeReplicationGroups(MultivaluedMap<String, String> params) {
|
||||
String filterId = params.getFirst("ReplicationGroupId");
|
||||
try {
|
||||
@@ -295,12 +336,22 @@ public class ElastiCacheQueryHandler {
|
||||
|
||||
private Response handleDescribeCacheClusters(MultivaluedMap<String, String> params) {
|
||||
String filterId = params.getFirst("CacheClusterId");
|
||||
boolean showNodeInfo = "true".equalsIgnoreCase(params.getFirst("ShowCacheNodeInfo"));
|
||||
try {
|
||||
Collection<CacheCluster> clusterList = memcachedService.listCacheClusters(filterId);
|
||||
List<ElastiCacheService.MemberCacheCluster> members = service.listMemberCacheClusters(filterId);
|
||||
Collection<CacheCluster> clusterList;
|
||||
if (filterId != null && !filterId.isBlank() && !members.isEmpty()) {
|
||||
clusterList = List.of();
|
||||
} else {
|
||||
clusterList = memcachedService.listCacheClusters(filterId);
|
||||
}
|
||||
var xml = new XmlBuilder().start("CacheClusters");
|
||||
for (CacheCluster c : clusterList) {
|
||||
xml.raw(cacheClusterXml(c));
|
||||
}
|
||||
for (ElastiCacheService.MemberCacheCluster member : members) {
|
||||
xml.raw(memberCacheClusterXml(member, showNodeInfo));
|
||||
}
|
||||
xml.end("CacheClusters").start("Marker").end("Marker");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeCacheClusters", AwsNamespaces.EC, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
@@ -308,6 +359,63 @@ public class ElastiCacheQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private String memberCacheClusterXml(ElastiCacheService.MemberCacheCluster member, boolean showNodeInfo) {
|
||||
ReplicationGroup g = member.group();
|
||||
boolean authTokenEnabled = g.getAuthMode() == AuthMode.PASSWORD;
|
||||
var xml = new XmlBuilder()
|
||||
.start("CacheCluster")
|
||||
.elem("CacheClusterId", member.cacheClusterId())
|
||||
.elem("CacheClusterStatus", memberCacheClusterStatus(g))
|
||||
.elem("NumCacheNodes", 1L)
|
||||
.elem("ReplicationGroupId", g.getReplicationGroupId())
|
||||
.elem("AutoMinorVersionUpgrade", true)
|
||||
.elem("AuthTokenEnabled", authTokenEnabled)
|
||||
.elem("TransitEncryptionEnabled", authTokenEnabled)
|
||||
.elem("AtRestEncryptionEnabled", false);
|
||||
if (g.getEngine() != null) {
|
||||
xml.elem("Engine", g.getEngine());
|
||||
}
|
||||
if (g.getEngineVersion() != null) {
|
||||
xml.elem("EngineVersion", g.getEngineVersion());
|
||||
}
|
||||
if (g.getCacheNodeType() != null) {
|
||||
xml.elem("CacheNodeType", g.getCacheNodeType());
|
||||
}
|
||||
if (g.getCacheParameterGroupName() != null) {
|
||||
xml.start("CacheParameterGroup")
|
||||
.elem("CacheParameterGroupName", g.getCacheParameterGroupName())
|
||||
.elem("ParameterApplyStatus", "in-sync")
|
||||
.end("CacheParameterGroup");
|
||||
}
|
||||
if (g.getCacheSubnetGroupName() != null) {
|
||||
xml.elem("CacheSubnetGroupName", g.getCacheSubnetGroupName());
|
||||
}
|
||||
if (showNodeInfo && g.getConfigurationEndpoint() != null) {
|
||||
xml.start("CacheNodes")
|
||||
.start("CacheNode")
|
||||
.elem("CacheNodeId", "0001")
|
||||
.elem("CacheNodeStatus", "available")
|
||||
.start("Endpoint")
|
||||
.elem("Address", g.getConfigurationEndpoint().address())
|
||||
.elem("Port", (long) member.port())
|
||||
.end("Endpoint")
|
||||
.end("CacheNode")
|
||||
.end("CacheNodes");
|
||||
}
|
||||
return xml.end("CacheCluster").build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Members mirror the group's status, except {@code create-failed}: that value is only legal
|
||||
* on ReplicationGroup.Status, so members report the documented {@code restore-failed}.
|
||||
*/
|
||||
private static String memberCacheClusterStatus(ReplicationGroup g) {
|
||||
if (g.getStatus() == ReplicationGroupStatus.CREATE_FAILED) {
|
||||
return "restore-failed";
|
||||
}
|
||||
return g.getStatus().wireName();
|
||||
}
|
||||
|
||||
private Response handleDeleteCacheCluster(MultivaluedMap<String, String> params) {
|
||||
String clusterId = params.getFirst("CacheClusterId");
|
||||
if (clusterId == null || clusterId.isBlank()) {
|
||||
@@ -640,26 +748,46 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
|
||||
private String replicationGroupXml(ReplicationGroup g) {
|
||||
Endpoint ep = g.getConfigurationEndpoint();
|
||||
boolean authTokenEnabled = g.getAuthMode() == AuthMode.PASSWORD;
|
||||
List<ElastiCacheService.MemberCacheCluster> members = service.memberCacheClusters(g);
|
||||
var xml = new XmlBuilder()
|
||||
.start("ReplicationGroup")
|
||||
.elem("ReplicationGroupId", g.getReplicationGroupId())
|
||||
.elem("Description", g.getDescription())
|
||||
.elem("Status", g.getStatus().name().toLowerCase())
|
||||
.elem("Status", g.getStatus().wireName())
|
||||
.elem("AuthTokenEnabled", authTokenEnabled)
|
||||
.elem("TransitEncryptionEnabled", authTokenEnabled)
|
||||
.elem("AtRestEncryptionEnabled", g.isAtRestEncryptionEnabled())
|
||||
.elem("ClusterEnabled", false)
|
||||
.elem("MultiAZ", "disabled")
|
||||
.elem("AutomaticFailover", "disabled")
|
||||
.elem("ClusterEnabled", g.isClusterEnabled())
|
||||
.elem("ClusterMode", g.isClusterEnabled() ? "enabled" : "disabled")
|
||||
.elem("MultiAZ", g.isMultiAzEnabled() ? "enabled" : "disabled")
|
||||
.elem("AutomaticFailover", g.isAutomaticFailoverEnabled() ? "enabled" : "disabled")
|
||||
.elem("SnapshotRetentionLimit", (long) g.getSnapshotRetentionLimit());
|
||||
xml.elem("SnapshotWindow", g.getSnapshotWindow() != null
|
||||
? g.getSnapshotWindow() : ReplicationGroupSettings.DEFAULT_SNAPSHOT_WINDOW);
|
||||
if (g.getKmsKeyId() != null) {
|
||||
xml.elem("KmsKeyId", g.getKmsKeyId());
|
||||
}
|
||||
if (g.getEngine() != null) {
|
||||
xml.elem("Engine", g.getEngine());
|
||||
}
|
||||
if (g.getCacheNodeType() != null) {
|
||||
xml.elem("CacheNodeType", g.getCacheNodeType());
|
||||
}
|
||||
if (g.getArn() != null) {
|
||||
xml.elem("ARN", g.getArn());
|
||||
}
|
||||
xml.start("MemberClusters");
|
||||
for (ElastiCacheService.MemberCacheCluster member : members) {
|
||||
xml.elem("ClusterId", member.cacheClusterId());
|
||||
}
|
||||
xml.end("MemberClusters");
|
||||
xml.start("NodeGroups");
|
||||
if (g.isClusterEnabled() && !g.getClusterNodes().isEmpty()) {
|
||||
appendClusterModeNodeGroups(xml, g);
|
||||
} else {
|
||||
appendSingleNodeGroup(xml, g, members, ep);
|
||||
}
|
||||
xml.end("NodeGroups");
|
||||
if (ep != null) {
|
||||
xml.start("ConfigurationEndpoint")
|
||||
.elem("Address", ep.address())
|
||||
@@ -669,6 +797,60 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
|
||||
return xml.end("ReplicationGroup").build();
|
||||
}
|
||||
|
||||
private static void appendClusterModeNodeGroups(XmlBuilder xml, ReplicationGroup g) {
|
||||
Map<String, List<ClusterNode>> byNodeGroup = new LinkedHashMap<>();
|
||||
for (ClusterNode node : g.getClusterNodes()) {
|
||||
byNodeGroup.computeIfAbsent(node.getNodeGroupId(), key -> new ArrayList<>()).add(node);
|
||||
}
|
||||
byNodeGroup.forEach((nodeGroupId, nodes) -> {
|
||||
xml.start("NodeGroup")
|
||||
.elem("NodeGroupId", nodeGroupId)
|
||||
.elem("Status", "available")
|
||||
.elem("Slots", nodes.getFirst().getSlots())
|
||||
.start("NodeGroupMembers");
|
||||
for (ClusterNode node : nodes) {
|
||||
xml.start("NodeGroupMember")
|
||||
.elem("CacheClusterId", node.getMemberClusterId())
|
||||
.elem("CacheNodeId", "0001")
|
||||
.end("NodeGroupMember");
|
||||
}
|
||||
xml.end("NodeGroupMembers").end("NodeGroup");
|
||||
});
|
||||
}
|
||||
|
||||
private static void appendSingleNodeGroup(XmlBuilder xml, ReplicationGroup g,
|
||||
List<ElastiCacheService.MemberCacheCluster> members,
|
||||
Endpoint ep) {
|
||||
xml.start("NodeGroup")
|
||||
.elem("NodeGroupId", "0001")
|
||||
.elem("Status", "available");
|
||||
if (ep != null) {
|
||||
xml.start("PrimaryEndpoint")
|
||||
.elem("Address", ep.address())
|
||||
.elem("Port", (long) ep.port())
|
||||
.end("PrimaryEndpoint")
|
||||
.start("ReaderEndpoint")
|
||||
.elem("Address", ep.address())
|
||||
.elem("Port", (long) ep.port())
|
||||
.end("ReaderEndpoint");
|
||||
}
|
||||
xml.start("NodeGroupMembers");
|
||||
for (ElastiCacheService.MemberCacheCluster member : members) {
|
||||
xml.start("NodeGroupMember")
|
||||
.elem("CacheClusterId", member.cacheClusterId())
|
||||
.elem("CacheNodeId", "0001")
|
||||
.elem("CurrentRole", member.primary() ? "primary" : "replica");
|
||||
if (ep != null) {
|
||||
xml.start("ReadEndpoint")
|
||||
.elem("Address", ep.address())
|
||||
.elem("Port", (long) member.port())
|
||||
.end("ReadEndpoint");
|
||||
}
|
||||
xml.end("NodeGroupMember");
|
||||
}
|
||||
xml.end("NodeGroupMembers").end("NodeGroup");
|
||||
}
|
||||
|
||||
private String userXml(ElastiCacheUser u) {
|
||||
String authType = switch (u.getAuthMode()) {
|
||||
case IAM -> "iam";
|
||||
|
||||
+506
-45
@@ -12,9 +12,11 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ValkeyClusterFormation;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.CacheParameterGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.CacheSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
|
||||
@@ -26,6 +28,9 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -37,6 +42,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -55,6 +61,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
private final StorageBackend<String, CacheSubnetGroup> subnetGroups;
|
||||
private final ElastiCacheContainerManager containerManager;
|
||||
private final ElastiCacheProxyManager proxyManager;
|
||||
private final ValkeyClusterFormation clusterFormation;
|
||||
private final EmulatorConfig config;
|
||||
private final KmsService kmsService;
|
||||
private final Ec2Service ec2Service;
|
||||
@@ -66,6 +73,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
@Inject
|
||||
public ElastiCacheService(ElastiCacheContainerManager containerManager,
|
||||
ElastiCacheProxyManager proxyManager,
|
||||
ValkeyClusterFormation clusterFormation,
|
||||
StorageFactory storageFactory,
|
||||
EmulatorConfig config,
|
||||
Ec2Service ec2Service,
|
||||
@@ -74,6 +82,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
this.kmsService = kmsService;
|
||||
this.containerManager = containerManager;
|
||||
this.proxyManager = proxyManager;
|
||||
this.clusterFormation = clusterFormation;
|
||||
this.config = config;
|
||||
this.ec2Service = ec2Service;
|
||||
this.regionResolver = regionResolver;
|
||||
@@ -87,6 +96,31 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
new TypeReference<Map<String, CacheSubnetGroup>>() {});
|
||||
}
|
||||
|
||||
/**
|
||||
* The CreateReplicationGroup parameters floci models. Anything unset falls back to the
|
||||
* defaults a bare create has always had: one non-cluster node behind one proxy port.
|
||||
*/
|
||||
public record CreateReplicationGroupRequest(
|
||||
String replicationGroupId,
|
||||
String description,
|
||||
AuthMode authMode,
|
||||
String authToken,
|
||||
String region,
|
||||
String engine,
|
||||
String engineVersion,
|
||||
String cacheNodeType,
|
||||
String cacheParameterGroupName,
|
||||
String cacheSubnetGroupName,
|
||||
String clusterMode,
|
||||
Integer numNodeGroups,
|
||||
Integer replicasPerNodeGroup,
|
||||
Integer numCacheClusters,
|
||||
Boolean automaticFailoverEnabled,
|
||||
Boolean multiAzEnabled,
|
||||
ReplicationGroupSettings settings,
|
||||
Map<String, String> tags) {
|
||||
}
|
||||
|
||||
public ReplicationGroup createReplicationGroup(String groupId, String description,
|
||||
AuthMode authMode, String authToken, String region) {
|
||||
return createReplicationGroup(groupId, description, authMode, authToken, region,
|
||||
@@ -97,10 +131,19 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
AuthMode authMode, String authToken, String region,
|
||||
ReplicationGroupSettings settings,
|
||||
Map<String, String> tags) {
|
||||
return createReplicationGroup(new CreateReplicationGroupRequest(groupId, description,
|
||||
authMode, authToken, region, null, null, null, null, null, null,
|
||||
null, null, null, null, null, settings, tags));
|
||||
}
|
||||
|
||||
public ReplicationGroup createReplicationGroup(CreateReplicationGroupRequest request) {
|
||||
String groupId = request.replicationGroupId();
|
||||
ReplicationGroupSettings settings = request.settings() != null
|
||||
? request.settings() : ReplicationGroupSettings.defaults();
|
||||
settings.validate();
|
||||
// resolved with the other validations, before a port is taken or a container started
|
||||
ReplicationGroupSettings resolvedSettings =
|
||||
settings.withKmsKeyId(resolveKmsKeyArn(settings.kmsKeyId(), region));
|
||||
settings.withKmsKeyId(resolveKmsKeyArn(settings.kmsKeyId(), request.region()));
|
||||
if (groups.get(groupId).isPresent()) {
|
||||
throw new AwsException("ReplicationGroupAlreadyExistsFault",
|
||||
"Replication group " + groupId + " already exists.", 400);
|
||||
@@ -113,50 +156,395 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
|
||||
try {
|
||||
int proxyPort = allocateProxyPort();
|
||||
String image = config.services().elasticache().defaultImage();
|
||||
|
||||
LOG.infov("Creating replication group {0} with authMode={1} on proxy port {2}",
|
||||
groupId, authMode, String.valueOf(proxyPort));
|
||||
|
||||
ElastiCacheContainerHandle handle = null;
|
||||
try {
|
||||
handle = containerManager.start(groupId, image);
|
||||
|
||||
String endpointHost = resolveEndpointHost();
|
||||
Endpoint endpoint = new Endpoint(endpointHost, proxyPort);
|
||||
ReplicationGroup group = new ReplicationGroup(
|
||||
groupId, description, ReplicationGroupStatus.AVAILABLE,
|
||||
authMode, endpoint, Instant.now(), proxyPort);
|
||||
group.setContainerId(handle.getContainerId());
|
||||
group.setContainerHost(handle.getHost());
|
||||
group.setContainerPort(handle.getPort());
|
||||
group.setAuthToken(authToken);
|
||||
group.setArn(regionResolver.buildArn("elasticache", region, "replicationgroup:" + groupId));
|
||||
group.setRegion(region);
|
||||
group.setSnapshotWindow(ReplicationGroupSettings.DEFAULT_SNAPSHOT_WINDOW);
|
||||
resolvedSettings.applyTo(group);
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
group.setTags(new LinkedHashMap<>(tags));
|
||||
}
|
||||
|
||||
proxyManager.startProxy(groupId, authMode, proxyPort,
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, password) -> validatePassword(groupId, username, password));
|
||||
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Replication group {0} created, endpoint={1}:{2}", groupId, endpointHost, String.valueOf(proxyPort));
|
||||
return group;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Replication group {0} provisioning failed, rolling back: {1}", groupId, e.getMessage());
|
||||
rollbackReplicationGroup(groupId, handle, proxyPort);
|
||||
throw e;
|
||||
if (resolveClusterEnabled(request)) {
|
||||
return provisionClusterModeGroup(request, resolvedSettings);
|
||||
}
|
||||
return provisionSingleNodeGroup(request, resolvedSettings);
|
||||
} finally {
|
||||
provisioningGroupIds.remove(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
private ReplicationGroup provisionSingleNodeGroup(CreateReplicationGroupRequest request,
|
||||
ReplicationGroupSettings resolvedSettings) {
|
||||
String groupId = request.replicationGroupId();
|
||||
AuthMode authMode = request.authMode();
|
||||
int proxyPort = allocateProxyPort();
|
||||
String image = config.services().elasticache().defaultImage();
|
||||
|
||||
LOG.infov("Creating replication group {0} with authMode={1} on proxy port {2}",
|
||||
groupId, authMode, String.valueOf(proxyPort));
|
||||
|
||||
ElastiCacheContainerHandle handle = null;
|
||||
try {
|
||||
handle = containerManager.start(groupId, image);
|
||||
|
||||
String endpointHost = resolveEndpointHost();
|
||||
Endpoint endpoint = new Endpoint(endpointHost, proxyPort);
|
||||
ReplicationGroup group = new ReplicationGroup(
|
||||
groupId, request.description(), ReplicationGroupStatus.AVAILABLE,
|
||||
authMode, endpoint, Instant.now(), proxyPort);
|
||||
group.setContainerId(handle.getContainerId());
|
||||
group.setContainerHost(handle.getHost());
|
||||
group.setContainerPort(handle.getPort());
|
||||
group.setAuthToken(request.authToken());
|
||||
group.setArn(regionResolver.buildArn("elasticache", request.region(),
|
||||
"replicationgroup:" + groupId));
|
||||
group.setRegion(request.region());
|
||||
group.setNumCacheClusters(request.numCacheClusters() != null
|
||||
? validateRange("NumCacheClusters", request.numCacheClusters(), 1, 6)
|
||||
: 1);
|
||||
applyCommonAttributes(group, request, resolvedSettings);
|
||||
|
||||
proxyManager.startProxy(groupId, authMode, proxyPort,
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, password) -> validatePassword(groupId, username, password));
|
||||
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Replication group {0} created, endpoint={1}:{2}", groupId, endpointHost, String.valueOf(proxyPort));
|
||||
return group;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Replication group {0} provisioning failed, rolling back: {1}", groupId, e.getMessage());
|
||||
rollbackReplicationGroup(groupId, handle, proxyPort);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private ReplicationGroup provisionClusterModeGroup(CreateReplicationGroupRequest request,
|
||||
ReplicationGroupSettings resolvedSettings) {
|
||||
String groupId = request.replicationGroupId();
|
||||
AuthMode authMode = request.authMode();
|
||||
int numNodeGroups = request.numNodeGroups() != null
|
||||
? validateNumNodeGroups(request.numNodeGroups())
|
||||
: 1;
|
||||
int replicasPerNodeGroup = request.replicasPerNodeGroup() != null
|
||||
? validateRange("ReplicasPerNodeGroup", request.replicasPerNodeGroup(), 0, 5)
|
||||
: 0;
|
||||
String image = config.services().elasticache().defaultImage();
|
||||
String endpointHost = resolveClusterAnnounceHost();
|
||||
String announceIp = resolveAnnounceIp(endpointHost);
|
||||
|
||||
LOG.infov("Creating cluster-mode replication group {0} with {1} node group(s), {2} replica(s) each",
|
||||
groupId, String.valueOf(numNodeGroups), String.valueOf(replicasPerNodeGroup));
|
||||
|
||||
List<ClusterNode> nodes = new ArrayList<>();
|
||||
List<ElastiCacheContainerHandle> handles = new ArrayList<>();
|
||||
List<String> startedProxyKeys = new ArrayList<>();
|
||||
String inFlightMemberId = null;
|
||||
try {
|
||||
for (int shard = 0; shard < numNodeGroups; shard++) {
|
||||
String nodeGroupId = String.format("%04d", shard + 1);
|
||||
int[] slots = ValkeyClusterFormation.slotRange(shard, numNodeGroups);
|
||||
for (int member = 0; member <= replicasPerNodeGroup; member++) {
|
||||
String memberId = groupId + "-" + nodeGroupId + "-" + String.format("%03d", member + 1);
|
||||
nodes.add(new ClusterNode(memberId, nodeGroupId, member == 0,
|
||||
allocateProxyPort(), slots[0] + "-" + slots[1]));
|
||||
}
|
||||
}
|
||||
|
||||
List<ValkeyClusterFormation.Node> formationNodes = new ArrayList<>(nodes.size());
|
||||
for (ClusterNode node : nodes) {
|
||||
inFlightMemberId = node.getMemberClusterId();
|
||||
ElastiCacheContainerHandle handle = containerManager.start(
|
||||
node.getMemberClusterId(), image,
|
||||
clusterNodeFlags(endpointHost, announceIp, node.getProxyPort()));
|
||||
inFlightMemberId = null;
|
||||
handles.add(handle);
|
||||
node.setContainerId(handle.getContainerId());
|
||||
node.setContainerHost(handle.getHost());
|
||||
node.setContainerPort(handle.getPort());
|
||||
String networkIp = handle.getNetworkIp() != null ? handle.getNetworkIp() : handle.getHost();
|
||||
formationNodes.add(new ValkeyClusterFormation.Node(
|
||||
handle.getHost(), handle.getPort(), networkIp,
|
||||
Integer.parseInt(node.getNodeGroupId()) - 1, node.isPrimary()));
|
||||
}
|
||||
|
||||
clusterFormation.form(groupId, formationNodes, numNodeGroups);
|
||||
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
ClusterNode node = nodes.get(i);
|
||||
ElastiCacheContainerHandle handle = handles.get(i);
|
||||
proxyManager.startProxy(node.getMemberClusterId(), authMode, node.getProxyPort(),
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, password) -> validatePassword(groupId, username, password));
|
||||
startedProxyKeys.add(node.getMemberClusterId());
|
||||
}
|
||||
|
||||
Endpoint configurationEndpoint = new Endpoint(endpointHost, nodes.getFirst().getProxyPort());
|
||||
ReplicationGroup group = new ReplicationGroup(
|
||||
groupId, request.description(), ReplicationGroupStatus.AVAILABLE,
|
||||
authMode, configurationEndpoint, Instant.now(), nodes.getFirst().getProxyPort());
|
||||
group.setAuthToken(request.authToken());
|
||||
group.setArn(regionResolver.buildArn("elasticache", request.region(),
|
||||
"replicationgroup:" + groupId));
|
||||
group.setRegion(request.region());
|
||||
group.setClusterEnabled(true);
|
||||
group.setNumNodeGroups(numNodeGroups);
|
||||
group.setReplicasPerNodeGroup(replicasPerNodeGroup);
|
||||
group.setNumCacheClusters(nodes.size());
|
||||
group.setClusterNodes(nodes);
|
||||
applyCommonAttributes(group, request, resolvedSettings);
|
||||
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Cluster-mode replication group {0} created, configuration endpoint={1}:{2}",
|
||||
groupId, endpointHost, String.valueOf(configurationEndpoint.port()));
|
||||
return group;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Cluster-mode replication group {0} provisioning failed, rolling back: {1}",
|
||||
groupId, e.getMessage());
|
||||
rollbackClusterModeGroup(groupId, startedProxyKeys, handles, inFlightMemberId,
|
||||
nodes.stream().map(ClusterNode::getProxyPort).toList());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void applyCommonAttributes(ReplicationGroup group, CreateReplicationGroupRequest request,
|
||||
ReplicationGroupSettings resolvedSettings) {
|
||||
group.setEngine(request.engine() != null && !request.engine().isBlank()
|
||||
? normalizeEngine(request.engine())
|
||||
: defaultEngineForImage());
|
||||
group.setEngineVersion(request.engineVersion() != null && !request.engineVersion().isBlank()
|
||||
? request.engineVersion()
|
||||
: ("valkey".equals(group.getEngine()) ? "8.1" : "7.1"));
|
||||
group.setCacheNodeType(request.cacheNodeType() != null && !request.cacheNodeType().isBlank()
|
||||
? request.cacheNodeType()
|
||||
: "cache.t4g.micro");
|
||||
group.setCacheParameterGroupName(request.cacheParameterGroupName());
|
||||
group.setCacheSubnetGroupName(request.cacheSubnetGroupName());
|
||||
group.setAutomaticFailoverEnabled(Boolean.TRUE.equals(request.automaticFailoverEnabled()));
|
||||
group.setMultiAzEnabled(Boolean.TRUE.equals(request.multiAzEnabled()));
|
||||
group.setSnapshotWindow(ReplicationGroupSettings.DEFAULT_SNAPSHOT_WINDOW);
|
||||
resolvedSettings.applyTo(group);
|
||||
if (request.tags() != null && !request.tags().isEmpty()) {
|
||||
group.setTags(new LinkedHashMap<>(request.tags()));
|
||||
}
|
||||
}
|
||||
|
||||
private String defaultEngineForImage() {
|
||||
String image = config.services().elasticache().defaultImage();
|
||||
return image != null && image.contains("valkey") ? "valkey" : "redis";
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster mode follows AWS's signal — the parameter group — plus the request shapes that
|
||||
* imply it: an explicit ClusterMode, or more than one node group. ClusterMode
|
||||
* {@code compatible} — the mid-migration state — is deliberately not modelled; it enables
|
||||
* cluster mode only when one of the other signals also does.
|
||||
*/
|
||||
private boolean resolveClusterEnabled(CreateReplicationGroupRequest request) {
|
||||
if ("enabled".equalsIgnoreCase(request.clusterMode())) {
|
||||
return true;
|
||||
}
|
||||
String parameterGroupName = request.cacheParameterGroupName();
|
||||
if (parameterGroupName != null) {
|
||||
if (parameterGroupName.endsWith(".cluster.on")) {
|
||||
return true;
|
||||
}
|
||||
boolean customClusterGroup = findParameterGroup(parameterGroupName)
|
||||
.map(group -> "yes".equalsIgnoreCase(group.getParameters().get("cluster-enabled")))
|
||||
.orElse(false);
|
||||
if (customClusterGroup) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return request.numNodeGroups() != null && request.numNodeGroups() > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nodes announce the cluster announce hostname as their preferred endpoint, so MOVED/ASK
|
||||
* redirects and CLUSTER SLOTS hand clients the exact name floci reports as the configuration
|
||||
* endpoint — how (or whether) that name resolves inside floci's own container is irrelevant.
|
||||
* The best-effort IPv4 stays announced for consumers that read the address fields instead.
|
||||
*/
|
||||
private static List<String> clusterNodeFlags(String endpointHost, String announceIp, int proxyPort) {
|
||||
return List.of(
|
||||
"--cluster-enabled", "yes",
|
||||
"--cluster-announce-hostname", endpointHost,
|
||||
"--cluster-preferred-endpoint-type", "hostname",
|
||||
"--cluster-announce-client-ipv4", announceIp,
|
||||
"--cluster-announce-port", String.valueOf(proxyPort),
|
||||
"--cluster-announce-bus-port", "16379");
|
||||
}
|
||||
|
||||
private static String resolveAnnounceIp(String endpointHost) {
|
||||
try {
|
||||
for (InetAddress address : InetAddress.getAllByName(endpointHost)) {
|
||||
if (address instanceof Inet4Address) {
|
||||
return address.getHostAddress();
|
||||
}
|
||||
}
|
||||
} catch (UnknownHostException e) {
|
||||
LOG.warnv("Could not resolve {0} to an IPv4 for cluster announce, using 127.0.0.1: {1}",
|
||||
endpointHost, e.getMessage());
|
||||
}
|
||||
return "127.0.0.1";
|
||||
}
|
||||
|
||||
private static int validateRange(String parameterName, int value, int min, int max) {
|
||||
if (value < min || value > max) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
parameterName + " must be between " + min + " and " + max + ".", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** 500 is AWS's raised NumNodeGroups quota (the default is 90; 500 with a limit increase). */
|
||||
private static final int MAX_NODE_GROUPS = 500;
|
||||
|
||||
private static int validateNumNodeGroups(int value) {
|
||||
if (value > MAX_NODE_GROUPS) {
|
||||
throw new AwsException("NodeGroupsPerReplicationGroupQuotaExceeded",
|
||||
"The request cannot be processed because it would exceed the maximum allowed"
|
||||
+ " number of node groups (shards) in a single replication group."
|
||||
+ " The maximum is " + MAX_NODE_GROUPS + ".", 400);
|
||||
}
|
||||
return validateRange("NumNodeGroups", value, 1, MAX_NODE_GROUPS);
|
||||
}
|
||||
|
||||
private void rollbackClusterModeGroup(String groupId, List<String> startedProxyKeys,
|
||||
List<ElastiCacheContainerHandle> handles,
|
||||
String inFlightMemberId, Collection<Integer> proxyPorts) {
|
||||
for (String proxyKey : startedProxyKeys) {
|
||||
try {
|
||||
proxyManager.stopProxy(proxyKey);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error stopping proxy {0} during rollback of group {1}: {2}",
|
||||
proxyKey, groupId, e.getMessage());
|
||||
}
|
||||
}
|
||||
for (ElastiCacheContainerHandle handle : handles) {
|
||||
try {
|
||||
containerManager.stop(handle);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error stopping container {0} during rollback of group {1}: {2}",
|
||||
handle.getContainerId(), groupId, e.getMessage());
|
||||
}
|
||||
}
|
||||
if (inFlightMemberId != null) {
|
||||
try {
|
||||
containerManager.stopByGroupId(inFlightMemberId);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error stopping in-flight container {0} during rollback of group {1}: {2}",
|
||||
inFlightMemberId, groupId, e.getMessage());
|
||||
}
|
||||
}
|
||||
for (int port : proxyPorts) {
|
||||
releaseProxyPort(port);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the data plane back up for cluster-mode groups restored from disk. Invoked from
|
||||
* {@code EmulatorLifecycle} after {@code storageFactory.loadAll()}, alongside the other
|
||||
* services that restore persisted runtime. Only topology survives a restart — containers,
|
||||
* proxies and port reservations are process-local — so each group is re-provisioned from
|
||||
* its persisted node list, and a group whose data plane cannot come back is reported
|
||||
* {@code create-failed} instead of available. Cluster-mode-disabled groups are deliberately
|
||||
* out of scope: they keep their pre-existing behaviour of reporting available after a
|
||||
* restart without a restored runtime.
|
||||
*
|
||||
* <p>Container restarts and cluster formation can take a readiness timeout and a formation
|
||||
* timeout per group, so the data-plane work runs in the background and must not delay
|
||||
* emulator readiness. Groups are marked {@code creating} synchronously — each node's proxy
|
||||
* port is reserved at the same time, before any request can claim it — and flip to
|
||||
* {@code available} or {@code create-failed} as their restoration finishes.
|
||||
*/
|
||||
public CompletableFuture<Void> restorePersistedRuntime() {
|
||||
List<ReplicationGroup> toRestore = new ArrayList<>();
|
||||
for (ReplicationGroup group : groups.scan(k -> true)) {
|
||||
if (!group.isClusterEnabled() || group.getClusterNodes().isEmpty()
|
||||
|| group.getStatus() == ReplicationGroupStatus.DELETING) {
|
||||
continue;
|
||||
}
|
||||
List<Integer> reserved = new ArrayList<>();
|
||||
try {
|
||||
for (ClusterNode node : group.getClusterNodes()) {
|
||||
node.setProxyPort(reserveOrAllocateProxyPort(node.getProxyPort()));
|
||||
reserved.add(node.getProxyPort());
|
||||
}
|
||||
group.setStatus(ReplicationGroupStatus.CREATING);
|
||||
toRestore.add(group);
|
||||
} catch (RuntimeException e) {
|
||||
reserved.forEach(this::releaseProxyPort);
|
||||
group.setStatus(ReplicationGroupStatus.CREATE_FAILED);
|
||||
group.setConfigurationEndpoint(null);
|
||||
LOG.warnv(e, "Failed to restore cluster-mode replication group {0}",
|
||||
group.getReplicationGroupId());
|
||||
}
|
||||
groups.put(group.getReplicationGroupId(), group);
|
||||
}
|
||||
if (toRestore.isEmpty()) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
LOG.infov("Restoring {0} cluster-mode replication group(s) in the background",
|
||||
String.valueOf(toRestore.size()));
|
||||
return CompletableFuture.runAsync(() -> toRestore.forEach(this::restoreClusterModeGroup));
|
||||
}
|
||||
|
||||
private void restoreClusterModeGroup(ReplicationGroup group) {
|
||||
String groupId = group.getReplicationGroupId();
|
||||
String image = config.services().elasticache().defaultImage();
|
||||
String endpointHost = resolveClusterAnnounceHost();
|
||||
String announceIp = resolveAnnounceIp(endpointHost);
|
||||
List<ClusterNode> nodes = group.getClusterNodes();
|
||||
|
||||
List<ElastiCacheContainerHandle> handles = new ArrayList<>();
|
||||
List<String> startedProxyKeys = new ArrayList<>();
|
||||
List<Integer> reservedPorts = nodes.stream().map(ClusterNode::getProxyPort).toList();
|
||||
String inFlightMemberId = null;
|
||||
try {
|
||||
List<ValkeyClusterFormation.Node> formationNodes = new ArrayList<>(nodes.size());
|
||||
for (ClusterNode node : nodes) {
|
||||
inFlightMemberId = node.getMemberClusterId();
|
||||
ElastiCacheContainerHandle handle = containerManager.start(
|
||||
node.getMemberClusterId(), image,
|
||||
clusterNodeFlags(endpointHost, announceIp, node.getProxyPort()));
|
||||
inFlightMemberId = null;
|
||||
handles.add(handle);
|
||||
node.setContainerId(handle.getContainerId());
|
||||
node.setContainerHost(handle.getHost());
|
||||
node.setContainerPort(handle.getPort());
|
||||
String networkIp = handle.getNetworkIp() != null ? handle.getNetworkIp() : handle.getHost();
|
||||
formationNodes.add(new ValkeyClusterFormation.Node(
|
||||
handle.getHost(), handle.getPort(), networkIp,
|
||||
Integer.parseInt(node.getNodeGroupId()) - 1, node.isPrimary()));
|
||||
}
|
||||
|
||||
clusterFormation.form(groupId, formationNodes, group.getNumNodeGroups());
|
||||
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
ClusterNode node = nodes.get(i);
|
||||
ElastiCacheContainerHandle handle = handles.get(i);
|
||||
proxyManager.startProxy(node.getMemberClusterId(), group.getAuthMode(), node.getProxyPort(),
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, password) -> validatePassword(groupId, username, password));
|
||||
startedProxyKeys.add(node.getMemberClusterId());
|
||||
}
|
||||
|
||||
group.setConfigurationEndpoint(new Endpoint(endpointHost, nodes.getFirst().getProxyPort()));
|
||||
group.setStatus(ReplicationGroupStatus.AVAILABLE);
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Restored cluster-mode replication group {0}: {1} node(s), configuration endpoint={2}:{3}",
|
||||
groupId, String.valueOf(nodes.size()), endpointHost,
|
||||
String.valueOf(group.getConfigurationEndpoint().port()));
|
||||
} catch (RuntimeException e) {
|
||||
rollbackClusterModeGroup(groupId, startedProxyKeys, handles, inFlightMemberId, reservedPorts);
|
||||
for (ClusterNode node : nodes) {
|
||||
node.setContainerId(null);
|
||||
node.setContainerHost(null);
|
||||
node.setContainerPort(0);
|
||||
}
|
||||
group.setStatus(ReplicationGroupStatus.CREATE_FAILED);
|
||||
group.setConfigurationEndpoint(null);
|
||||
try {
|
||||
groups.put(groupId, group);
|
||||
} catch (RuntimeException persistFailure) {
|
||||
e.addSuppressed(persistFailure);
|
||||
}
|
||||
LOG.warnv(e, "Failed to restore cluster-mode replication group {0}", groupId);
|
||||
}
|
||||
}
|
||||
|
||||
private void rollbackReplicationGroup(String groupId, ElastiCacheContainerHandle handle, int proxyPort) {
|
||||
try {
|
||||
if (handle != null) {
|
||||
@@ -206,19 +594,73 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
group.setStatus(ReplicationGroupStatus.DELETING);
|
||||
groups.put(groupId, group);
|
||||
|
||||
proxyManager.stopProxy(groupId);
|
||||
if (group.isClusterEnabled() && !group.getClusterNodes().isEmpty()) {
|
||||
for (ClusterNode node : group.getClusterNodes()) {
|
||||
proxyManager.stopProxy(node.getMemberClusterId());
|
||||
if (node.getContainerId() != null) {
|
||||
containerManager.stop(new ElastiCacheContainerHandle(
|
||||
node.getContainerId(), node.getMemberClusterId(),
|
||||
node.getContainerHost(), node.getContainerPort()));
|
||||
} else {
|
||||
// Transient container fields are lost across a Floci restart; the
|
||||
// deterministic container name still finds the node.
|
||||
containerManager.stopByGroupId(node.getMemberClusterId());
|
||||
}
|
||||
releaseProxyPort(node.getProxyPort());
|
||||
}
|
||||
} else {
|
||||
proxyManager.stopProxy(groupId);
|
||||
|
||||
if (group.getContainerId() != null) {
|
||||
containerManager.stop(new ElastiCacheContainerHandle(
|
||||
group.getContainerId(), groupId, group.getContainerHost(), group.getContainerPort()));
|
||||
if (group.getContainerId() != null) {
|
||||
containerManager.stop(new ElastiCacheContainerHandle(
|
||||
group.getContainerId(), groupId, group.getContainerHost(), group.getContainerPort()));
|
||||
}
|
||||
|
||||
releaseProxyPort(group.getProxyPort());
|
||||
}
|
||||
|
||||
releaseProxyPort(group.getProxyPort());
|
||||
groups.delete(groupId);
|
||||
LOG.infov("Replication group {0} deleted", groupId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A replication-group member viewed as the cache cluster AWS reports it as. The terraform
|
||||
* provider follows {@code MemberClusters} into DescribeCacheClusters, so every member name
|
||||
* a describe hands out must answer there.
|
||||
*/
|
||||
public record MemberCacheCluster(ReplicationGroup group, String cacheClusterId,
|
||||
int port, boolean primary) {}
|
||||
|
||||
public List<MemberCacheCluster> listMemberCacheClusters(String filterClusterId) {
|
||||
List<MemberCacheCluster> members = new ArrayList<>();
|
||||
for (ReplicationGroup group : groups.scan(k -> true)) {
|
||||
for (MemberCacheCluster member : memberCacheClusters(group)) {
|
||||
if (filterClusterId == null || filterClusterId.isBlank()
|
||||
|| filterClusterId.equals(member.cacheClusterId())) {
|
||||
members.add(member);
|
||||
}
|
||||
}
|
||||
}
|
||||
return members;
|
||||
}
|
||||
|
||||
public List<MemberCacheCluster> memberCacheClusters(ReplicationGroup group) {
|
||||
List<MemberCacheCluster> members = new ArrayList<>();
|
||||
if (group.isClusterEnabled() && !group.getClusterNodes().isEmpty()) {
|
||||
for (ClusterNode node : group.getClusterNodes()) {
|
||||
members.add(new MemberCacheCluster(group, node.getMemberClusterId(),
|
||||
node.getProxyPort(), node.isPrimary()));
|
||||
}
|
||||
return members;
|
||||
}
|
||||
for (int i = 1; i <= group.getNumCacheClusters(); i++) {
|
||||
members.add(new MemberCacheCluster(group,
|
||||
group.getReplicationGroupId() + "-" + String.format("%03d", i),
|
||||
group.getProxyPort(), i == 1));
|
||||
}
|
||||
return members;
|
||||
}
|
||||
|
||||
public ReplicationGroup modifyReplicationGroup(String groupId, List<String> userIdsToAdd,
|
||||
List<String> userIdsToRemove) {
|
||||
return modifyReplicationGroup(groupId, userIdsToAdd, userIdsToRemove,
|
||||
@@ -394,6 +836,18 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
return config.hostname().orElse("localhost");
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster-mode groups bake this name into MOVED/ASK redirects and topology responses that
|
||||
* every client must resolve, unlike the plain endpoint host that clients may override —
|
||||
* so a hostname resolvable only inside Floci's Docker network (e.g. a Compose service
|
||||
* name) needs the cluster-announce-hostname override.
|
||||
*/
|
||||
private String resolveClusterAnnounceHost() {
|
||||
return config.services().elasticache().clusterAnnounceHostname()
|
||||
.filter(host -> !host.isBlank())
|
||||
.orElseGet(this::resolveEndpointHost);
|
||||
}
|
||||
|
||||
private int allocateProxyPort() {
|
||||
int base = config.services().elasticache().proxyBasePort();
|
||||
int max = config.services().elasticache().proxyMaxPort();
|
||||
@@ -416,6 +870,13 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
usedPorts.remove(port);
|
||||
}
|
||||
|
||||
private int reserveOrAllocateProxyPort(int persistedPort) {
|
||||
if (persistedPort > 0 && usedPorts.add(persistedPort)) {
|
||||
return persistedPort;
|
||||
}
|
||||
return allocateProxyPort();
|
||||
}
|
||||
|
||||
// ── Cache Subnet Groups ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
+6
@@ -11,6 +11,7 @@ public class ElastiCacheContainerHandle {
|
||||
private final String groupId;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private String networkIp;
|
||||
private Closeable logStream;
|
||||
|
||||
public ElastiCacheContainerHandle(String containerId, String groupId, String host, int port) {
|
||||
@@ -24,6 +25,11 @@ public class ElastiCacheContainerHandle {
|
||||
public String getGroupId() { return groupId; }
|
||||
public String getHost() { return host; }
|
||||
public int getPort() { return port; }
|
||||
|
||||
/** The container's IP on its Docker network — the address sibling containers dial. */
|
||||
public String getNetworkIp() { return networkIp; }
|
||||
public void setNetworkIp(String networkIp) { this.networkIp = networkIp; }
|
||||
|
||||
public Closeable getLogStream() { return logStream; }
|
||||
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
|
||||
}
|
||||
+22
-1
@@ -70,6 +70,15 @@ public class ElastiCacheContainerManager {
|
||||
}
|
||||
|
||||
public ElastiCacheContainerHandle start(String groupId, String image) {
|
||||
return start(groupId, image, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a backend container for the given resource id, appending {@code extraServerFlags}
|
||||
* to the Valkey server command line (via the image's {@code VALKEY_EXTRA_FLAGS} hook).
|
||||
* Cluster-mode nodes use this to pass {@code --cluster-enabled} and announce settings.
|
||||
*/
|
||||
public ElastiCacheContainerHandle start(String groupId, String image, List<String> extraServerFlags) {
|
||||
LOG.infov("Starting ElastiCache backend container for group: {0}", groupId);
|
||||
|
||||
String containerName = containerName(groupId);
|
||||
@@ -77,12 +86,17 @@ public class ElastiCacheContainerManager {
|
||||
// Remove any stale container with the same name
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
|
||||
StringBuilder serverFlags = new StringBuilder("--loglevel verbose");
|
||||
for (String flag : extraServerFlags) {
|
||||
serverFlags.append(' ').append(flag);
|
||||
}
|
||||
|
||||
// Build container spec. Only publish the backend port to the host in
|
||||
// native mode — in Docker mode the JVM reaches the container via its
|
||||
// network IP, no host binding needed.
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv("VALKEY_EXTRA_FLAGS", "--loglevel verbose")
|
||||
.withEnv("VALKEY_EXTRA_FLAGS", serverFlags.toString())
|
||||
.withDockerNetwork(config.services().elasticache().dockerNetwork())
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
@@ -104,6 +118,13 @@ public class ElastiCacheContainerManager {
|
||||
|
||||
ElastiCacheContainerHandle handle = new ElastiCacheContainerHandle(
|
||||
info.containerId(), groupId, endpoint.host(), endpoint.port());
|
||||
try {
|
||||
handle.setNetworkIp(lifecycleManager.resolveContainerNetworkIp(
|
||||
info.containerId(), config.services().elasticache().dockerNetwork().orElse(null)));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not resolve network IP for ElastiCache container {0}: {1}",
|
||||
info.containerId(), e.getMessage());
|
||||
}
|
||||
activeContainers.put(groupId, handle);
|
||||
|
||||
// Attach log streaming
|
||||
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.container;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Forms a Valkey cluster out of freshly started cluster-enabled nodes, the way
|
||||
* {@code valkey-cli --cluster create} does: distinct config epochs, MEET, slot
|
||||
* assignment on the primaries, then REPLICATE for the replicas.
|
||||
*
|
||||
* <p>Commands are issued from the JVM over each node's Floci-reachable endpoint;
|
||||
* the addresses handed to MEET are the nodes' Docker-network IPs, because that is
|
||||
* where the nodes reach <em>each other</em>.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ValkeyClusterFormation {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ValkeyClusterFormation.class);
|
||||
|
||||
private static final int BACKEND_PORT = 6379;
|
||||
private static final int TOTAL_SLOTS = 16384;
|
||||
private static final int CONNECT_TIMEOUT_MS = 5_000;
|
||||
private static final int READ_TIMEOUT_MS = 10_000;
|
||||
private static final long FORMATION_DEADLINE_MS = 60_000;
|
||||
private static final long RETRY_SLEEP_MS = 200;
|
||||
|
||||
/**
|
||||
* One node to join into the cluster.
|
||||
*
|
||||
* @param endpointHost host Floci uses to reach the node
|
||||
* @param endpointPort port Floci uses to reach the node
|
||||
* @param networkIp the node's Docker-network IP, dialled by its peers
|
||||
* @param nodeGroup zero-based shard index
|
||||
* @param primary whether this node holds the shard's slots
|
||||
*/
|
||||
public record Node(String endpointHost, int endpointPort, String networkIp,
|
||||
int nodeGroup, boolean primary) {}
|
||||
|
||||
public void form(String groupId, List<Node> nodes, int numNodeGroups) {
|
||||
long deadline = System.currentTimeMillis() + FORMATION_DEADLINE_MS;
|
||||
List<RespClient> clients = new ArrayList<>(nodes.size());
|
||||
try {
|
||||
for (Node node : nodes) {
|
||||
clients.add(new RespClient(node.endpointHost(), node.endpointPort()));
|
||||
}
|
||||
|
||||
List<String> nodeIds = new ArrayList<>(nodes.size());
|
||||
for (RespClient client : clients) {
|
||||
nodeIds.add(client.callString("CLUSTER", "MYID"));
|
||||
}
|
||||
|
||||
for (int i = 0; i < clients.size(); i++) {
|
||||
try {
|
||||
clients.get(i).callString("CLUSTER", "SET-CONFIG-EPOCH", String.valueOf(i + 1));
|
||||
} catch (RespError e) {
|
||||
LOG.debugv("SET-CONFIG-EPOCH on node {0} of group {1}: {2}",
|
||||
String.valueOf(i), groupId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 1; i < nodes.size(); i++) {
|
||||
clients.getFirst().callString("CLUSTER", "MEET",
|
||||
nodes.get(i).networkIp(), String.valueOf(BACKEND_PORT));
|
||||
}
|
||||
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
Node node = nodes.get(i);
|
||||
if (node.primary()) {
|
||||
int[] range = slotRange(node.nodeGroup(), numNodeGroups);
|
||||
clients.get(i).callString("CLUSTER", "ADDSLOTSRANGE",
|
||||
String.valueOf(range[0]), String.valueOf(range[1]));
|
||||
}
|
||||
}
|
||||
|
||||
awaitKnownNodes(groupId, clients, nodes.size(), deadline);
|
||||
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
Node node = nodes.get(i);
|
||||
if (!node.primary()) {
|
||||
String primaryId = nodeIds.get(primaryIndex(nodes, node.nodeGroup()));
|
||||
replicateWithRetry(groupId, clients.get(i), primaryId, deadline);
|
||||
}
|
||||
}
|
||||
|
||||
awaitClusterOk(groupId, clients, deadline);
|
||||
LOG.infov("Valkey cluster for group {0} formed: {1} shard(s), {2} node(s)",
|
||||
groupId, String.valueOf(numNodeGroups), String.valueOf(nodes.size()));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Cluster formation for group " + groupId + " failed: " + e.getMessage(), e);
|
||||
} finally {
|
||||
clients.forEach(RespClient::closeQuietly);
|
||||
}
|
||||
}
|
||||
|
||||
/** The contiguous slot range served by the given shard, covering all 16384 slots overall. */
|
||||
public static int[] slotRange(int nodeGroup, int numNodeGroups) {
|
||||
int start = nodeGroup * TOTAL_SLOTS / numNodeGroups;
|
||||
int end = (nodeGroup + 1) * TOTAL_SLOTS / numNodeGroups - 1;
|
||||
return new int[] {start, end};
|
||||
}
|
||||
|
||||
private static int primaryIndex(List<Node> nodes, int nodeGroup) {
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
if (nodes.get(i).primary() && nodes.get(i).nodeGroup() == nodeGroup) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("No primary for node group " + nodeGroup);
|
||||
}
|
||||
|
||||
private static void replicateWithRetry(String groupId, RespClient replica,
|
||||
String primaryId, long deadline) throws IOException {
|
||||
while (true) {
|
||||
try {
|
||||
replica.callString("CLUSTER", "REPLICATE", primaryId);
|
||||
return;
|
||||
} catch (RespError e) {
|
||||
// The replica may not have gossiped the primary yet — retry until the deadline.
|
||||
if (System.currentTimeMillis() >= deadline) {
|
||||
throw new RuntimeException("Cluster formation for group " + groupId
|
||||
+ " timed out waiting to replicate " + primaryId + ": " + e.getMessage(), e);
|
||||
}
|
||||
sleep(groupId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void awaitKnownNodes(String groupId, List<RespClient> clients,
|
||||
int expected, long deadline) throws IOException {
|
||||
while (!allMatch(clients, info -> parseInfoField(info, "cluster_known_nodes") >= expected)) {
|
||||
if (System.currentTimeMillis() >= deadline) {
|
||||
throw new RuntimeException("Cluster formation for group " + groupId
|
||||
+ " timed out waiting for all " + expected + " nodes to meet");
|
||||
}
|
||||
sleep(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
private static void awaitClusterOk(String groupId, List<RespClient> clients,
|
||||
long deadline) throws IOException {
|
||||
while (!allMatch(clients, info -> info.contains("cluster_state:ok"))) {
|
||||
if (System.currentTimeMillis() >= deadline) {
|
||||
throw new RuntimeException("Cluster formation for group " + groupId
|
||||
+ " timed out waiting for cluster_state:ok");
|
||||
}
|
||||
sleep(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean allMatch(List<RespClient> clients,
|
||||
java.util.function.Predicate<String> infoPredicate) throws IOException {
|
||||
for (RespClient client : clients) {
|
||||
if (!infoPredicate.test(client.callString("CLUSTER", "INFO"))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static long parseInfoField(String info, String field) {
|
||||
for (String line : info.split("\r?\n")) {
|
||||
if (line.startsWith(field + ":")) {
|
||||
try {
|
||||
return Long.parseLong(line.substring(field.length() + 1).trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static void sleep(String groupId) {
|
||||
try {
|
||||
Thread.sleep(RETRY_SLEEP_MS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted while forming cluster for group " + groupId, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** An {@code -ERR} reply from the server, distinct from transport failures. */
|
||||
static final class RespError extends IOException {
|
||||
RespError(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Minimal RESP2 client: sends one command array, reads one reply. */
|
||||
static final class RespClient implements Closeable {
|
||||
|
||||
private final Socket socket;
|
||||
private final InputStream in;
|
||||
private final OutputStream out;
|
||||
|
||||
RespClient(String host, int port) throws IOException {
|
||||
socket = new Socket();
|
||||
socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
|
||||
socket.setTcpNoDelay(true);
|
||||
socket.setSoTimeout(READ_TIMEOUT_MS);
|
||||
in = socket.getInputStream();
|
||||
out = socket.getOutputStream();
|
||||
}
|
||||
|
||||
String callString(String... args) throws IOException {
|
||||
Object reply = call(args);
|
||||
return reply == null ? null : reply.toString();
|
||||
}
|
||||
|
||||
Object call(String... args) throws IOException {
|
||||
StringBuilder header = new StringBuilder();
|
||||
header.append('*').append(args.length).append("\r\n");
|
||||
out.write(header.toString().getBytes(StandardCharsets.UTF_8));
|
||||
for (String arg : args) {
|
||||
byte[] bytes = arg.getBytes(StandardCharsets.UTF_8);
|
||||
out.write(("$" + bytes.length + "\r\n").getBytes(StandardCharsets.UTF_8));
|
||||
out.write(bytes);
|
||||
out.write('\r');
|
||||
out.write('\n');
|
||||
}
|
||||
out.flush();
|
||||
return readReply();
|
||||
}
|
||||
|
||||
private Object readReply() throws IOException {
|
||||
int type = in.read();
|
||||
if (type == -1) {
|
||||
throw new IOException("Connection closed while awaiting reply");
|
||||
}
|
||||
String line = readLine();
|
||||
return switch (type) {
|
||||
case '+' -> line;
|
||||
case '-' -> throw new RespError(line);
|
||||
case ':' -> Long.parseLong(line);
|
||||
case '$' -> readBulk(Integer.parseInt(line));
|
||||
case '*' -> readArray(Integer.parseInt(line));
|
||||
default -> throw new IOException("Unexpected RESP type: " + (char) type);
|
||||
};
|
||||
}
|
||||
|
||||
private String readBulk(int length) throws IOException {
|
||||
if (length < 0) {
|
||||
return null;
|
||||
}
|
||||
byte[] data = in.readNBytes(length);
|
||||
if (data.length != length) {
|
||||
throw new IOException("Truncated bulk reply");
|
||||
}
|
||||
expectCrLf();
|
||||
return new String(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private List<Object> readArray(int count) throws IOException {
|
||||
if (count < 0) {
|
||||
return null;
|
||||
}
|
||||
List<Object> items = new ArrayList<>(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
items.add(readReply());
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private String readLine() throws IOException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int b;
|
||||
while ((b = in.read()) != -1) {
|
||||
if (b == '\r') {
|
||||
int next = in.read();
|
||||
if (next != '\n') {
|
||||
throw new IOException("Malformed RESP line terminator");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
sb.append((char) b);
|
||||
}
|
||||
throw new IOException("Connection closed mid-line");
|
||||
}
|
||||
|
||||
private void expectCrLf() throws IOException {
|
||||
if (in.read() != '\r' || in.read() != '\n') {
|
||||
throw new IOException("Missing CRLF after bulk reply");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
socket.close();
|
||||
}
|
||||
|
||||
void closeQuietly() {
|
||||
try {
|
||||
close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv("Ignoring close failure for formation connection to {0}: {1}",
|
||||
socket.getRemoteSocketAddress(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* One node of a cluster-mode-enabled replication group: a member cache cluster
|
||||
* backed by its own Valkey container and auth-proxy port.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class ClusterNode {
|
||||
|
||||
private String memberClusterId;
|
||||
private String nodeGroupId;
|
||||
private boolean primary;
|
||||
private int proxyPort;
|
||||
private String slots;
|
||||
|
||||
// Transient fields — not persisted, restored on container restart
|
||||
private transient String containerId;
|
||||
private transient String containerHost;
|
||||
private transient int containerPort;
|
||||
|
||||
public ClusterNode() {}
|
||||
|
||||
public ClusterNode(String memberClusterId, String nodeGroupId, boolean primary,
|
||||
int proxyPort, String slots) {
|
||||
this.memberClusterId = memberClusterId;
|
||||
this.nodeGroupId = nodeGroupId;
|
||||
this.primary = primary;
|
||||
this.proxyPort = proxyPort;
|
||||
this.slots = slots;
|
||||
}
|
||||
|
||||
public String getMemberClusterId() { return memberClusterId; }
|
||||
public void setMemberClusterId(String memberClusterId) { this.memberClusterId = memberClusterId; }
|
||||
|
||||
public String getNodeGroupId() { return nodeGroupId; }
|
||||
public void setNodeGroupId(String nodeGroupId) { this.nodeGroupId = nodeGroupId; }
|
||||
|
||||
public boolean isPrimary() { return primary; }
|
||||
public void setPrimary(boolean primary) { this.primary = primary; }
|
||||
|
||||
public int getProxyPort() { return proxyPort; }
|
||||
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
|
||||
|
||||
public String getSlots() { return slots; }
|
||||
public void setSlots(String slots) { this.slots = slots; }
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public void setContainerId(String containerId) { this.containerId = containerId; }
|
||||
|
||||
public String getContainerHost() { return containerHost; }
|
||||
public void setContainerHost(String containerHost) { this.containerHost = containerHost; }
|
||||
|
||||
public int getContainerPort() { return containerPort; }
|
||||
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
|
||||
}
|
||||
+52
@@ -3,8 +3,10 @@ package io.github.hectorvent.floci.services.elasticache.model;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -27,6 +29,18 @@ public class ReplicationGroup {
|
||||
private int snapshotRetentionLimit;
|
||||
private String snapshotWindow;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
private boolean clusterEnabled;
|
||||
private int numNodeGroups = 1;
|
||||
private int replicasPerNodeGroup;
|
||||
private int numCacheClusters = 1;
|
||||
private String engine;
|
||||
private String engineVersion;
|
||||
private String cacheNodeType;
|
||||
private String cacheParameterGroupName;
|
||||
private String cacheSubnetGroupName;
|
||||
private boolean automaticFailoverEnabled;
|
||||
private boolean multiAzEnabled;
|
||||
private List<ClusterNode> clusterNodes = new ArrayList<>();
|
||||
|
||||
// Transient fields — not persisted, restored on container restart
|
||||
private transient String containerId;
|
||||
@@ -105,4 +119,42 @@ public class ReplicationGroup {
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public boolean isClusterEnabled() { return clusterEnabled; }
|
||||
public void setClusterEnabled(boolean clusterEnabled) { this.clusterEnabled = clusterEnabled; }
|
||||
|
||||
public int getNumNodeGroups() { return numNodeGroups; }
|
||||
public void setNumNodeGroups(int numNodeGroups) { this.numNodeGroups = numNodeGroups; }
|
||||
|
||||
public int getReplicasPerNodeGroup() { return replicasPerNodeGroup; }
|
||||
public void setReplicasPerNodeGroup(int replicasPerNodeGroup) { this.replicasPerNodeGroup = replicasPerNodeGroup; }
|
||||
|
||||
public int getNumCacheClusters() { return numCacheClusters; }
|
||||
public void setNumCacheClusters(int numCacheClusters) { this.numCacheClusters = numCacheClusters; }
|
||||
|
||||
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 String getCacheParameterGroupName() { return cacheParameterGroupName; }
|
||||
public void setCacheParameterGroupName(String cacheParameterGroupName) { this.cacheParameterGroupName = cacheParameterGroupName; }
|
||||
|
||||
public String getCacheSubnetGroupName() { return cacheSubnetGroupName; }
|
||||
public void setCacheSubnetGroupName(String cacheSubnetGroupName) { this.cacheSubnetGroupName = cacheSubnetGroupName; }
|
||||
|
||||
public boolean isAutomaticFailoverEnabled() { return automaticFailoverEnabled; }
|
||||
public void setAutomaticFailoverEnabled(boolean automaticFailoverEnabled) { this.automaticFailoverEnabled = automaticFailoverEnabled; }
|
||||
|
||||
public boolean isMultiAzEnabled() { return multiAzEnabled; }
|
||||
public void setMultiAzEnabled(boolean multiAzEnabled) { this.multiAzEnabled = multiAzEnabled; }
|
||||
|
||||
public List<ClusterNode> getClusterNodes() { return clusterNodes; }
|
||||
public void setClusterNodes(List<ClusterNode> clusterNodes) {
|
||||
this.clusterNodes = clusterNodes != null ? clusterNodes : new ArrayList<>();
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -2,7 +2,14 @@ package io.github.hectorvent.floci.services.elasticache.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
@RegisterForReflection
|
||||
public enum ReplicationGroupStatus {
|
||||
CREATING, AVAILABLE, DELETING
|
||||
CREATING, AVAILABLE, DELETING, CREATE_FAILED;
|
||||
|
||||
/** The status string as AWS reports it, e.g. {@code create-failed}. */
|
||||
public String wireName() {
|
||||
return name().toLowerCase(Locale.ROOT).replace('_', '-');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user