fix(rds): retry grant and snapshot archive uploads (#6069)

* fix(rds): retry master grant archive uploads

* fix(rds): retry snapshot restore archive uploads
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-20 08:25:52 -04:00
1 parent 9d1565fda3
commit 1a598b7f0c
3 files changed
+255 -29

No files matched your search

+6
View File
@@ -36,6 +36,12 @@ mark those members `failed` until a successful retry.
Floci manages real PostgreSQL, MySQL, MariaDB, and SQL Server Docker containers and proxies TCP connections to them, including IAM authentication support where the protocol supports it. SQL Server uses a transparent TCP relay for its native TDS protocol.
MySQL and MariaDB master-grant script uploads, and PostgreSQL snapshot restore archive uploads,
retry transient Docker connection failures up to six attempts with exponential backoff starting
at 500 ms. Every attempt sends a fresh archive. Containers start, or snapshot restore commands
run, only after the upload succeeds. A permanent Docker error or exhausted retries follows the
existing failure path. The PostgreSQL restore SQL readiness retry policy is unchanged.
RDS Data API (`rds-data`) is documented separately because it uses REST JSON routes instead of the RDS Query protocol. See [RDS Data API](rds-data.md).
## Supported Management Actions
@@ -19,15 +19,14 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLiveness;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
@@ -68,6 +67,7 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final ServiceConfigAccess serviceConfigAccess;
private final long uploadBackoffMillis;
private final Map<String, RdsContainerHandle> activeContainers = new ConcurrentHashMap<>();
private final Map<String, String> activeStorageOwners = new ConcurrentHashMap<>();
private final Set<String> claimedRuntimes = ConcurrentHashMap.newKeySet();
@@ -105,6 +105,18 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
EmulatorConfig config,
RegionResolver regionResolver,
ServiceConfigAccess serviceConfigAccess) {
this(containerBuilder, lifecycleManager, logStreamer, containerDetector, config,
regionResolver, serviceConfigAccess, RetryingTarCopier.DEFAULT_BACKOFF_MS);
}
RdsContainerManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer,
ContainerDetector containerDetector,
EmulatorConfig config,
RegionResolver regionResolver,
ServiceConfigAccess serviceConfigAccess,
long uploadBackoffMillis) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
@@ -112,6 +124,7 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
this.config = config;
this.regionResolver = regionResolver;
this.serviceConfigAccess = serviceConfigAccess;
this.uploadBackoffMillis = uploadBackoffMillis;
}
public RdsContainerHandle start(String instanceId, String volumeId, DatabaseEngine engine,
@@ -846,23 +859,9 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
*/
private void installMasterGrantInitScript(String containerId, String masterUsername) {
byte[] sql = mysqlMasterGrantSql(masterUsername).getBytes(StandardCharsets.UTF_8);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
TarArchiveEntry entry = new TarArchiveEntry("floci-master-grants.sql");
entry.setSize(sql.length);
entry.setMode(0644);
tar.putArchiveEntry(entry);
tar.write(sql);
tar.closeArchiveEntry();
}
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
.withRemotePath("/docker-entrypoint-initdb.d")
.withTarInputStream(new ByteArrayInputStream(bos.toByteArray()))
.exec();
} catch (IOException e) {
throw new IllegalStateException(
"Failed to install the master-grant init script into container " + containerId, e);
}
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId,
"/docker-entrypoint-initdb.d", "floci-master-grants.sql", sql, 0644,
RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, uploadBackoffMillis);
}
private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description) {
@@ -962,21 +961,18 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
try (Lease _ = holdContainer(containerId)) {
String restoreScript = postgresRestoreScript();
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
try (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream tar =
new org.apache.commons.compress.archivers.tar.TarArchiveOutputStream(bos)) {
tar.setLongFileMode(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream.LONGFILE_GNU);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
addTarEntry(tar, "dump.sql", sqlDump);
addTarEntry(tar, "restore.sh", restoreScript);
}
try (java.io.InputStream tarStream = new java.io.ByteArrayInputStream(bos.toByteArray())) {
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
.withRemotePath("/tmp")
.withTarInputStream(tarStream)
.exec();
}
byte[] archive = bos.toByteArray();
RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId,
"/tmp", "postgres-restore", out -> out.write(archive),
RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, uploadBackoffMillis);
String[] cmd = { "sh", "/tmp/restore.sh", effectiveUser };
@@ -0,0 +1,224 @@
package io.github.hectorvent.floci.services.rds.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.testing.DockerArchiveUploadFixture;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
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.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RdsArchiveRetryTest {
private static final String CONTAINER = "rds-retry-id";
@TempDir
Path temporary;
private DockerClient docker;
private ContainerLifecycleManager lifecycle;
private RdsContainerManager manager;
@BeforeEach
void setUp() {
docker = mock(DockerClient.class);
lifecycle = mock(ContainerLifecycleManager.class);
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.create(any())).thenReturn(CONTAINER);
when(lifecycle.startCreated(eq(CONTAINER), any())).thenReturn(new ContainerInfo(CONTAINER,
Map.of(3306, new EndpointInfo("localhost", 3306))));
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(spec.build()).thenReturn(new ContainerSpec("test-image"));
when(builder.newContainer(anyString())).thenReturn(spec);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().rds().dockerNetwork()).thenReturn(Optional.empty());
when(config.storage().hostPersistentPath()).thenReturn(temporary.toString());
when(config.storage().mode()).thenReturn("persistent");
ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
manager = new RdsContainerManager(builder, lifecycle, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class), 0);
}
@AfterEach
void tearDown() {
manager.clear();
manager.shutdownAutoPause();
}
@ParameterizedTest
@CsvSource({"MYSQL,0", "MYSQL,73", "MYSQL,8192", "MARIADB,0", "MARIADB,73", "MARIADB,8192"})
void masterGrantRetriesConsumedUploadBeforeStarting(DatabaseEngine engine, int consumedBytes) throws Exception {
DockerArchiveUploadFixture uploads = failingUploads(consumedBytes, 1);
RdsContainerHandle handle = manager.start("db", "volume", engine, "test-image", "we'ird\\", "password", "db");
assertEquals(CONTAINER, handle.getContainerId());
assertEquals(2, uploads.commands.size());
assertEquals(1, uploads.completed.size());
assertNotSame(uploads.streams.get(0), uploads.streams.get(1));
verify(uploads.commands.get(1)).withRemotePath("/docker-entrypoint-initdb.d");
try (TarArchiveInputStream tar = new TarArchiveInputStream(new ByteArrayInputStream(uploads.completed.getFirst()))) {
TarArchiveEntry entry = tar.getNextEntry();
assertEquals("floci-master-grants.sql", entry.getName());
assertEquals(0644, entry.getMode());
assertArrayEquals("GRANT ALL PRIVILEGES ON *.* TO 'we\\'ird\\\\'@'%' WITH GRANT OPTION;"
.getBytes(StandardCharsets.UTF_8), tar.readAllBytes());
assertNull(tar.getNextEntry());
}
InOrder order = inOrder(lifecycle, uploads.commands.get(1));
order.verify(lifecycle).create(any());
order.verify(uploads.commands.get(1)).exec();
order.verify(lifecycle).startCreated(eq(CONTAINER), any());
verify(docker, never()).execCreateCmd(anyString());
}
@ParameterizedTest
@ValueSource(ints = {0, 73, 8192})
void postgresRestoreRetriesBothEntriesBeforeRunningSql(int consumedBytes) throws Exception {
DockerArchiveUploadFixture uploads = failingUploads(consumedBytes, 1);
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
String dump = "-- snapshot é\n".repeat(2048);
manager.restorePostgresSnapshot(CONTAINER, "admin", dump);
assertEquals(2, uploads.commands.size());
assertEquals(1, uploads.completed.size());
assertNotSame(uploads.streams.get(0), uploads.streams.get(1));
verify(uploads.commands.get(1)).withRemotePath("/tmp");
try (TarArchiveInputStream tar = new TarArchiveInputStream(new ByteArrayInputStream(uploads.completed.getFirst()))) {
assertTarEntry(tar, "dump.sql", dump);
assertTarEntry(tar, "restore.sh", RdsContainerManager.postgresRestoreScript());
assertNull(tar.getNextEntry());
}
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin")), commands);
InOrder order = inOrder(uploads.commands.get(1), docker);
order.verify(uploads.commands.get(1)).exec();
order.verify(docker).execCreateCmd(CONTAINER);
}
@ParameterizedTest
@CsvSource({"MYSQL,false", "MARIADB,false", "MYSQL,true", "MARIADB,true"})
void failedGrantUploadCleansUpAndReleasesOwnership(DatabaseEngine engine, boolean permanent) {
DockerArchiveUploadFixture uploads = failingUploads(73, Integer.MAX_VALUE);
if (permanent) {
uploads.failure = new NotFoundException("container missing");
}
RuntimeException failure = assertThrows(RuntimeException.class,
() -> manager.start("db", "volume", engine, "test-image", "admin", "password", "db"));
assertSame(uploads.failure, failure.getCause());
assertEquals(permanent ? 1 : 6, uploads.commands.size());
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemoveStrict(CONTAINER, null);
verify(docker, never()).execCreateCmd(anyString());
uploads.failures = 0;
assertEquals(CONTAINER,
manager.start("db", "volume", engine, "test-image", "admin", "password", "db").getContainerId());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedRestoreUploadNeverRunsSql(boolean permanent) {
DockerArchiveUploadFixture uploads = failingUploads(73, Integer.MAX_VALUE);
if (permanent) {
uploads.failure = new NotFoundException("container missing");
}
RuntimeException failure = assertThrows(RuntimeException.class,
() -> manager.restorePostgresSnapshot(CONTAINER, "admin", "SELECT 1;"));
assertSame(uploads.failure, failure.getCause());
assertEquals(permanent ? 1 : 6, uploads.commands.size());
verify(docker, never()).execCreateCmd(anyString());
}
@Test
void sqlFailureDoesNotRetryUploadOrSql() {
DockerArchiveUploadFixture uploads = failingUploads(0, 0);
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 1, "", "invalid dump");
RuntimeException failure = assertThrows(RuntimeException.class,
() -> manager.restorePostgresSnapshot(CONTAINER, "admin", "SELECT 1;"));
assertTrue(failure.getMessage().contains("psql restore failed with exit code 1: invalid dump"));
assertEquals(1, uploads.commands.size());
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin")), commands);
}
@Test
void sqlTransportFailureDoesNotRetryUploadOrSql() {
DockerArchiveUploadFixture uploads = failingUploads(0, 0);
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
RuntimeException transportFailure = new RuntimeException(new IOException("Connection reset"));
when(docker.execStartCmd(anyString())).thenThrow(transportFailure);
RuntimeException failure = assertThrows(RuntimeException.class,
() -> manager.restorePostgresSnapshot(CONTAINER, "admin", "SELECT 1;"));
assertSame(transportFailure, failure);
assertEquals(1, uploads.commands.size());
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin")), commands);
}
private static void assertTarEntry(TarArchiveInputStream tar, String name, String content) throws IOException {
TarArchiveEntry entry = tar.getNextEntry();
assertEquals(name, entry.getName());
assertEquals(0755, entry.getMode());
assertArrayEquals(content.getBytes(StandardCharsets.UTF_8), tar.readAllBytes());
}
private DockerArchiveUploadFixture failingUploads(int consumedBytes, int failures) {
DockerArchiveUploadFixture uploads = new DockerArchiveUploadFixture(docker, CONTAINER);
uploads.failures = failures;
uploads.consumedBytes = consumedBytes;
uploads.failure = new RuntimeException(new IOException("Connection reset"));
return uploads;
}
}