mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(rds): pause and resume Aurora Serverless v2 clusters at zero capacity (#4232)
An Aurora cluster whose ServerlessV2ScalingConfiguration has MinCapacity 0 now freezes its database container with docker pause once nothing has used it for SecondsUntilAutoPause, and resumes it for the next client, as Aurora Serverless v2 does. Every client of a backend container holds a lease while it uses it: each connection through the auth proxy (cluster, reader, instance and RDS Proxy endpoints), each RDS Data API call and open transaction, and each command Floci runs inside the container. A client that reaches a paused cluster is held, not refused, until the container runs again, after FLOCI_SERVICES_RDS_AURORA_RESUME_DELAY_MILLIS (default 0; Aurora takes about 15000). A connection that arrives while the pause is under way cancels it. While paused, the cluster and its instances stay available, DescribeEvents reports RDS-EVENT-0370 to 0374 for each instance, and ServerlessDatabaseCapacity, ACUUtilization and CPUUtilization report 0 once a minute. A cluster with a provisioned instance, in a global database or behind an RDS Proxy never pauses. A ModifyDBCluster that changes MinCapacity or SecondsUntilAutoPause resumes a paused cluster. Stopping, deleting or rebooting a cluster, shutting Floci down and resetting its state thaw a paused container first. FLOCI_SERVICES_RDS_AURORA_AUTO_PAUSE_ENABLED=false keeps every cluster running. Closes #4219
This commit is contained in:
1 parent
c15af65bf0
commit
7e4d4dafae
18 files changed
+2264
-26
No files matched your search
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbCluster;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.container.AutoPauseListener;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
|
||||
@@ -73,6 +74,7 @@ import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -1758,6 +1760,102 @@ class RdsServiceTest {
|
||||
assertEquals(300, passwordOnlyChange.getServerlessV2SecondsUntilAutoPause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void auroraClusterHandsItsAutoPauseIntervalToItsContainer() {
|
||||
DbCluster cluster = createAutoPauseCluster(rdsService, "paused", 600);
|
||||
|
||||
verify(containerManager).configureAutoPause(eq(cluster.getDbClusterArn()), eq(600), any());
|
||||
|
||||
rdsService.modifyDbCluster("paused", null, null, 0.5, null, null);
|
||||
verify(containerManager).configureAutoPause(eq(cluster.getDbClusterArn()), isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void auroraClusterMayAutoPauseOnlyWithServerlessInstancesAndNothingHoldingItAwake() {
|
||||
DbCluster cluster = createAutoPauseCluster(rdsService, "paused", 300);
|
||||
AutoPauseListener listener = capturedAutoPauseListener(cluster);
|
||||
assertFalse(listener.mayPause(), "a cluster without instances has nothing to pause");
|
||||
|
||||
createMember(rdsService, "paused-1", "db.serverless", "paused");
|
||||
assertTrue(listener.mayPause());
|
||||
|
||||
createMember(rdsService, "paused-2", "db.r6g.large", "paused");
|
||||
assertFalse(listener.mayPause(), "a provisioned instance keeps the cluster awake");
|
||||
rdsService.deleteDbInstance("paused-2");
|
||||
assertTrue(listener.mayPause());
|
||||
|
||||
rdsService.modifyDbCluster("paused", null, null, 0.5, null, null);
|
||||
assertFalse(listener.mayPause(), "a nonzero MinCapacity never pauses");
|
||||
rdsService.modifyDbCluster("paused", null, null, 0.0, null, null);
|
||||
assertTrue(listener.mayPause());
|
||||
|
||||
rdsService.createGlobalCluster("global-1", "paused", null, null, null, null, null,
|
||||
Map.of(), "us-east-1");
|
||||
assertFalse(listener.mayPause(), "a global database keeps its primary awake");
|
||||
}
|
||||
|
||||
@Test
|
||||
void auroraClusterBehindAnRdsProxyDoesNotAutoPause() {
|
||||
InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
|
||||
RdsService service = proxyStoreService(regionResolver, config, new InMemoryStorage<>(),
|
||||
targetGroups, new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
DbCluster cluster = createAutoPauseCluster(service, "paused", 300);
|
||||
createMember(service, "paused-1", "db.serverless", "paused");
|
||||
AutoPauseListener listener = capturedAutoPauseListener(cluster);
|
||||
assertTrue(listener.mayPause());
|
||||
|
||||
DbProxyTargetGroup targetGroup = persistedTargetGroup("app-proxy", "us-east-1", "123456789012", "abc");
|
||||
targetGroup.setTargets(List.of(new DbProxyTarget("TRACKED_CLUSTER", "paused",
|
||||
cluster.getDbClusterArn(), "localhost", 5432)));
|
||||
targetGroups.put("us-east-1::app-proxy", targetGroup);
|
||||
|
||||
assertFalse(listener.mayPause(), "an RDS Proxy holds connections open to its targets");
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoPauseStepsAreRecordedAsEventsOfEachServerlessInstance() {
|
||||
DbCluster cluster = createAutoPauseCluster(rdsService, "paused", 300);
|
||||
DbInstance member = createMember(rdsService, "paused-1", "db.serverless", "paused");
|
||||
AutoPauseListener listener = capturedAutoPauseListener(cluster);
|
||||
Instant start = Instant.now();
|
||||
|
||||
listener.onAutoPause(AutoPauseListener.Event.PAUSE_INITIATED, start);
|
||||
listener.onAutoPause(AutoPauseListener.Event.PAUSED, start.plusSeconds(1));
|
||||
listener.onAutoPause(AutoPauseListener.Event.STILL_PAUSED, start.plusSeconds(61));
|
||||
listener.onAutoPause(AutoPauseListener.Event.RESUME_INITIATED, start.plusSeconds(90));
|
||||
listener.onAutoPause(AutoPauseListener.Event.RESUMED, start.plusSeconds(91));
|
||||
|
||||
List<RdsEvent> events = rdsService.describeEvents(
|
||||
"paused-1", "db-instance", start.minusSeconds(1), start.plusSeconds(120), null);
|
||||
assertEquals(List.of(
|
||||
"Initiated pause for the DB instance.",
|
||||
"Successfully paused the DB instance.",
|
||||
"Initiated resume for the DB instance.",
|
||||
"Successfully resumed the DB instance."),
|
||||
events.stream().map(RdsEvent::message).toList());
|
||||
RdsEvent paused = events.get(1);
|
||||
assertEquals(List.of("notification", "serverless"), paused.eventCategories());
|
||||
assertEquals(member.getDbInstanceArn(), paused.sourceArn());
|
||||
assertEquals(start.plusSeconds(1), paused.date());
|
||||
}
|
||||
|
||||
private static DbCluster createAutoPauseCluster(RdsService service, String id, int secondsUntilAutoPause) {
|
||||
return service.createDbCluster(id, "aurora-postgresql", "16.3", "admin", "password", "dbname",
|
||||
false, null, null, null, false, "us-east-1", 0.0, 4.0, secondsUntilAutoPause);
|
||||
}
|
||||
|
||||
private static DbInstance createMember(RdsService service, String id, String instanceClass, String clusterId) {
|
||||
return service.createDbInstance(id, "aurora-postgresql", "16.3", "admin", "password", "dbname",
|
||||
instanceClass, 20, false, null, null, clusterId);
|
||||
}
|
||||
|
||||
private AutoPauseListener capturedAutoPauseListener(DbCluster cluster) {
|
||||
ArgumentCaptor<AutoPauseListener> listener = ArgumentCaptor.forClass(AutoPauseListener.class);
|
||||
verify(containerManager, atLeastOnce())
|
||||
.configureAutoPause(eq(cluster.getDbClusterArn()), any(), listener.capture());
|
||||
return listener.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbClusterRejectsServerlessV2ScalingForNonAuroraCluster() {
|
||||
when(config.services().rds().mock()).thenReturn(true);
|
||||
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import io.github.hectorvent.floci.services.rds.container.AutoPauseController.State;
|
||||
import io.github.hectorvent.floci.services.rds.container.AutoPauseListener.Event;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
class AutoPauseControllerTest {
|
||||
|
||||
private static final Duration IDLE = Duration.ofSeconds(300);
|
||||
|
||||
private final ManualScheduler scheduler = new ManualScheduler();
|
||||
private final FakeFreezer freezer = new FakeFreezer();
|
||||
private final RecordingListener listener = new RecordingListener();
|
||||
|
||||
@Test
|
||||
void pausesOnceIdleForSecondsUntilAutoPause() {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
|
||||
scheduler.advance(Duration.ofSeconds(299));
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(0, freezer.pauses.get());
|
||||
|
||||
scheduler.advance(Duration.ofSeconds(1));
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
assertTrue(freezer.paused);
|
||||
assertEquals(List.of(Event.PAUSE_INITIATED, Event.PAUSED), listener.events);
|
||||
assertTrue(listener.times.get(1).isAfter(listener.times.get(0)),
|
||||
"events raised within one instant still keep their order");
|
||||
}
|
||||
|
||||
@Test
|
||||
void openConnectionsKeepItAwakeAndTheIdleClockStartsWhenTheLastOneCloses() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
RdsBackendGate.Lease first = controller.acquire();
|
||||
RdsBackendGate.Lease second = controller.acquire();
|
||||
|
||||
scheduler.advance(Duration.ofHours(1));
|
||||
first.close();
|
||||
scheduler.advance(Duration.ofHours(1));
|
||||
assertEquals(State.RUNNING, controller.state(), "one connection is still open");
|
||||
|
||||
second.close();
|
||||
scheduler.advance(Duration.ofSeconds(299));
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
scheduler.advance(Duration.ofSeconds(1));
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionResumesAPausedContainerBeforeItIsServed() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
|
||||
RdsBackendGate.Lease lease = controller.acquire();
|
||||
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertFalse(freezer.paused);
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
assertEquals(1, controller.leaseCount());
|
||||
assertEquals(List.of(Event.PAUSE_INITIATED, Event.PAUSED, Event.RESUME_INITIATED, Event.RESUMED),
|
||||
listener.events);
|
||||
|
||||
lease.close();
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.PAUSED, controller.state(), "idle again after the connection closed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resumeDelayHoldsConnectionsIncludingOnesThatArriveWhileResuming() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ofSeconds(15));
|
||||
|
||||
Acquirer first = new Acquirer(controller, freezer);
|
||||
awaitCondition(() -> controller.state() == State.RESUMING && first.isWaiting(), "first waits");
|
||||
Acquirer second = new Acquirer(controller, freezer);
|
||||
second.awaitWaiting();
|
||||
|
||||
scheduler.advance(Duration.ofSeconds(14));
|
||||
assertFalse(first.isDone());
|
||||
assertFalse(second.isDone());
|
||||
assertEquals(State.RESUMING, controller.state());
|
||||
|
||||
scheduler.advance(Duration.ofSeconds(1));
|
||||
first.lease();
|
||||
second.lease();
|
||||
assertFalse(first.sawFrozenContainer);
|
||||
assertFalse(second.sawFrozenContainer);
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
assertEquals(2, controller.leaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionDuringPausingCancelsThePause() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
freezer.blockPause();
|
||||
Thread pausing = Thread.ofPlatform().daemon().start(() -> scheduler.advance(IDLE));
|
||||
freezer.awaitPauseEntered();
|
||||
assertEquals(State.PAUSING, controller.state());
|
||||
|
||||
Acquirer client = new Acquirer(controller, freezer);
|
||||
client.awaitWaiting();
|
||||
freezer.releasePause();
|
||||
RdsBackendGate.Lease lease = client.lease();
|
||||
pausing.join(TimeUnit.SECONDS.toMillis(5));
|
||||
|
||||
assertFalse(client.sawFrozenContainer, "the client must not reach the frozen container");
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertFalse(freezer.paused);
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
assertEquals(List.of(Event.PAUSE_INITIATED, Event.PAUSE_CANCELED), listener.events);
|
||||
assertEquals(1, controller.leaseCount());
|
||||
|
||||
lease.close();
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentConnectionsResumeTheContainerOnce() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
freezer.blockUnpause();
|
||||
|
||||
List<Acquirer> clients = new ArrayList<>();
|
||||
for (int i = 0; i < 16; i++) {
|
||||
clients.add(new Acquirer(controller, freezer));
|
||||
}
|
||||
freezer.awaitUnpauseEntered();
|
||||
awaitCondition(() -> clients.stream().allMatch(Acquirer::isWaiting), "every client waits");
|
||||
freezer.releaseUnpause();
|
||||
for (Acquirer client : clients) {
|
||||
client.lease();
|
||||
assertFalse(client.sawFrozenContainer);
|
||||
}
|
||||
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
assertEquals(16, controller.leaseCount());
|
||||
assertEquals(1, listener.events.stream().filter(event -> event == Event.RESUMED).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void turningAutoPauseOffResumesAPausedContainerAndKeepsItRunning() {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
|
||||
controller.configure(null, listener);
|
||||
scheduler.advance(Duration.ZERO);
|
||||
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertFalse(freezer.paused);
|
||||
scheduler.advance(Duration.ofDays(1));
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(1, freezer.pauses.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void turningAutoPauseOffWhilePausingCancelsThePause() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
freezer.blockPause();
|
||||
Thread pausing = Thread.ofPlatform().daemon().start(() -> scheduler.advance(IDLE));
|
||||
freezer.awaitPauseEntered();
|
||||
|
||||
controller.configure(null, listener);
|
||||
freezer.releasePause();
|
||||
pausing.join(TimeUnit.SECONDS.toMillis(5));
|
||||
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertFalse(freezer.paused);
|
||||
assertEquals(List.of(Event.PAUSE_INITIATED, Event.PAUSE_CANCELED), listener.events);
|
||||
scheduler.advance(Duration.ofDays(1));
|
||||
assertEquals(1, freezer.pauses.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void turningAutoPauseOffBeforeTheIntervalEndsPreventsThePause() {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
scheduler.advance(Duration.ofSeconds(200));
|
||||
|
||||
controller.configure(null, listener);
|
||||
scheduler.advance(Duration.ofDays(1));
|
||||
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(0, freezer.pauses.get());
|
||||
assertEquals(0, listener.checks.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheIntervalRestartsTheIdleClock() {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
scheduler.advance(Duration.ofSeconds(200));
|
||||
|
||||
controller.configure(600, listener);
|
||||
scheduler.advance(Duration.ofSeconds(599));
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
scheduler.advance(Duration.ofSeconds(1));
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterThatMayNotPauseIsAskedAgainAfterAnotherInterval() {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
listener.mayPause = false;
|
||||
controller.configure(300, listener);
|
||||
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(1, listener.checks.get());
|
||||
assertEquals(0, freezer.pauses.get());
|
||||
|
||||
listener.mayPause = true;
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
assertEquals(2, listener.checks.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPauseLeavesTheContainerRunningAndTriesAgainLater() {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
freezer.pauseFailure = new IllegalStateException("daemon unavailable");
|
||||
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(List.of(Event.PAUSE_INITIATED, Event.PAUSE_CANCELED), listener.events);
|
||||
|
||||
freezer.pauseFailure = null;
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedResumeFailsTheConnectionAndLeavesTheContainerPaused() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
freezer.unpauseFailure = new IllegalStateException("daemon unavailable");
|
||||
|
||||
assertThrows(IllegalStateException.class, controller::acquire);
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
|
||||
freezer.unpauseFailure = null;
|
||||
controller.acquire();
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertFalse(freezer.paused);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeThawsAPausedContainerAndStopsTracking() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
|
||||
controller.close();
|
||||
|
||||
assertFalse(freezer.paused);
|
||||
assertSame(RdsBackendGate.Lease.NONE, controller.acquire());
|
||||
assertEquals(0, controller.leaseCount());
|
||||
scheduler.advance(Duration.ofDays(1));
|
||||
assertEquals(1, freezer.pauses.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeDuringTheResumeDelayReleasesTheWaitingConnection() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ofSeconds(15));
|
||||
Acquirer client = new Acquirer(controller, freezer);
|
||||
awaitCondition(() -> controller.state() == State.RESUMING && client.isWaiting(), "client waits");
|
||||
|
||||
controller.close();
|
||||
|
||||
assertSame(RdsBackendGate.Lease.NONE, client.lease());
|
||||
assertFalse(freezer.paused);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeWhilePausingThawsTheContainerOnceTheFreezeReturns() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
freezer.blockPause();
|
||||
Thread pausing = Thread.ofPlatform().daemon().start(() -> scheduler.advance(IDLE));
|
||||
freezer.awaitPauseEntered();
|
||||
|
||||
controller.close();
|
||||
freezer.releasePause();
|
||||
pausing.join(TimeUnit.SECONDS.toMillis(5));
|
||||
|
||||
assertFalse(freezer.paused, "a released container must not stay frozen");
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pausedContainerReportsEveryMinuteUntilItResumes() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
|
||||
scheduler.advance(Duration.ofMinutes(2));
|
||||
assertEquals(2, listener.events.stream().filter(event -> event == Event.STILL_PAUSED).count());
|
||||
|
||||
controller.acquire();
|
||||
scheduler.advance(Duration.ofMinutes(10));
|
||||
assertEquals(2, listener.events.stream().filter(event -> event == Event.STILL_PAUSED).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingALeaseTwiceCountsOnce() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
RdsBackendGate.Lease first = controller.acquire();
|
||||
controller.acquire();
|
||||
|
||||
first.close();
|
||||
first.close();
|
||||
|
||||
assertEquals(1, controller.leaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pauseIfIdleRunsTheIdleCheckWithoutWaiting() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
RdsBackendGate.Lease lease = controller.acquire();
|
||||
assertFalse(controller.pauseIfIdle(), "a connection is open");
|
||||
|
||||
lease.close();
|
||||
assertTrue(controller.pauseIfIdle());
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
}
|
||||
|
||||
private AutoPauseController controller(Duration resumeDelay) {
|
||||
return new AutoPauseController("container-1", "localhost", 5432, freezer, scheduler,
|
||||
Runnable::run, scheduler.clock(), resumeDelay);
|
||||
}
|
||||
|
||||
private AutoPauseController pausedController(Duration resumeDelay) {
|
||||
AutoPauseController controller = controller(resumeDelay);
|
||||
controller.configure(300, listener);
|
||||
scheduler.advance(IDLE);
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
return controller;
|
||||
}
|
||||
|
||||
private static void awaitCondition(BooleanSupplier condition, String description) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (!condition.getAsBoolean()) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
fail("Timed out waiting until " + description);
|
||||
}
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs scheduled tasks on whichever thread advances its clock, in the order they fall due. */
|
||||
private static final class ManualScheduler implements AutoPauseController.Scheduler {
|
||||
|
||||
private Instant now = Instant.parse("2026-01-01T00:00:00Z");
|
||||
private long sequence;
|
||||
private final List<Scheduled> tasks = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public synchronized Future<?> schedule(Runnable task, Duration delay) {
|
||||
FutureTask<Void> future = new FutureTask<>(task, null);
|
||||
tasks.add(new Scheduled(now.plus(delay), sequence++, future));
|
||||
return future;
|
||||
}
|
||||
|
||||
void advance(Duration duration) {
|
||||
Instant target;
|
||||
synchronized (this) {
|
||||
target = now.plus(duration);
|
||||
}
|
||||
while (true) {
|
||||
Scheduled next;
|
||||
synchronized (this) {
|
||||
next = tasks.stream()
|
||||
.filter(task -> !task.due().isAfter(target))
|
||||
.min(Comparator.comparing(Scheduled::due).thenComparingLong(Scheduled::sequence))
|
||||
.orElse(null);
|
||||
if (next == null) {
|
||||
now = target;
|
||||
return;
|
||||
}
|
||||
tasks.remove(next);
|
||||
if (next.due().isAfter(now)) {
|
||||
now = next.due();
|
||||
}
|
||||
}
|
||||
// Outside the monitor: the task schedules its successors.
|
||||
next.future().run();
|
||||
}
|
||||
}
|
||||
|
||||
Clock clock() {
|
||||
return new Clock() {
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
synchronized (ManualScheduler.this) {
|
||||
return now;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private record Scheduled(Instant due, long sequence, FutureTask<Void> future) {
|
||||
}
|
||||
}
|
||||
|
||||
private static final class FakeFreezer implements AutoPauseController.Freezer {
|
||||
|
||||
final AtomicInteger pauses = new AtomicInteger();
|
||||
final AtomicInteger unpauses = new AtomicInteger();
|
||||
volatile boolean paused;
|
||||
volatile RuntimeException pauseFailure;
|
||||
volatile RuntimeException unpauseFailure;
|
||||
private volatile CountDownLatch pauseEntered;
|
||||
private volatile CountDownLatch pauseRelease;
|
||||
private volatile CountDownLatch unpauseEntered;
|
||||
private volatile CountDownLatch unpauseRelease;
|
||||
|
||||
@Override
|
||||
public void pause(String containerId) {
|
||||
pauses.incrementAndGet();
|
||||
block(pauseEntered, pauseRelease);
|
||||
if (pauseFailure != null) {
|
||||
throw pauseFailure;
|
||||
}
|
||||
paused = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unpause(String containerId) {
|
||||
unpauses.incrementAndGet();
|
||||
block(unpauseEntered, unpauseRelease);
|
||||
if (unpauseFailure != null) {
|
||||
throw unpauseFailure;
|
||||
}
|
||||
paused = false;
|
||||
}
|
||||
|
||||
void blockPause() {
|
||||
pauseEntered = new CountDownLatch(1);
|
||||
pauseRelease = new CountDownLatch(1);
|
||||
}
|
||||
|
||||
void awaitPauseEntered() throws InterruptedException {
|
||||
assertTrue(pauseEntered.await(5, TimeUnit.SECONDS), "docker pause was not called");
|
||||
}
|
||||
|
||||
void releasePause() {
|
||||
pauseRelease.countDown();
|
||||
}
|
||||
|
||||
void blockUnpause() {
|
||||
unpauseEntered = new CountDownLatch(1);
|
||||
unpauseRelease = new CountDownLatch(1);
|
||||
}
|
||||
|
||||
void awaitUnpauseEntered() throws InterruptedException {
|
||||
assertTrue(unpauseEntered.await(5, TimeUnit.SECONDS), "docker unpause was not called");
|
||||
}
|
||||
|
||||
void releaseUnpause() {
|
||||
unpauseRelease.countDown();
|
||||
}
|
||||
|
||||
private static void block(CountDownLatch entered, CountDownLatch release) {
|
||||
if (entered == null) {
|
||||
return;
|
||||
}
|
||||
entered.countDown();
|
||||
try {
|
||||
if (!release.await(5, TimeUnit.SECONDS)) {
|
||||
throw new IllegalStateException("The test never released the Docker call");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RecordingListener implements AutoPauseListener {
|
||||
|
||||
final List<Event> events = new CopyOnWriteArrayList<>();
|
||||
final List<Instant> times = new CopyOnWriteArrayList<>();
|
||||
final AtomicInteger checks = new AtomicInteger();
|
||||
volatile boolean mayPause = true;
|
||||
|
||||
@Override
|
||||
public boolean mayPause() {
|
||||
checks.incrementAndGet();
|
||||
return mayPause;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAutoPause(Event event, Instant at) {
|
||||
events.add(event);
|
||||
times.add(at);
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls acquire() on a platform thread of its own, so that a test can watch it wait. */
|
||||
private static final class Acquirer {
|
||||
|
||||
private final CompletableFuture<RdsBackendGate.Lease> result = new CompletableFuture<>();
|
||||
private final Thread thread;
|
||||
private volatile boolean sawFrozenContainer;
|
||||
|
||||
Acquirer(AutoPauseController controller, FakeFreezer freezer) {
|
||||
thread = Thread.ofPlatform().daemon().start(() -> {
|
||||
try {
|
||||
RdsBackendGate.Lease lease = controller.acquire();
|
||||
sawFrozenContainer = freezer.paused;
|
||||
result.complete(lease);
|
||||
} catch (InterruptedException | RuntimeException e) {
|
||||
result.completeExceptionally(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
boolean isWaiting() {
|
||||
Thread.State state = thread.getState();
|
||||
return state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING;
|
||||
}
|
||||
|
||||
void awaitWaiting() {
|
||||
awaitCondition(this::isWaiting, "the client waits");
|
||||
}
|
||||
|
||||
boolean isDone() {
|
||||
return result.isDone();
|
||||
}
|
||||
|
||||
RdsBackendGate.Lease lease() throws Exception {
|
||||
return result.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbCluster;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static io.restassured.http.ContentType.URLENC;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* Aurora Serverless v2 auto-pause against a real PostgreSQL container: an idle cluster with
|
||||
* MinCapacity 0 is frozen with docker pause while it reports "available", zero capacity and the
|
||||
* pause events, and the next connection through its endpoint resumes it and finds its data. The
|
||||
* API does not accept a SecondsUntilAutoPause below 300, so the test runs the idle check directly
|
||||
* instead of waiting for it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@Tag("docker")
|
||||
class RdsAuroraAutoPauseIntegrationTest {
|
||||
|
||||
private static final String RDS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260923/us-east-1/rds/aws4_request, "
|
||||
+ "SignedHeaders=content-type;host, Signature=test";
|
||||
private static final String OWNER_RDS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=222222222222/20260923/us-east-1/rds/aws4_request, "
|
||||
+ "SignedHeaders=content-type;host, Signature=test";
|
||||
private static final String CLOUDWATCH_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260923/us-east-1/monitoring/aws4_request";
|
||||
private static final String MASTER_USER = "master";
|
||||
private static final String MASTER_PASSWORD = "Master123!";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
RdsService rdsService;
|
||||
|
||||
@Inject
|
||||
RdsContainerManager containerManager;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void checkDocker() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
} catch (Exception e) {
|
||||
assumeTrue(false, "Docker is not available: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void idleClusterPausesAndItsNextConnectionResumesIt() throws Exception {
|
||||
String clusterId = "auto-pause-" + Long.toString(System.nanoTime(), 36);
|
||||
String instanceId = clusterId + "-1";
|
||||
Instant start = Instant.now();
|
||||
rds("CreateDBCluster")
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("Engine", "aurora-postgresql")
|
||||
.formParam("MasterUsername", MASTER_USER)
|
||||
.formParam("MasterUserPassword", MASTER_PASSWORD)
|
||||
.formParam("DatabaseName", "appdb")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MinCapacity", "0")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MaxCapacity", "2")
|
||||
.formParam("ServerlessV2ScalingConfiguration.SecondsUntilAutoPause", "300")
|
||||
.when().post("/").then().statusCode(200);
|
||||
try {
|
||||
rds("CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("Engine", "aurora-postgresql")
|
||||
.formParam("DBInstanceClass", "db.serverless")
|
||||
.when().post("/").then().statusCode(200);
|
||||
DbCluster cluster = rdsService.getDbCluster(clusterId);
|
||||
String containerId = cluster.getContainerId();
|
||||
String jdbcUrl = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().port()
|
||||
+ "/appdb?sslmode=disable";
|
||||
try (Connection connection = DriverManager.getConnection(jdbcUrl, MASTER_USER, MASTER_PASSWORD);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE marker(v text); INSERT INTO marker VALUES ('before-pause');");
|
||||
}
|
||||
|
||||
// The proxy lets go of the closed connection on its own thread.
|
||||
await().atMost(Duration.ofSeconds(10))
|
||||
.until(() -> containerManager.pauseIfIdle(cluster.getDbClusterArn()));
|
||||
assertTrue(isPaused(containerId), "the idle cluster's container is frozen");
|
||||
rds("DescribeDBClusters").formParam("DBClusterIdentifier", clusterId)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Status>available</Status>"));
|
||||
rds("DescribeDBInstances").formParam("DBInstanceIdentifier", instanceId)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<DBInstanceStatus>available</DBInstanceStatus>"));
|
||||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
|
||||
events(instanceId).then().statusCode(200)
|
||||
.body(containsString("<Message>Initiated pause for the DB instance.</Message>"))
|
||||
.body(containsString("<Message>Successfully paused the DB instance.</Message>")));
|
||||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
|
||||
for (String metricName : List.of("ServerlessDatabaseCapacity", "CPUUtilization")) {
|
||||
List<Float> minimums = metricMinimums(metricName, clusterId, start);
|
||||
assertFalse(minimums.isEmpty(), "a paused cluster reports its " + metricName);
|
||||
assertEquals(0.0f, minimums.get(minimums.size() - 1), metricName);
|
||||
}
|
||||
});
|
||||
|
||||
try (Connection connection = DriverManager.getConnection(jdbcUrl, MASTER_USER, MASTER_PASSWORD);
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery("SELECT v FROM marker")) {
|
||||
assertTrue(rows.next(), "the data written before the pause is still there");
|
||||
assertEquals("before-pause", rows.getString(1));
|
||||
}
|
||||
assertFalse(isPaused(containerId), "the connection resumed the container");
|
||||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
|
||||
events(instanceId).then().statusCode(200)
|
||||
.body(containsString("<Message>Initiated resume for the DB instance.</Message>"))
|
||||
.body(containsString("<Message>Successfully resumed the DB instance.</Message>")));
|
||||
|
||||
await().atMost(Duration.ofSeconds(10))
|
||||
.until(() -> containerManager.pauseIfIdle(cluster.getDbClusterArn()));
|
||||
rds("ModifyDBCluster")
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("ServerlessV2ScalingConfiguration.MinCapacity", "0.5")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MaxCapacity", "2")
|
||||
.when().post("/").then().statusCode(200);
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> !isPaused(containerId));
|
||||
assertFalse(containerManager.pauseIfIdle(cluster.getDbClusterArn()),
|
||||
"a nonzero MinCapacity keeps the cluster running");
|
||||
} finally {
|
||||
rds("DeleteDBInstance")
|
||||
.formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/");
|
||||
rds("DeleteDBCluster")
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pauseEventsBelongToTheAccountThatOwnsTheCluster() throws Exception {
|
||||
String clusterId = "auto-pause-owner-" + Long.toString(System.nanoTime(), 36);
|
||||
String instanceId = clusterId + "-1";
|
||||
XmlPath created = rds(OWNER_RDS_AUTH, "CreateDBCluster")
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("Engine", "aurora-postgresql")
|
||||
.formParam("MasterUsername", MASTER_USER)
|
||||
.formParam("MasterUserPassword", MASTER_PASSWORD)
|
||||
.formParam("DatabaseName", "appdb")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MinCapacity", "0")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MaxCapacity", "2")
|
||||
.formParam("ServerlessV2ScalingConfiguration.SecondsUntilAutoPause", "300")
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
String clusterArn = created.getString("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.DBClusterArn");
|
||||
int port = created.getInt("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.Port");
|
||||
try {
|
||||
rds(OWNER_RDS_AUTH, "CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("Engine", "aurora-postgresql")
|
||||
.formParam("DBInstanceClass", "db.serverless")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
// The pause and resume events reach RDS on a background thread, outside any request.
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> containerManager.pauseIfIdle(clusterArn));
|
||||
try (Connection connection = DriverManager.getConnection(
|
||||
"jdbc:postgresql://127.0.0.1:" + port + "/appdb?sslmode=disable", MASTER_USER, MASTER_PASSWORD)) {
|
||||
assertTrue(connection.isValid(5), "the connection resumed the cluster");
|
||||
}
|
||||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
|
||||
events(OWNER_RDS_AUTH, instanceId).then().statusCode(200)
|
||||
.body(containsString("<Message>Initiated pause for the DB instance.</Message>"))
|
||||
.body(containsString("<Message>Successfully paused the DB instance.</Message>"))
|
||||
.body(containsString("<Message>Initiated resume for the DB instance.</Message>"))
|
||||
.body(containsString("<Message>Successfully resumed the DB instance.</Message>")));
|
||||
events(RDS_AUTH, instanceId).then().statusCode(200)
|
||||
.body(not(containsString("<Event>")));
|
||||
} finally {
|
||||
rds(OWNER_RDS_AUTH, "DeleteDBInstance")
|
||||
.formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/");
|
||||
rds(OWNER_RDS_AUTH, "DeleteDBCluster")
|
||||
.formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
|
||||
private static RequestSpecification rds(String action) {
|
||||
return rds(RDS_AUTH, action);
|
||||
}
|
||||
|
||||
private static RequestSpecification rds(String authorization, String action) {
|
||||
return given().header("Authorization", authorization)
|
||||
.contentType(URLENC)
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2014-10-31");
|
||||
}
|
||||
|
||||
private static Response events(String instanceId) {
|
||||
return events(RDS_AUTH, instanceId);
|
||||
}
|
||||
|
||||
private static Response events(String authorization, String instanceId) {
|
||||
return rds(authorization, "DescribeEvents")
|
||||
.formParam("SourceType", "db-instance")
|
||||
.formParam("SourceIdentifier", instanceId)
|
||||
.formParam("Duration", "60")
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private static List<Float> metricMinimums(String metricName, String clusterId, Instant from) {
|
||||
String body = """
|
||||
{"Namespace":"AWS/RDS","MetricName":"%s",
|
||||
"Dimensions":[{"Name":"DBClusterIdentifier","Value":"%s"}],
|
||||
"StartTime":%d,"EndTime":%d,"Period":60,"Statistics":["Minimum"]}
|
||||
""".formatted(metricName, clusterId, from.minusSeconds(60).getEpochSecond(),
|
||||
Instant.now().plusSeconds(60).getEpochSecond());
|
||||
return given().contentType("application/x-amz-json-1.0")
|
||||
.header("Authorization", CLOUDWATCH_AUTH)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics")
|
||||
.body(body)
|
||||
.post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getList("Datapoints.Minimum", Float.class);
|
||||
}
|
||||
|
||||
private boolean isPaused(String containerId) {
|
||||
return Boolean.TRUE.equals(dockerClient.inspectContainerCmd(containerId).exec().getState().getPaused());
|
||||
}
|
||||
}
|
||||
+119
@@ -12,9 +12,11 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -24,6 +26,8 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.command.PauseContainerCmd;
|
||||
import com.github.dockerjava.api.command.UnpauseContainerCmd;
|
||||
import com.github.dockerjava.api.model.Bind;
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
|
||||
@@ -31,14 +35,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -1155,6 +1162,118 @@ class RdsContainerManagerTest {
|
||||
"Script must assign the first argument to the USER variable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoPausedContainerResumesForItsNextClientAndIsThawedBeforeItStops() throws Exception {
|
||||
EmulatorConfig config = config(tempDir.resolve("auto-pause-root"));
|
||||
when(config.services().rds().auroraAutoPauseEnabled()).thenReturn(true);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
|
||||
"cluster-container", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
PauseContainerCmd pause = mock(PauseContainerCmd.class);
|
||||
UnpauseContainerCmd unpause = mock(UnpauseContainerCmd.class);
|
||||
when(dockerClient.pauseContainerCmd("cluster-container")).thenReturn(pause);
|
||||
when(dockerClient.unpauseContainerCmd("cluster-container")).thenReturn(unpause);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
RdsContainerManager manager = autoPauseManager(config, lifecycleManager);
|
||||
String runtimeId = "arn:aws:rds:us-east-1:000000000000:cluster:paused";
|
||||
RdsContainerHandle handle = manager.start(runtimeId, "paused", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
manager.configureAutoPause(runtimeId, 300, alwaysMayPause());
|
||||
|
||||
try (RdsBackendGate.Lease client = manager.enter("db1", 3306)) {
|
||||
assertFalse(manager.pauseIfIdle(runtimeId), "a client is connected");
|
||||
}
|
||||
assertTrue(manager.pauseIfIdle(runtimeId));
|
||||
verify(pause).exec();
|
||||
|
||||
manager.enter("db1", 3306).close();
|
||||
verify(unpause).exec();
|
||||
|
||||
assertTrue(manager.pauseIfIdle(runtimeId));
|
||||
manager.stop(handle);
|
||||
InOrder order = inOrder(unpause, lifecycleManager);
|
||||
order.verify(unpause, times(2)).exec();
|
||||
order.verify(lifecycleManager).stopAndRemoveStrict(eq("cluster-container"), any());
|
||||
assertSame(RdsBackendGate.Lease.NONE, manager.enter("db1", 3306));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetThawsAPausedContainerAndEndsItsAutoPause() throws Exception {
|
||||
EmulatorConfig config = config(tempDir.resolve("auto-pause-root"));
|
||||
when(config.services().rds().auroraAutoPauseEnabled()).thenReturn(true);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
|
||||
"cluster-container", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
UnpauseContainerCmd unpause = mock(UnpauseContainerCmd.class);
|
||||
when(dockerClient.pauseContainerCmd("cluster-container")).thenReturn(mock(PauseContainerCmd.class));
|
||||
when(dockerClient.unpauseContainerCmd("cluster-container")).thenReturn(unpause);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
RdsContainerManager manager = autoPauseManager(config, lifecycleManager);
|
||||
String runtimeId = "arn:aws:rds:us-east-1:000000000000:cluster:paused";
|
||||
manager.start(runtimeId, "paused", null, DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
manager.configureAutoPause(runtimeId, 300, alwaysMayPause());
|
||||
assertTrue(manager.pauseIfIdle(runtimeId));
|
||||
|
||||
manager.clear();
|
||||
|
||||
verify(unpause).exec();
|
||||
assertSame(RdsBackendGate.Lease.NONE, manager.enter("db1", 3306));
|
||||
assertFalse(manager.pauseIfIdle(runtimeId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerStartedOnAnAddressTakesItOverFromOneDockerRemoved() throws Exception {
|
||||
EmulatorConfig config = config(tempDir.resolve("auto-pause-root"));
|
||||
when(config.services().rds().auroraAutoPauseEnabled()).thenReturn(true);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
ContainerLifecycleManager.EndpointInfo address = new ContainerLifecycleManager.EndpointInfo("db1", 3306);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo("removed-container", Map.of(3306, address)),
|
||||
new ContainerLifecycleManager.ContainerInfo("new-container", Map.of(3306, address)));
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
when(dockerClient.pauseContainerCmd(any())).thenReturn(mock(PauseContainerCmd.class));
|
||||
when(dockerClient.unpauseContainerCmd(any())).thenReturn(mock(UnpauseContainerCmd.class));
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
RdsContainerManager manager = autoPauseManager(config, lifecycleManager);
|
||||
String removedRuntime = "arn:aws:rds:us-east-1:000000000000:cluster:removed";
|
||||
manager.start(removedRuntime, "removed", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
manager.configureAutoPause(removedRuntime, 300, alwaysMayPause());
|
||||
assertTrue(manager.pauseIfIdle(removedRuntime));
|
||||
|
||||
manager.start("arn:aws:rds:us-east-1:000000000000:cluster:new", "new", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
manager.enter("db1", 3306).close();
|
||||
|
||||
verify(dockerClient, never()).unpauseContainerCmd("new-container");
|
||||
assertFalse(manager.pauseIfIdle(removedRuntime), "the removed container's auto-pause is gone");
|
||||
}
|
||||
|
||||
private RdsContainerManager autoPauseManager(EmulatorConfig config, ContainerLifecycleManager lifecycleManager) {
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
return new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
}
|
||||
|
||||
private static AutoPauseListener alwaysMayPause() {
|
||||
return new AutoPauseListener() {
|
||||
@Override
|
||||
public boolean mayPause() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAutoPause(Event event, Instant at) {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(Path hostRoot) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
|
||||
+34
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -13,7 +14,9 @@ import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -100,6 +103,37 @@ class RdsAuthProxyBoundsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void holdsTheClientUntilTheBackendGateAdmitsItAndReleasesTheLeaseWhenItLeaves() throws Exception {
|
||||
fakeBackend = new ServerSocket(0);
|
||||
fakeBackend.setSoTimeout(300);
|
||||
CountDownLatch admit = new CountDownLatch(1);
|
||||
CountDownLatch released = new CountDownLatch(1);
|
||||
RdsBackendGate gate = (host, port) -> {
|
||||
admit.await();
|
||||
return released::countDown;
|
||||
};
|
||||
int proxyPort = freePort();
|
||||
proxy = new RdsAuthProxy("db-1", "localhost", fakeBackend.getLocalPort(),
|
||||
DatabaseEngine.SQLSERVER, false, "sa", "Secret123", null,
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
|
||||
5000, 5000, 100, null, gate);
|
||||
proxy.start(proxyPort);
|
||||
|
||||
try (Socket client = new Socket("localhost", proxyPort)) {
|
||||
client.setSoTimeout(5000);
|
||||
assertThrows(SocketTimeoutException.class, fakeBackend::accept,
|
||||
"the proxy reached the backend before the gate admitted the client");
|
||||
admit.countDown();
|
||||
fakeBackend.setSoTimeout(5000);
|
||||
try (Socket backendSide = fakeBackend.accept()) {
|
||||
backendSide.getOutputStream().write('x');
|
||||
assertEquals('x', client.getInputStream().read(), "the held client is served once admitted");
|
||||
}
|
||||
}
|
||||
assertTrue(released.await(5, TimeUnit.SECONDS), "the lease is released when the connection ends");
|
||||
}
|
||||
|
||||
private RdsAuthProxy newProxy(int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
|
||||
int maxConnections) {
|
||||
return new RdsAuthProxy("db-1", "localhost", fakeBackend.getLocalPort(),
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
@@ -18,9 +19,12 @@ import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.h2.Driver;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
@@ -773,6 +777,66 @@ class RdsDataServiceTest {
|
||||
assertEquals(0L, harness.countById("shutdown"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void statementOutsideATransactionHoldsTheClusterAwakeOnlyWhileItRuns() throws Exception {
|
||||
TestHarness harness = new TestHarness();
|
||||
harness.createTables();
|
||||
|
||||
harness.service.executeStatement(harness.request("select 1"), REGION);
|
||||
|
||||
assertEquals(List.of("127.0.0.1:3306"), harness.gate.entered);
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactionHoldsTheClusterAwakeUntilItEnds() throws Exception {
|
||||
TestHarness harness = new TestHarness();
|
||||
harness.createTables();
|
||||
|
||||
String committed = harness.service.beginTransaction(harness.beginRequest(), REGION)
|
||||
.get("transactionId").asText();
|
||||
ObjectNode insert = harness.request("insert into data_api_items(id, title, score) values ('held', 'Held', 1)");
|
||||
insert.put("transactionId", committed);
|
||||
harness.service.executeStatement(insert, REGION);
|
||||
assertEquals(1, harness.gate.held.get(), "an open transaction keeps the cluster from pausing");
|
||||
harness.service.commitTransaction(harness.transactionRequest(committed), REGION);
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
|
||||
String rolledBack = harness.service.beginTransaction(harness.beginRequest(), REGION)
|
||||
.get("transactionId").asText();
|
||||
assertEquals(1, harness.gate.held.get());
|
||||
harness.service.rollbackTransaction(harness.transactionRequest(rolledBack), REGION);
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
assertEquals(2, harness.gate.entered.size(), "statements in a transaction reuse its hold");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredTransactionLetsTheClusterPause() throws Exception {
|
||||
TestHarness harness = new TestHarness(Duration.ofMillis(50));
|
||||
String tx = harness.service.beginTransaction(harness.beginRequest(), REGION)
|
||||
.get("transactionId").asText();
|
||||
Thread.sleep(200);
|
||||
|
||||
ObjectNode next = harness.request("select 1");
|
||||
next.put("transactionId", tx);
|
||||
assertThrows(AwsException.class, () -> harness.service.executeStatement(next, REGION));
|
||||
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterThatCannotResumeFailsTheRequestAsAnInternalError() {
|
||||
TestHarness harness = new TestHarness();
|
||||
harness.gate.failure = new IllegalStateException("Could not resume auto-paused RDS container");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> harness.service.executeStatement(harness.request("select 1"), REGION));
|
||||
|
||||
assertEquals("InternalServerErrorException", error.getErrorCode());
|
||||
assertEquals(500, error.getHttpStatus());
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closesConnectionWhenTransactionSetupFails() {
|
||||
RdsDataResourceResolver resolver = mock(RdsDataResourceResolver.class);
|
||||
@@ -921,10 +985,33 @@ class RdsDataServiceTest {
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts the backends the Data API enters and the holds still open on them. */
|
||||
private static final class CountingGate implements RdsBackendGate {
|
||||
private final List<String> entered = new CopyOnWriteArrayList<>();
|
||||
private final AtomicInteger held = new AtomicInteger();
|
||||
private volatile IllegalStateException failure;
|
||||
|
||||
@Override
|
||||
public Lease enter(String host, int port) {
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
entered.add(host + ":" + port);
|
||||
held.incrementAndGet();
|
||||
AtomicBoolean closed = new AtomicBoolean();
|
||||
return () -> {
|
||||
if (closed.compareAndSet(false, true)) {
|
||||
held.decrementAndGet();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private final class TestHarness {
|
||||
private final String jdbcUrl;
|
||||
private final RdsDataResourceResolver resolver;
|
||||
private final RdsDataResourceResolver.DatabaseTarget target;
|
||||
private final CountingGate gate = new CountingGate();
|
||||
private final RdsDataService service;
|
||||
|
||||
private TestHarness() {
|
||||
@@ -966,7 +1053,7 @@ class RdsDataServiceTest {
|
||||
return getConnection();
|
||||
}
|
||||
};
|
||||
service = new RdsDataService(resolver, secrets, objectMapper, connectionFactory, transactionTtl);
|
||||
service = new RdsDataService(resolver, secrets, objectMapper, connectionFactory, transactionTtl, gate);
|
||||
}
|
||||
|
||||
private Connection getConnection() throws SQLException {
|
||||
|
||||
Reference in new issue
Block a user