diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 432d82679e..41220c018c 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -228,7 +228,7 @@ floci: proxy-max-port: 6399 default-image: "valkey/valkey:8" shell-less-backend: false # true = image has no shell or CLI: flags as container arguments, snapshots via SAVE over RESP + Docker archive API - shell-less-backend-dbfilename: dump.rdb # snapshot file the server loads at startup (used with shell-less-backend) + shell-less-backend-dbfilename: dump.rdb # snapshot file the server loads at startup; a restore places the snapshot under it rds: enabled: true diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 51c1148e7e..614eff6b9f 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -498,8 +498,8 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT` | `6379` | First port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT` | `6399` | Last port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE` | `valkey/valkey:8` | Default Docker image for cache clusters | -| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | `false` | Pass server flags as container arguments and take and restore snapshots without a shell or CLI in the image (`SAVE` over RESP, the Docker archive API, the snapshot file placed before the server starts). Never inferred from the image; see [ElastiCache](../services/elasticache.md#images-with-no-shell-or-cli) | -| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME` | `dump.rdb` | Snapshot file name the server loads at startup; used only with `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | `false` | Pass server flags as container arguments and take snapshots without a shell or CLI in the image (`SAVE` over RESP, the Docker archive API). Never inferred from the image; see [ElastiCache](../services/elasticache.md#images-with-no-shell-or-cli) | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME` | `dump.rdb` | Snapshot file name the server loads at startup; a restore places the snapshot under it, with or without `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | | `FLOCI_SERVICES_ELASTICACHE_DOCKER_NETWORK` | _(none)_ | Docker network for ElastiCache containers (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) | | `FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME` | _(none)_ | Hostname cluster-mode nodes announce in `MOVED`/`ASK` redirects and topology responses, and report as the `ConfigurationEndpoint`. Set to a name every client resolves (e.g. `localhost.floci.io`) when `FLOCI_HOSTNAME` only resolves inside Floci's Docker network. Defaults to `FLOCI_HOSTNAME` | diff --git a/docs/services/elasticache.md b/docs/services/elasticache.md index 37e461c1f4..ff758fae45 100644 --- a/docs/services/elasticache.md +++ b/docs/services/elasticache.md @@ -380,11 +380,18 @@ snapshot's ARN. `DescribeSnapshots` returns snapshots in name order, `MaxRecords Snapshots outlive the group they were taken from, as on AWS. They are taken of cluster-mode-disabled replication groups only: a cluster-mode-enabled group, a standalone cache cluster or a group without a running backend is refused, as is seeding a cluster-mode-enabled -group. Automatic snapshots, `CopySnapshot` and `FinalSnapshotIdentifier` are not modeled. To -reload the dataset, the backend runs with `--enable-debug-command local`, which allows `DEBUG` -only for connections from inside its own container; clients always connect through the proxy. -With [`shell-less-backend`](#images-with-no-shell-or-cli) the snapshot file is placed before the -server starts instead, and `DEBUG` is not enabled. +group. Automatic snapshots, `CopySnapshot` and `FinalSnapshotIdentifier` are not modeled. + +A group created from a snapshot starts with the snapshot file already in its backend's data +directory (the image's working directory, where a server started without `--dir` keeps its data), +so the server loads it at startup. No backend runs with `--enable-debug-command`, which a Redis +before 7.0 refuses to start with, and `DEBUG` is never used. The file is placed under the name set +by `floci.services.elasticache.shell-less-backend-dbfilename` +(`FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME`, default `dump.rdb`, the name Redis and +Valkey load), and Floci checks the server's `dir`, and its `dbfilename` when it reports one, once +it is up. If the file cannot be placed, or the server cannot start with it, the new group's +container is removed and the create fails with `InvalidSnapshotState`; the group the snapshot came +from and the snapshot are not touched. ## Engine version and backend image @@ -415,9 +422,9 @@ Memcached uses the separate `floci.services.elasticache.default-memcached-image` ### Images with no shell or CLI -By default Floci starts the backend through the image's `VALKEY_EXTRA_FLAGS` hook and takes and -restores snapshots with the `valkey-cli` or `redis-cli` inside the container, which only images -built like `valkey/valkey` provide. An image that has no shell and no CLI, such as a distroless +By default Floci starts the backend through the image's `VALKEY_EXTRA_FLAGS` hook and takes +snapshots with the `valkey-cli` or `redis-cli` inside the container, which only images built like +`valkey/valkey` provide. An image that has no shell and no CLI, such as a distroless Redis-compatible image, needs the other path, which is selected by `floci.services.elasticache.shell-less-backend` (`FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND`). It is `false` by default and is never inferred from the image name, so which path runs is always the @@ -432,17 +439,13 @@ With `shell-less-backend` set to `true`: - `CreateSnapshot` runs `SAVE`, reads `CONFIG GET dir` and `CONFIG GET dbfilename` over the RESP connection to the backend, and copies the file out of the container through the Docker archive API. No command is executed inside the container. -- `CreateReplicationGroup` with `SnapshotName` places the snapshot file in the container's data - directory (the image's working directory, which is where a server started without `--dir` keeps - its data) before the server starts, so the server loads it itself. No `DEBUG` command is used and - `--enable-debug-command` is not passed. If the file cannot be placed, or the server cannot start - with it, the new group's container is removed and the create fails with `InvalidSnapshotState`; - the group the snapshot came from and the snapshot are not touched. +- `CreateReplicationGroup` with `SnapshotName` places the snapshot file before the server starts, + as on the default path. - `floci.services.elasticache.shell-less-backend-dbfilename` (`FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME`, default `dump.rdb`) names the file the server loads from its data directory at startup. A restore places the snapshot under this - name, and a snapshot falls back to it when the server does not report `dbfilename`. Set it to the - name your image's server uses. + name on either path, and a snapshot falls back to it when the server does not report + `dbfilename`. Set it to the name your image's server uses. An image used this way has to: @@ -480,7 +483,7 @@ do not restore a snapshot taken from one engine into another. | `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT` | `6399` | Last host port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE` | `valkey/valkey:8` | Docker image for Redis/Valkey containers | | `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | `false` | Start and snapshot the backend for an image with no shell or CLI: [see above](#images-with-no-shell-or-cli) | -| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME` | `dump.rdb` | Snapshot file name the server loads at startup, used with the setting above | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME` | `dump.rdb` | Snapshot file name the server loads at startup; a restore places the snapshot under it on either path | ### Docker Compose diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 1dc4707176..f577833bc4 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1917,18 +1917,18 @@ public interface EmulatorConfig { /** * Start and snapshot the backend of a Redis or Valkey replication group the way an image * with no shell and no CLI needs: server flags go to the container as arguments instead of - * the {@code VALKEY_EXTRA_FLAGS} hook, a snapshot is taken with {@code SAVE} over the RESP - * connection and read out of the container through the Docker archive API, and a snapshot - * is restored by placing its file in the data directory before the server starts, so no - * {@code DEBUG} command is involved. Off by default and never inferred from the image name: - * the default image keeps the {@code VALKEY_EXTRA_FLAGS} and CLI path. + * the {@code VALKEY_EXTRA_FLAGS} hook, and a snapshot is taken with {@code SAVE} over the + * RESP connection and read out of the container through the Docker archive API. Off by + * default and never inferred from the image name: the default image keeps the + * {@code VALKEY_EXTRA_FLAGS} and CLI path. Either way a snapshot is restored by placing its + * file in the data directory before the server starts, so no {@code DEBUG} command is involved. */ @WithDefault("false") boolean shellLessBackend(); /** - * Name of the snapshot file the server loads from its data directory at startup. Only used - * with {@link #shellLessBackend()}: a restore places the snapshot under this name, and a + * Name of the snapshot file the server loads from its data directory at startup. A restore + * places the snapshot under this name on either path, and with {@link #shellLessBackend()} a * snapshot export falls back to it when the server does not report {@code dbfilename}. * Set it to the name the image's server uses ({@code dump.rdb} for Redis and Valkey). */ diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java index 46dd91a1b0..f4578051fe 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java @@ -452,21 +452,21 @@ public class ElastiCacheService implements ResourceProvider { // derived from configuration and need no Docker, so the group is created and reaches // 'available' even when no daemon is reachable. Only connecting to the cache needs // the container. - // With the shell-less backend the snapshot is placed in the data directory before the - // server starts; otherwise it is loaded into the running server below. - String startupSeed = seed != null && containerManager.isShellLessBackend() ? seed.rdbBase64() : null; + // A snapshot is placed in the data directory before the server starts, so the server + // loads it itself and no server version needs DEBUG. try { - handle = startupSeed == null + handle = seed == null ? containerManager.tryStart(groupId, image, request.region()) - : containerManager.tryStart(groupId, image, request.region(), startupSeed); + : containerManager.tryStart(groupId, image, request.region(), seed.rdbBase64()); } catch (ElastiCacheContainerManager.SnapshotRestoreException e) { LOG.warnv(e, "Failed to restore snapshot {0} into replication group {1}", seed.snapshotName(), groupId); throw new AwsException("InvalidSnapshotState", "Failed to restore snapshot " + seed.snapshotName() + " into replication group " + groupId + ": " + e.getMessage(), 400); } - if (seed != null && (startupSeed == null || handle == null)) { - loadSnapshot(groupId, handle, seed); + if (seed != null && handle == null) { + throw new AwsException("InvalidReplicationGroupState", "Replication group " + groupId + + " has no running backend to restore snapshot " + seed.snapshotName() + " into.", 400); } String endpointHost = resolveEndpointHost(); @@ -1591,20 +1591,6 @@ public class ElastiCacheService implements ResourceProvider { return createReplicationGroup(request, new SnapshotSeed(snapshotName, archive)); } - private void loadSnapshot(String groupId, ElastiCacheContainerHandle handle, SnapshotSeed seed) { - if (handle == null) { - throw new AwsException("InvalidReplicationGroupState", "Replication group " + groupId - + " has no running backend to restore snapshot " + seed.snapshotName() + " into.", 400); - } - try { - containerManager.restore(handle.getContainerId(), seed.rdbBase64()); - } catch (RuntimeException e) { - LOG.warnv(e, "Failed to restore snapshot {0} into replication group {1}", seed.snapshotName(), groupId); - throw new AwsException("InvalidSnapshotState", "Failed to restore snapshot " + seed.snapshotName() - + " into replication group " + groupId + ": " + e.getMessage(), 400); - } - } - // ── Cache Clusters (single-node Redis/Valkey) ───────────────────────────── /** diff --git a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java index cfad833af0..1e1073bcde 100644 --- a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java +++ b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java @@ -151,9 +151,10 @@ public class ElastiCacheContainerManager { } /** - * {@link #start(String, String, List, String)} that also loads a snapshot at startup, for the - * shell-less path only: the RDB file is placed in the container's data directory before the - * server process starts, so it loads the dataset itself and no {@code DEBUG} command is needed. + * {@link #start(String, String, List, String)} that also loads a snapshot at startup: the RDB + * file is placed in the container's data directory before the server process starts, so it loads + * the dataset itself. No {@code DEBUG} command is needed, nor {@code --enable-debug-command}, + * which a server before Redis 7 refuses to start with. * A container that cannot be seeded is removed and reported as a {@link SnapshotRestoreException}. * * @param seedRdbBase64 a {@link #snapshot} archive to start from, or {@code null} for an empty cache @@ -162,10 +163,6 @@ public class ElastiCacheContainerManager { String region, String seedRdbBase64) { LOG.infov("Starting ElastiCache backend container for group: {0}", groupId); boolean shellLess = isShellLessBackend(); - if (seedRdbBase64 != null && !shellLess) { - throw new IllegalArgumentException( - "A snapshot is loaded at startup only with floci.services.elasticache.shell-less-backend"); - } String containerName = containerName(groupId); @@ -191,9 +188,9 @@ public class ElastiCacheContainerManager { arguments.addAll(extraServerFlags); specBuilder.withCmd(arguments); } else { - // DEBUG is enabled for connections from inside the container only, so a snapshot restore - // can reload the dataset (DEBUG RELOAD NOSAVE); clients reach the server through the proxy. - StringBuilder serverFlags = new StringBuilder("--loglevel verbose --enable-debug-command local"); + // No --enable-debug-command, which a server before Redis 7 refuses to start with: a + // snapshot is restored by file, before start, here too. + StringBuilder serverFlags = new StringBuilder("--loglevel verbose"); for (String flag : extraServerFlags) { serverFlags.append(' ').append(flag); } @@ -443,21 +440,6 @@ public class ElastiCacheContainerManager { } } - /** Replaces the dataset with a {@link #snapshot} RDB file and reloads it without saving first. */ - public void restore(String containerId, String rdbBase64) { - byte[] rdb = Base64.getDecoder().decode(rdbBase64); - RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/tmp", - "floci-restore.rdb", rdb, 0644); - String[] cmd = {"sh", "-c", CLI + "D=$($C CONFIG GET dir | sed -n 2p); F=$($C CONFIG GET dbfilename | sed -n 2p);" - + " cp /tmp/floci-restore.rdb \"$D/$F\" && rm -f /tmp/floci-restore.rdb" - + " && $C DEBUG RELOAD NOSAVE | grep -q OK"}; - ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 300); - if (result.exitCode() != 0) { - throw new IllegalStateException("restore failed with exit code " + result.exitCode() + ": " - + result.stderr() + result.stdout()); - } - } - public void stop(ElastiCacheContainerHandle handle) { if (handle == null) { return; diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java deleted file mode 100644 index e41fef8c1d..0000000000 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java +++ /dev/null @@ -1,109 +0,0 @@ -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(); - } -} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheSnapshotServiceTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheSnapshotServiceTest.java index 325598a977..747e92407f 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheSnapshotServiceTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheSnapshotServiceTest.java @@ -56,6 +56,9 @@ class ElastiCacheSnapshotServiceTest { doAnswer(inv -> "headless".equals(inv.getArgument(0)) ? null : ElastiCacheServiceFixture.containerHandle(inv.getArgument(0))) .when(containerManager).tryStart(anyString(), anyString(), any()); + doAnswer(inv -> "headless".equals(inv.getArgument(0)) ? null + : ElastiCacheServiceFixture.containerHandle(inv.getArgument(0))) + .when(containerManager).tryStart(anyString(), anyString(), anyString(), any()); when(containerManager.snapshot("container-source")).thenReturn(RDB); } @@ -70,10 +73,18 @@ class ElastiCacheSnapshotServiceTest { assertEquals("manual", snapshot.getSnapshotSource()); assertEquals("source", snapshot.getReplicationGroupId()); assertEquals("arn:aws:elasticache:us-east-1:000000000000:snapshot:snap", snapshot.getArn()); - verify(containerManager).restore("container-restored", RDB); + verify(containerManager).tryStart("restored", "valkey/valkey:8", "us-east-1", RDB); assertEquals("restored", service.getReplicationGroup("restored").getReplicationGroupId()); } + @Test + void aGroupWithoutASnapshotStartsWithoutOne() { + group("plain"); + + verify(containerManager).tryStart("plain", "valkey/valkey:8", "us-east-1"); + verify(containerManager, never()).tryStart(eq("plain"), anyString(), anyString(), any()); + } + @Test void theRdbIsLoadedBeforeTheGroupIsPublishedOrReachable() { group("source"); @@ -81,14 +92,14 @@ class ElastiCacheSnapshotServiceTest { AtomicReference duringLoad = new AtomicReference<>(); doAnswer(inv -> { duringLoad.set(fault(() -> service.getReplicationGroup("restored"))); - return null; - }).when(containerManager).restore("container-restored", RDB); + return ElastiCacheServiceFixture.containerHandle("restored"); + }).when(containerManager).tryStart("restored", "valkey/valkey:8", "us-east-1", RDB); service.createReplicationGroupFromSnapshot(request("restored", null), "snap"); assertEquals("ReplicationGroupNotFoundFault", duringLoad.get()); InOrder order = inOrder(containerManager, proxyManager); - order.verify(containerManager).restore("container-restored", RDB); + order.verify(containerManager).tryStart("restored", "valkey/valkey:8", "us-east-1", RDB); order.verify(proxyManager).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any()); } @@ -177,20 +188,38 @@ class ElastiCacheSnapshotServiceTest { fault(() -> service.createReplicationGroupFromSnapshot(request("restored", null), "snap"))); assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("restored"))); verify(containerManager, never()).tryStart(eq("restored"), anyString(), any()); + verify(containerManager, never()).tryStart(eq("restored"), anyString(), anyString(), any()); } @Test - void aGroupTheRdbCannotBeLoadedIntoIsRemoved() { + void aGroupTheRdbCannotBeLoadedIntoIsRemovedAndTheRestIsKept() { group("source"); service.createSnapshot("snap", "source", null); - doThrow(new IllegalStateException("DEBUG RELOAD failed")) - .when(containerManager).restore("container-restored", RDB); + doThrow(new ElastiCacheContainerManager.SnapshotRestoreException("the server could not load it")) + .when(containerManager).tryStart("restored", "valkey/valkey:8", "us-east-1", RDB); assertEquals("InvalidSnapshotState", fault(() -> service.createReplicationGroupFromSnapshot(request("restored", null), "snap"))); assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("restored"))); verify(proxyManager, never()).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any()); - verify(containerManager).stop(any()); + // The container of the failed start is removed by id, since no handle came back. + verify(containerManager).stopByGroupId("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", null), "snap"); + } + + @Test + void withoutADockerDaemonASnapshotCannotBeRestoredAndNothingIsLeftBehind() { + group("source"); + service.createSnapshot("snap", "source", null); + + assertEquals("InvalidReplicationGroupState", + fault(() -> service.createReplicationGroupFromSnapshot(request("headless", null), "snap"))); + assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("headless"))); + verify(containerManager).stopByGroupId("headless"); } @Test @@ -201,6 +230,7 @@ class ElastiCacheSnapshotServiceTest { assertEquals("InvalidParameterCombination", fault(() -> service.createReplicationGroupFromSnapshot(request("sharded", "enabled"), "snap"))); verify(containerManager, never()).tryStart(eq("sharded"), anyString(), any()); + verify(containerManager, never()).tryStart(eq("sharded"), anyString(), anyString(), any()); } @Test diff --git a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java index f5f156c0d0..3ab78d99a3 100644 --- a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java @@ -134,21 +134,10 @@ class ElastiCacheShellLessContainerManagerTest { 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).withEnv("VALKEY_EXTRA_FLAGS", "--loglevel verbose " + 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); @@ -209,6 +198,11 @@ class ElastiCacheShellLessContainerManagerTest { } private ElastiCacheContainerManager seededManager(ServerSocket backend, String configuredFileName) { + return seededManager(backend, configuredFileName, true); + } + + private ElastiCacheContainerManager seededManager(ServerSocket backend, String configuredFileName, + boolean shellLess) { DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); when(docker.inspectContainerCmd(anyString()).exec().getConfig().getWorkingDir()).thenReturn("/data"); when(lifecycleManager.getDockerClient()).thenReturn(docker); @@ -218,11 +212,26 @@ class ElastiCacheShellLessContainerManagerTest { return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))); }); - ElastiCacheContainerManager manager = manager(true); + ElastiCacheContainerManager manager = manager(shellLess); when(elasticache.shellLessBackendDbfilename()).thenReturn(configuredFileName); return manager; } + // Catches: the default path loading a snapshot with DEBUG RELOAD, which needs + // --enable-debug-command, a flag a Redis before 7 refuses to start with. + @Test + void theDefaultPathPlacesTheSnapshotBeforeTheServerStartsWithoutTheDebugCommand() throws IOException { + try (ServerSocket backend = fakeBackend("/data", "dump.rdb")) { + ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb", false); + + manager.start("my-group", "valkey/valkey:8", List.of(), "us-east-1", "UkVESVM="); + + verify(lifecycleManager.getDockerClient()).copyArchiveToContainerCmd("container-id"); + verify(builder).withEnv("VALKEY_EXTRA_FLAGS", "--loglevel verbose"); + verify(builder, never()).withCmd(any(List.class)); + } + } + @Test void aRestoreIsConfirmedWhenTheServerLoadsTheFileThatWasPlaced() throws IOException { try (ServerSocket backend = fakeBackend("/data", "dump.rdb")) {