mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(elasticache): add an explicit shell-less backend path for Redis-compatible images (#8642)
* feat(elasticache): add an explicit shell-less backend path for Redis-compatible images
This commit is contained in:
1 parent
e281defa12
commit
b7a95fc920
17 files changed
+1315
-19
No files matched your search
+343
@@ -0,0 +1,343 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.enterprise.inject.spi.CDI;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.bulk;
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.command;
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.containerOf;
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.docker;
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.dockerExit;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The shell-less ElastiCache backend ({@code floci.services.elasticache.shell-less-backend}) against
|
||||
* a real image with no shell and no CLI, pinned by digest in {@link ShellLessBackendProfile}: server
|
||||
* flags as container arguments, snapshot export over RESP and the Docker archive API, restore by
|
||||
* placing the file before the server starts, authentication and ACLs through the proxy, and cleanup
|
||||
* of the containers on delete and on a failed restore.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(ShellLessBackendProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class ElastiCacheShellLessBackendIntegrationTest {
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request";
|
||||
private static final String SOURCE_ID = "it-sl-source";
|
||||
private static final String RESTORED_ID = "it-sl-restored";
|
||||
private static final String TOKEN_ID = "it-sl-token";
|
||||
private static final String RBAC_ID = "it-sl-rbac";
|
||||
private static final String BAD_SEED_ID = "it-sl-bad-seed";
|
||||
private static final String SNAPSHOT_NAME = "it-sl-snap";
|
||||
private static final String TOKEN = "shell-less-group-token";
|
||||
private static final String DEFAULT_USER_ID = "it-sl-default-user";
|
||||
private static final String APP_USER_ID = "it-sl-app-user";
|
||||
private static final String APP_USER_NAME = "it-sl-app";
|
||||
private static final String APP_PASSWORD = "app-secret-123456";
|
||||
private static final int SOCKET_TIMEOUT_MS = 10_000;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
private static int sourcePort;
|
||||
private static int restoredPort;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() throws InterruptedException {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
|
||||
"Docker daemon must be available for ElastiCache integration tests");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
for (String groupId : List.of(RBAC_ID, TOKEN_ID, RESTORED_ID, SOURCE_ID)) {
|
||||
try {
|
||||
request("DeleteReplicationGroup").port(baseUri.getPort()).formParam("ReplicationGroupId", groupId).post("/");
|
||||
} catch (RuntimeException expected) {
|
||||
// Best effort: the group may not exist when a test failed before creating it.
|
||||
}
|
||||
}
|
||||
for (String userId : List.of(APP_USER_ID, DEFAULT_USER_ID)) {
|
||||
try {
|
||||
request("DeleteUser").port(baseUri.getPort()).formParam("UserId", userId).post("/");
|
||||
} catch (RuntimeException expected) {
|
||||
// Best effort, as above.
|
||||
}
|
||||
}
|
||||
try {
|
||||
request("DeleteSnapshot").port(baseUri.getPort()).formParam("SnapshotName", SNAPSHOT_NAME).post("/");
|
||||
} catch (RuntimeException expected) {
|
||||
// Best effort, as above.
|
||||
}
|
||||
try {
|
||||
CDI.current().select(ElastiCacheContainerManager.class).get().stopByGroupId(BAD_SEED_ID);
|
||||
} catch (RuntimeException expected) {
|
||||
// Best effort, as above.
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createGroupOnAnImageWithNoShell() {
|
||||
sourcePort = createGroup(SOURCE_ID, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void theImageReallyHasNoShell() throws Exception {
|
||||
String container = containerOf(SOURCE_ID);
|
||||
assertFalse(container.isEmpty(), "the backend container exists");
|
||||
assertNotEquals(0, dockerExit("exec", container, "sh", "-c", "true"),
|
||||
"the fixture image must have no shell, or the test proves nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void serverFlagsAreDeliveredAsContainerArguments() throws Exception {
|
||||
String container = containerOf(SOURCE_ID);
|
||||
String command = docker("inspect", "--format", "{{json .Config.Cmd}}", container);
|
||||
assertTrue(command.contains("\"--port\",\"6379\""), command);
|
||||
assertTrue(command.contains("\"--protected-mode\",\"no\""), command);
|
||||
assertFalse(command.contains("enable-debug-command"), "DEBUG is not enabled anywhere: " + command);
|
||||
String environment = docker("inspect", "--format", "{{json .Config.Env}}", container);
|
||||
assertFalse(environment.contains("VALKEY_EXTRA_FLAGS"), environment);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void dataIsServedThroughTheProxy() throws Exception {
|
||||
try (Socket socket = open(sourcePort)) {
|
||||
assertEquals("+OK", command(socket, "SET", "snapshot-key", "kept"));
|
||||
assertEquals("kept", bulk(socket, "GET", "snapshot-key"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void snapshotIsExportedAndRestoredBeforeTheServerStarts() throws Exception {
|
||||
request("CreateSnapshot")
|
||||
.formParam("SnapshotName", SNAPSHOT_NAME)
|
||||
.formParam("ReplicationGroupId", SOURCE_ID)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateSnapshotResponse.CreateSnapshotResult.Snapshot.SnapshotStatus", equalTo("available"));
|
||||
// Written after the snapshot: the restored group must not see it.
|
||||
try (Socket socket = open(sourcePort)) {
|
||||
assertEquals("+OK", command(socket, "SET", "later-key", "after"));
|
||||
}
|
||||
|
||||
restoredPort = createGroup(RESTORED_ID, SNAPSHOT_NAME, null);
|
||||
|
||||
try (Socket socket = open(restoredPort)) {
|
||||
assertEquals("kept", bulk(socket, "GET", "snapshot-key"));
|
||||
assertEquals("$-1", command(socket, "GET", "later-key"));
|
||||
}
|
||||
String command = docker("inspect", "--format", "{{json .Config.Cmd}}", containerOf(RESTORED_ID));
|
||||
assertFalse(command.contains("enable-debug-command"), "no DEBUG for a restore: " + command);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void theSourceKeepsItsDataAndItsSnapshotSurvivesTheRestore() throws Exception {
|
||||
try (Socket socket = open(sourcePort)) {
|
||||
assertEquals("after", bulk(socket, "GET", "later-key"));
|
||||
}
|
||||
request("DescribeSnapshots")
|
||||
.formParam("SnapshotName", SNAPSHOT_NAME)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeSnapshotsResponse.DescribeSnapshotsResult.Snapshots.Snapshot.SnapshotStatus",
|
||||
equalTo("available"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void groupAuthTokenIsEnforcedByTheProxy() throws Exception {
|
||||
int port = createGroup(TOKEN_ID, null, TOKEN);
|
||||
try (Socket socket = open(port)) {
|
||||
assertTrue(command(socket, "PING").startsWith("-NOAUTH"));
|
||||
}
|
||||
try (Socket socket = open(port)) {
|
||||
assertEquals("-ERR invalid username-password pair or user is disabled.",
|
||||
command(socket, "AUTH", "wrong-token"));
|
||||
}
|
||||
try (Socket socket = open(port)) {
|
||||
assertEquals("+OK", command(socket, "AUTH", TOKEN));
|
||||
assertEquals("+PONG", command(socket, "PING"));
|
||||
assertEquals("+OK", command(socket, "SET", "token-key", "value"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void commandsAnAccessStringRefusesAreRefusedAndTheRefusalReachesTheClient() throws Exception {
|
||||
int port = createGroup(RBAC_ID, null, null);
|
||||
createUser(DEFAULT_USER_ID, "default", "no-password-required", null, "on ~* +@all");
|
||||
createUser(APP_USER_ID, APP_USER_NAME, "password", APP_PASSWORD, "on ~app:* -@all +get +set +ping");
|
||||
request("ModifyReplicationGroup")
|
||||
.formParam("ReplicationGroupId", RBAC_ID)
|
||||
.formParam("UserGroupIdsToAdd.member.1", DEFAULT_USER_ID)
|
||||
.formParam("UserGroupIdsToAdd.member.2", APP_USER_ID)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
try (Socket socket = open(port)) {
|
||||
assertEquals("-ERR invalid username-password pair or user is disabled.",
|
||||
command(socket, "AUTH", APP_USER_NAME, "wrong-password"));
|
||||
}
|
||||
try (Socket socket = open(port)) {
|
||||
assertEquals("+OK", command(socket, "AUTH", APP_USER_NAME, APP_PASSWORD));
|
||||
assertEquals("+OK", command(socket, "SET", "app:key", "allowed"));
|
||||
assertEquals("allowed", bulk(socket, "GET", "app:key"));
|
||||
String otherKey = command(socket, "SET", "other:key", "refused");
|
||||
assertTrue(otherKey.startsWith("-NOPERM"), otherKey);
|
||||
String flush = command(socket, "FLUSHALL");
|
||||
assertTrue(flush.startsWith("-NOPERM"), flush);
|
||||
assertEquals("allowed", bulk(socket, "GET", "app:key"));
|
||||
}
|
||||
// Floci's own connection to the backend is not authenticated, so once the proxy has set up
|
||||
// the backend's ACL a snapshot is refused rather than hanging or returning stale data.
|
||||
request("CreateSnapshot")
|
||||
.formParam("SnapshotName", "it-sl-acl-snap")
|
||||
.formParam("ReplicationGroupId", RBAC_ID)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidReplicationGroupState"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void aSnapshotTheServerCannotLoadFailsTheStartAndLeavesNoContainer() throws Exception {
|
||||
ElastiCacheContainerManager manager = CDI.current().select(ElastiCacheContainerManager.class).get();
|
||||
String garbage = Base64.getEncoder().encodeToString("not a snapshot".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThrows(ElastiCacheContainerManager.SnapshotRestoreException.class, () ->
|
||||
manager.start(BAD_SEED_ID, ShellLessBackendProfile.IMAGE, List.of(), "us-east-1", garbage));
|
||||
// The caller cleans up as the service's rollback does; the failed container is not left behind.
|
||||
manager.stopByGroupId(BAD_SEED_ID);
|
||||
assertEquals("", containerOf(BAD_SEED_ID));
|
||||
|
||||
// The failure touched neither the cluster the snapshot came from nor the snapshot itself.
|
||||
try (Socket socket = open(sourcePort)) {
|
||||
assertEquals("after", bulk(socket, "GET", "later-key"));
|
||||
}
|
||||
request("DescribeSnapshots")
|
||||
.formParam("SnapshotName", SNAPSHOT_NAME)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeSnapshotsResponse.DescribeSnapshotsResult.Snapshots.Snapshot.SnapshotStatus",
|
||||
equalTo("available"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void deletingTheGroupsRemovesTheirContainers() throws Exception {
|
||||
for (String groupId : List.of(RBAC_ID, TOKEN_ID, RESTORED_ID, SOURCE_ID)) {
|
||||
assertFalse(containerOf(groupId).isEmpty(), groupId + " has a container before the delete");
|
||||
request("DeleteReplicationGroup")
|
||||
.formParam("ReplicationGroupId", groupId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
await().atMost(60, TimeUnit.SECONDS).untilAsserted(() ->
|
||||
assertEquals("", containerOf(groupId), groupId + " container is removed"));
|
||||
}
|
||||
request("DeleteSnapshot")
|
||||
.formParam("SnapshotName", SNAPSHOT_NAME)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
for (String userId : List.of(APP_USER_ID, DEFAULT_USER_ID)) {
|
||||
request("DeleteUser").formParam("UserId", userId).post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static RequestSpecification request(String action) {
|
||||
return given().formParam("Action", action).header("Authorization", AUTH_HEADER);
|
||||
}
|
||||
|
||||
private static int createGroup(String groupId, String snapshotName, String authToken) {
|
||||
RequestSpecification request = request("CreateReplicationGroup")
|
||||
.formParam("ReplicationGroupId", groupId)
|
||||
.formParam("ReplicationGroupDescription", "shell-less backend");
|
||||
if (snapshotName != null) {
|
||||
request = request.formParam("SnapshotName", snapshotName);
|
||||
}
|
||||
if (authToken != null) {
|
||||
request = request.formParam("AuthToken", authToken);
|
||||
}
|
||||
return request
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.xmlPath()
|
||||
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup"
|
||||
+ ".NodeGroups.NodeGroup.PrimaryEndpoint.Port");
|
||||
}
|
||||
|
||||
private static void createUser(String userId, String userName, String authType, String password,
|
||||
String accessString) {
|
||||
RequestSpecification request = request("CreateUser")
|
||||
.formParam("UserId", userId)
|
||||
.formParam("UserName", userName)
|
||||
.formParam("AuthenticationMode.Type", authType)
|
||||
.formParam("AccessString", accessString);
|
||||
if (password != null) {
|
||||
request = request.formParam("AuthenticationMode.Passwords.member.1", password);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Socket open(int port) throws IOException {
|
||||
Socket socket = ElastiCacheTestConnections.openSocket("localhost", port);
|
||||
socket.setSoTimeout(SOCKET_TIMEOUT_MS);
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.command;
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.containerOf;
|
||||
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.docker;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Cluster-mode flags reach the nodes as container arguments with the shell-less backend, and the
|
||||
* cluster forms and serves from them. Key slots: {@code bar} is 5061, the first of two shards, and
|
||||
* {@code foo} is 12182, the second.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(ShellLessClusterProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class ElastiCacheShellLessClusterIntegrationTest {
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request";
|
||||
private static final String GROUP_ID = "it-sl-cluster";
|
||||
private static final List<String> NODES = List.of(GROUP_ID + "-0001-001", GROUP_ID + "-0002-001");
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
private static int configurationEndpointPort;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() throws InterruptedException {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
|
||||
"Docker daemon must be available for ElastiCache integration tests");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
try {
|
||||
given().port(baseUri.getPort())
|
||||
.formParam("Action", "DeleteReplicationGroup")
|
||||
.formParam("ReplicationGroupId", GROUP_ID)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.post("/");
|
||||
} catch (RuntimeException expected) {
|
||||
// Best effort: the group is already gone when the delete test ran.
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createClusterModeGroup() {
|
||||
configurationEndpointPort = given()
|
||||
.formParam("Action", "CreateReplicationGroup")
|
||||
.formParam("ReplicationGroupId", GROUP_ID)
|
||||
.formParam("ReplicationGroupDescription", "shell-less cluster mode")
|
||||
.formParam("NumNodeGroups", "2")
|
||||
.formParam("ReplicasPerNodeGroup", "0")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.Status",
|
||||
equalTo("available"))
|
||||
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.ClusterEnabled",
|
||||
equalTo("true"))
|
||||
.extract()
|
||||
.xmlPath()
|
||||
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup"
|
||||
+ ".ConfigurationEndpoint.Port");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void clusterFlagsAreContainerArgumentsOnEveryNode() throws Exception {
|
||||
for (String node : NODES) {
|
||||
String container = containerOf(node);
|
||||
assertFalse(container.isEmpty(), node + " has a container");
|
||||
String command = docker("inspect", "--format", "{{json .Config.Cmd}}", container);
|
||||
assertTrue(command.contains("\"--cluster-enabled\",\"yes\""), command);
|
||||
assertTrue(command.contains("\"--cluster-announce-bus-port\",\"16379\""), command);
|
||||
assertFalse(command.contains("enable-debug-command"), command);
|
||||
String environment = docker("inspect", "--format", "{{json .Config.Env}}", container);
|
||||
assertFalse(environment.contains("VALKEY_EXTRA_FLAGS"), environment);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void theClusterServesItsSlots() throws Exception {
|
||||
try (Socket socket = new Socket("localhost", configurationEndpointPort)) {
|
||||
socket.setSoTimeout(10_000);
|
||||
assertEquals("+OK", command(socket, "SET", "bar", "1"));
|
||||
assertTrue(command(socket, "SET", "foo", "1").startsWith("-MOVED 12182 "));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void deletingTheGroupRemovesEveryNodeContainer() throws Exception {
|
||||
given()
|
||||
.formParam("Action", "DeleteReplicationGroup")
|
||||
.formParam("ReplicationGroupId", GROUP_ID)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
for (String node : NODES) {
|
||||
await().atMost(60, TimeUnit.SECONDS).untilAsserted(() ->
|
||||
assertEquals("", containerOf(node), node + " container is removed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.floci.aws.services.elasticache.model.AuthMode;
|
||||
import io.floci.aws.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A group created from a snapshot when the backend is the shell-less one: the snapshot goes to the
|
||||
* container manager with the start, so it is loaded by the server at startup and never through
|
||||
* {@code restore}, and a group that cannot be started with it is rolled back without touching the
|
||||
* group or the snapshot it came from.
|
||||
*/
|
||||
class ElastiCacheShellLessSnapshotServiceTest {
|
||||
|
||||
private static final String RDB = "UkVESVMwMDEx+gl2YWxrZXktdmVyBTguMC4x/w==";
|
||||
|
||||
private ElastiCacheService service;
|
||||
private ElastiCacheContainerManager containerManager;
|
||||
private ElastiCacheProxyManager proxyManager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ElastiCacheServiceFixture fixture = new ElastiCacheServiceFixture();
|
||||
service = fixture.service;
|
||||
containerManager = fixture.containerManager;
|
||||
proxyManager = fixture.proxyManager;
|
||||
when(containerManager.isShellLessBackend()).thenReturn(true);
|
||||
doAnswer(inv -> ElastiCacheServiceFixture.containerHandle(inv.getArgument(0)))
|
||||
.when(containerManager).tryStart(anyString(), anyString(), any(), any());
|
||||
when(containerManager.snapshot("container-source")).thenReturn(RDB);
|
||||
service.createReplicationGroup("source", "group source", AuthMode.NO_AUTH, null, "us-east-1");
|
||||
service.createSnapshot("snap", "source", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSnapshotIsHandedToTheStartAndNeverRestoredIntoARunningServer() {
|
||||
service.createReplicationGroupFromSnapshot(request("restored"), "snap");
|
||||
|
||||
verify(containerManager).tryStart("restored", "valkey/valkey:8", "us-east-1", RDB);
|
||||
verify(containerManager, never()).restore(anyString(), anyString());
|
||||
verify(proxyManager).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any());
|
||||
assertEquals("restored", service.getReplicationGroup("restored").getReplicationGroupId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGroupWithoutASnapshotStartsWithoutOne() {
|
||||
service.createReplicationGroup("plain", "group plain", AuthMode.NO_AUTH, null, "us-east-1");
|
||||
|
||||
verify(containerManager).tryStart("plain", "valkey/valkey:8", "us-east-1");
|
||||
verify(containerManager, never()).tryStart(eq("plain"), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStartTheSnapshotCannotBeLoadedInRollsTheNewGroupBackAndKeepsTheRest() {
|
||||
doAnswer(inv -> {
|
||||
throw new ElastiCacheContainerManager.SnapshotRestoreException("the server could not load it");
|
||||
}).when(containerManager).tryStart(eq("restored"), anyString(), anyString(), any());
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> service.createReplicationGroupFromSnapshot(request("restored"), "snap"));
|
||||
|
||||
assertEquals("InvalidSnapshotState", failure.getErrorCode());
|
||||
// The container of the failed start is removed by id, since no handle came back.
|
||||
verify(containerManager).stopByGroupId("restored");
|
||||
verify(proxyManager, never()).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any());
|
||||
assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("restored")));
|
||||
// Neither the group the snapshot came from nor the snapshot is lost.
|
||||
assertEquals("source", service.getReplicationGroup("source").getReplicationGroupId());
|
||||
assertEquals("available", service.getSnapshot("snap").getSnapshotStatus());
|
||||
// The failed group's name and port are free again.
|
||||
service.createReplicationGroupFromSnapshot(request("restored-again"), "snap");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutADockerDaemonASnapshotCannotBeRestoredAndNothingIsLeftBehind() {
|
||||
doAnswer(inv -> null).when(containerManager).tryStart(eq("headless"), anyString(), anyString(), any());
|
||||
|
||||
assertEquals("InvalidReplicationGroupState",
|
||||
fault(() -> service.createReplicationGroupFromSnapshot(request("headless"), "snap")));
|
||||
assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("headless")));
|
||||
verify(containerManager).stopByGroupId("headless");
|
||||
}
|
||||
|
||||
private static ElastiCacheService.CreateReplicationGroupRequest request(String id) {
|
||||
return new ElastiCacheService.CreateReplicationGroupRequest(id, "group " + id, AuthMode.NO_AUTH, null,
|
||||
"us-east-1", null, null, null, null, null, null, null, null, null, null, null, null, null,
|
||||
Map.of(), null, null);
|
||||
}
|
||||
|
||||
private static String fault(Runnable call) {
|
||||
return assertThrows(AwsException.class, call::run).getErrorCode();
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,20 @@ import jakarta.enterprise.inject.spi.CDI;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Real CA validation for cache data-plane tests; never uses a trust-all manager. */
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Real CA validation for cache data-plane tests, which never uses a trust-all manager, and the Docker
|
||||
* CLI and RESP helpers the Docker-backed cache tests share.
|
||||
*/
|
||||
public final class ElastiCacheTestConnections {
|
||||
private ElastiCacheTestConnections() {}
|
||||
|
||||
@@ -59,4 +70,73 @@ public final class ElastiCacheTestConnections {
|
||||
throw new IOException("Could not establish a trusted cache TLS connection", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The id of the backend container of {@code resourceId}, or the empty string when there is none. */
|
||||
static String containerOf(String resourceId) throws Exception {
|
||||
return docker("ps", "-aq", "--filter", "label=io.floci.service=elasticache",
|
||||
"--filter", "label=io.floci.resource-id=" + resourceId);
|
||||
}
|
||||
|
||||
/** Runs the Docker CLI, which must succeed, and returns its trimmed output. */
|
||||
static String docker(String... arguments) throws Exception {
|
||||
Process process = startDocker(arguments);
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
assertTrue(process.waitFor(60, TimeUnit.SECONDS), "docker timed out");
|
||||
assertEquals(0, process.exitValue(), "docker " + String.join(" ", arguments) + ": " + output);
|
||||
return output;
|
||||
}
|
||||
|
||||
/** Runs the Docker CLI and returns its exit code. */
|
||||
static int dockerExit(String... arguments) throws Exception {
|
||||
Process process = startDocker(arguments);
|
||||
process.getInputStream().readAllBytes();
|
||||
assertTrue(process.waitFor(60, TimeUnit.SECONDS), "docker timed out");
|
||||
return process.exitValue();
|
||||
}
|
||||
|
||||
private static Process startDocker(String... arguments) throws IOException {
|
||||
List<String> command = new ArrayList<>(List.of("docker"));
|
||||
command.addAll(List.of(arguments));
|
||||
return new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
}
|
||||
|
||||
/** Sends one command and returns the first reply line, without its line ending. */
|
||||
static String command(Socket socket, String... parts) throws IOException {
|
||||
write(socket, parts);
|
||||
return readLine(socket.getInputStream());
|
||||
}
|
||||
|
||||
/** Sends one command whose reply is a bulk string and returns its content. */
|
||||
static String bulk(Socket socket, String... parts) throws IOException {
|
||||
write(socket, parts);
|
||||
InputStream in = socket.getInputStream();
|
||||
String header = readLine(in);
|
||||
assertTrue(header.startsWith("$"), "bulk reply expected, got " + header);
|
||||
int length = Integer.parseInt(header.substring(1));
|
||||
byte[] payload = in.readNBytes(length + 2);
|
||||
return new String(payload, 0, length, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static void write(Socket socket, String... parts) throws IOException {
|
||||
StringBuilder request = new StringBuilder("*").append(parts.length).append("\r\n");
|
||||
for (String part : parts) {
|
||||
request.append('$').append(part.getBytes(StandardCharsets.UTF_8).length).append("\r\n")
|
||||
.append(part).append("\r\n");
|
||||
}
|
||||
socket.getOutputStream().write(request.toString().getBytes(StandardCharsets.UTF_8));
|
||||
socket.getOutputStream().flush();
|
||||
}
|
||||
|
||||
static String readLine(InputStream in) throws IOException {
|
||||
StringBuilder line = new StringBuilder();
|
||||
int read;
|
||||
while ((read = in.read()) != -1) {
|
||||
if (read == '\r') {
|
||||
in.read();
|
||||
break;
|
||||
}
|
||||
line.append((char) read);
|
||||
}
|
||||
return line.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Runs the ElastiCache backend the way an image with no shell and no CLI needs
|
||||
* ({@code floci.services.elasticache.shell-less-backend}), against a real image of that kind: the
|
||||
* public KiviDB image, which is distroless. The image is pinned by digest, so the tests exercise
|
||||
* the same bytes every time; bumping it is a deliberate change to {@link #IMAGE}.
|
||||
*
|
||||
* <p>KiviDB names its snapshot file {@code dump.kdb} and does not report it as {@code dbfilename},
|
||||
* hence the file name override.
|
||||
*/
|
||||
public class ShellLessBackendProfile implements QuarkusTestProfile {
|
||||
|
||||
/** KiviDB v1.2.2, the multi-arch index digest. */
|
||||
public static final String IMAGE =
|
||||
"ghcr.io/kividbio/kividb:v1.2.2@sha256:8853c7b1e73e604502fd584533440cb1205ae311fe805d520543b4e85a4b71e9";
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.elasticache.default-image", IMAGE,
|
||||
"floci.services.elasticache.shell-less-backend", "true",
|
||||
"floci.services.elasticache.shell-less-backend-dbfilename", "dump.kdb");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The shell-less backend path with the default Valkey image, for cluster mode. KiviDB, the image
|
||||
* {@link ShellLessBackendProfile} uses, has no {@code --cluster-announce-client-ipv4} flag, which
|
||||
* Floci passes to every cluster-mode node, so it cannot form a Floci cluster yet; Valkey takes the
|
||||
* same container arguments and shows that the cluster-mode flags arrive and the cluster forms.
|
||||
*/
|
||||
public class ShellLessClusterProfile implements QuarkusTestProfile {
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.elasticache.shell-less-backend", "true");
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
package io.floci.aws.services.elasticache.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* How the backend container is configured with and without
|
||||
* {@code floci.services.elasticache.shell-less-backend}: the server flags go to the container as
|
||||
* arguments or through the image's {@code VALKEY_EXTRA_FLAGS} hook, never both.
|
||||
*/
|
||||
class ElastiCacheShellLessContainerManagerTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElastiCacheShellLessContainerManagerTest.class);
|
||||
|
||||
private static final List<String> CLUSTER_FLAGS = List.of(
|
||||
"--cluster-enabled", "yes",
|
||||
"--cluster-announce-hostname", "localhost",
|
||||
"--cluster-preferred-endpoint-type", "hostname",
|
||||
"--cluster-announce-client-ipv4", "127.0.0.1",
|
||||
"--cluster-announce-port", "6379",
|
||||
"--cluster-announce-bus-port", "16379");
|
||||
|
||||
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
private final ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
private final EmulatorConfig.ElastiCacheServiceConfig elasticache =
|
||||
mock(EmulatorConfig.ElastiCacheServiceConfig.class);
|
||||
|
||||
private ElastiCacheContainerManager manager(boolean shellLess) {
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.elasticache()).thenReturn(elasticache);
|
||||
when(elasticache.dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(elasticache.shellLessBackend()).thenReturn(shellLess);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
return new ElastiCacheContainerManager(containerBuilder, lifecycleManager,
|
||||
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config, regionResolver);
|
||||
}
|
||||
|
||||
/** Runs {@code start} against a fake backend that answers the readiness probe. */
|
||||
private void startAgainstFakeBackend(ElastiCacheContainerManager manager, List<String> flags)
|
||||
throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
Thread acceptor = new Thread(() -> {
|
||||
try (Socket socket = serverSocket.accept()) {
|
||||
socket.getInputStream().read(new byte[1024]);
|
||||
socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
socket.getOutputStream().flush();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Acceptor socket closed during test teardown");
|
||||
}
|
||||
});
|
||||
acceptor.setDaemon(true);
|
||||
acceptor.start();
|
||||
when(lifecycleManager.createAndStart(any(ContainerSpec.class)))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", serverSocket.getLocalPort()))));
|
||||
manager.start("my-group", "kividb/test", flags, "us-east-1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellLessBackendPassesTheServerFlagsAsContainerArguments() throws IOException {
|
||||
startAgainstFakeBackend(manager(true), List.of());
|
||||
|
||||
ArgumentCaptor<List<String>> command = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(command.capture());
|
||||
assertEquals(List.of("--port", "6379", "--protected-mode", "no", "--loglevel", "verbose"),
|
||||
command.getValue());
|
||||
verify(builder, never()).withEnv(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellLessBackendPassesClusterModeFlagsAsContainerArguments() throws IOException {
|
||||
startAgainstFakeBackend(manager(true), CLUSTER_FLAGS);
|
||||
|
||||
ArgumentCaptor<List<String>> command = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(command.capture());
|
||||
List<String> expected = new ArrayList<>(
|
||||
List.of("--port", "6379", "--protected-mode", "no", "--loglevel", "verbose"));
|
||||
expected.addAll(CLUSTER_FLAGS);
|
||||
assertEquals(expected, command.getValue());
|
||||
verify(builder, never()).withEnv(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellLessBackendNeverEnablesTheDebugCommand() throws IOException {
|
||||
startAgainstFakeBackend(manager(true), CLUSTER_FLAGS);
|
||||
|
||||
ArgumentCaptor<List<String>> command = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(command.capture());
|
||||
assertFalse(command.getValue().contains("--enable-debug-command"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultPathStillUsesTheValkeyExtraFlagsHook() throws IOException {
|
||||
startAgainstFakeBackend(manager(false), CLUSTER_FLAGS);
|
||||
|
||||
verify(builder).withEnv("VALKEY_EXTRA_FLAGS", "--loglevel verbose --enable-debug-command local "
|
||||
+ String.join(" ", CLUSTER_FLAGS));
|
||||
verify(builder, never()).withCmd(any(List.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotIsLoadedAtStartupOnlyWithTheShellLessBackend() {
|
||||
ElastiCacheContainerManager manager = manager(false);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> manager.start("my-group", "valkey/valkey:8", List.of(), "us-east-1", "UkVESVM="));
|
||||
|
||||
verify(lifecycleManager, never()).createAndStart(any(ContainerSpec.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotIsReadOnlyFromABackendThatIsRunning() {
|
||||
ElastiCacheContainerManager manager = manager(true);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.snapshot("no-such-container"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A server that answers PING and reports the given data directory and snapshot file name, on
|
||||
* as many connections as the start opens.
|
||||
*/
|
||||
private ServerSocket fakeBackend(String directory, String fileName) throws IOException {
|
||||
ServerSocket serverSocket = new ServerSocket(0);
|
||||
Thread acceptor = new Thread(() -> {
|
||||
while (!serverSocket.isClosed()) {
|
||||
try {
|
||||
Socket socket = serverSocket.accept();
|
||||
Thread handler = new Thread(() -> answer(socket, directory, fileName));
|
||||
handler.setDaemon(true);
|
||||
handler.start();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Fake backend closed during test teardown");
|
||||
}
|
||||
}
|
||||
});
|
||||
acceptor.setDaemon(true);
|
||||
acceptor.start();
|
||||
return serverSocket;
|
||||
}
|
||||
|
||||
private static void answer(Socket socket, String directory, String fileName) {
|
||||
try (socket) {
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
|
||||
String header;
|
||||
while ((header = in.readLine()) != null) {
|
||||
int count = Integer.parseInt(header.substring(1));
|
||||
StringBuilder request = new StringBuilder();
|
||||
for (int i = 0; i < count; i++) {
|
||||
in.readLine();
|
||||
request.append(in.readLine()).append(' ');
|
||||
}
|
||||
String reply;
|
||||
if (request.toString().startsWith("PING")) {
|
||||
reply = "+PONG\r\n";
|
||||
} else if (request.toString().endsWith("dbfilename ")) {
|
||||
reply = fileName.isEmpty() ? "*0\r\n"
|
||||
: "*2\r\n$10\r\ndbfilename\r\n$" + fileName.length() + "\r\n" + fileName + "\r\n";
|
||||
} else {
|
||||
reply = "*2\r\n$3\r\ndir\r\n$" + directory.length() + "\r\n" + directory + "\r\n";
|
||||
}
|
||||
socket.getOutputStream().write(reply.getBytes(StandardCharsets.UTF_8));
|
||||
socket.getOutputStream().flush();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Fake backend connection closed");
|
||||
}
|
||||
}
|
||||
|
||||
private ElastiCacheContainerManager seededManager(ServerSocket backend, String configuredFileName) {
|
||||
DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
when(docker.inspectContainerCmd(anyString()).exec().getConfig().getWorkingDir()).thenReturn("/data");
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(docker);
|
||||
when(lifecycleManager.createAndStart(any(ContainerSpec.class), any(Consumer.class))).thenAnswer(inv -> {
|
||||
Consumer<String> beforeStart = inv.getArgument(1);
|
||||
beforeStart.accept("container-id");
|
||||
return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort())));
|
||||
});
|
||||
ElastiCacheContainerManager manager = manager(true);
|
||||
when(elasticache.shellLessBackendDbfilename()).thenReturn(configuredFileName);
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreIsConfirmedWhenTheServerLoadsTheFileThatWasPlaced() throws IOException {
|
||||
try (ServerSocket backend = fakeBackend("/data", "dump.rdb")) {
|
||||
ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb");
|
||||
|
||||
manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM=");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreIsRefusedWhenTheServerLoadsAnotherFileName() throws IOException {
|
||||
try (ServerSocket backend = fakeBackend("/data", "dump.kdb")) {
|
||||
ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb");
|
||||
|
||||
ElastiCacheContainerManager.SnapshotRestoreException failure = assertThrows(
|
||||
ElastiCacheContainerManager.SnapshotRestoreException.class,
|
||||
() -> manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM="));
|
||||
|
||||
assertTrue(failure.getMessage().contains("dump.kdb"), failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreIsRefusedWhenTheServerUsesAnotherDirectory() throws IOException {
|
||||
try (ServerSocket backend = fakeBackend("/elsewhere", "")) {
|
||||
ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb");
|
||||
|
||||
assertThrows(ElastiCacheContainerManager.SnapshotRestoreException.class,
|
||||
() -> manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM="));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerThatReportsNoFileNameIsAcceptedWhenTheDirectoryMatches() throws IOException {
|
||||
try (ServerSocket backend = fakeBackend("/data", "")) {
|
||||
ElastiCacheContainerManager manager = seededManager(backend, "dump.kdb");
|
||||
|
||||
manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM=");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user