mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -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
@@ -1560,6 +1560,18 @@ public interface EmulatorConfig {
|
||||
int proxyBackendConnectTimeoutMillis();
|
||||
@WithDefault("100")
|
||||
int proxyMaxConnections();
|
||||
|
||||
/** Whether an Aurora Serverless v2 cluster with MinCapacity 0 pauses its container
|
||||
* after SecondsUntilAutoPause without connections, as Aurora does.
|
||||
* Env: FLOCI_SERVICES_RDS_AURORA_AUTO_PAUSE_ENABLED */
|
||||
@WithDefault("true")
|
||||
boolean auroraAutoPauseEnabled();
|
||||
|
||||
/** How long the first connection to an auto-paused cluster is held while it resumes.
|
||||
* Aurora takes about 15 seconds; 0 resumes at once.
|
||||
* Env: FLOCI_SERVICES_RDS_AURORA_RESUME_DELAY_MILLIS */
|
||||
@WithDefault("0")
|
||||
int auroraResumeDelayMillis();
|
||||
}
|
||||
|
||||
interface RdsDataServiceConfig {
|
||||
|
||||
@@ -20,9 +20,13 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||
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.DatabaseEngine;
|
||||
@@ -180,11 +184,16 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
|
||||
private final ResourceGroupsTaggingService taggingService;
|
||||
// Null when a test constructs the service without CloudWatch; auto-pause then reports no metrics.
|
||||
private final CloudWatchMetricsService metricsService;
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$");
|
||||
private static final Pattern SAFE_IMAGE_TAG_PATTERN = Pattern.compile("[A-Za-z0-9._-]+");
|
||||
private static final int SERVERLESS_V2_DEFAULT_AUTO_PAUSE_SECONDS = 300;
|
||||
private static final int SERVERLESS_V2_MAX_AUTO_PAUSE_SECONDS = 86_400;
|
||||
/** Only Aurora Serverless v2 instances pause; a provisioned one keeps its whole cluster awake. */
|
||||
private static final String SERVERLESS_V2_INSTANCE_CLASS = "db.serverless";
|
||||
private static final List<String> AUTO_PAUSE_EVENT_CATEGORIES = List.of("notification", "serverless");
|
||||
private static final Pattern DB_PROXY_NAME_PATTERN =
|
||||
Pattern.compile("[a-zA-Z](?:-?[a-zA-Z0-9]+)*");
|
||||
/**
|
||||
@@ -213,7 +222,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
DockerHostResolver dockerHostResolver,
|
||||
CurrentContainerNetworkResolver currentContainerNetworkResolver,
|
||||
ResourceGroupsTaggingService taggingService,
|
||||
KmsService kmsService) {
|
||||
KmsService kmsService,
|
||||
CloudWatchMetricsService metricsService) {
|
||||
this.containerManager = containerManager;
|
||||
this.proxyManager = proxyManager;
|
||||
this.ec2Service = ec2Service;
|
||||
@@ -224,6 +234,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
|
||||
this.taggingService = taggingService;
|
||||
this.metricsService = metricsService;
|
||||
this.instances = storageFactory.create("rds", "rds-instances.json",
|
||||
new TypeReference<Map<String, DbInstance>>() {});
|
||||
this.clusters = storageFactory.create("rds", "rds-clusters.json",
|
||||
@@ -381,6 +392,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
this.proxies = proxies;
|
||||
this.proxyTargetGroups = proxyTargetGroups;
|
||||
this.taggingService = taggingService;
|
||||
this.metricsService = null;
|
||||
this.globalClusters = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
|
||||
this.snapshots = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
|
||||
this.clusterSnapshots = new InMemoryStorage<>();
|
||||
@@ -2954,6 +2966,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
(user, pw) -> validateDbClusterPasswordForScope(accountId, clusterRegion, id, user, pw),
|
||||
proxyBinding(cluster.getEngine(), cluster.getEndpoint().address(), cluster.getProxyPort(),
|
||||
clusterRegion, accountId, cluster.getDbClusterResourceId()));
|
||||
applyAutoPause(cluster);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3183,6 +3196,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
cluster.setContainerHost(started.getHost());
|
||||
cluster.setContainerPort(started.getPort());
|
||||
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
|
||||
applyAutoPause(cluster);
|
||||
LOG.infov("Backing database container for DB cluster {0} started on retry", id);
|
||||
return cluster;
|
||||
}
|
||||
@@ -3469,6 +3483,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
applyAutoPause(cluster);
|
||||
LOG.infov("DB cluster {0} created (mock={1}), engine={2}, endpoint={3}:{4}",
|
||||
id, String.valueOf(mock), engine, endpoint.address(), String.valueOf(endpoint.port()));
|
||||
return cluster;
|
||||
@@ -3547,6 +3562,175 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
|| "aurora-postgresql".equalsIgnoreCase(engineIdentifier));
|
||||
}
|
||||
|
||||
// ── Aurora Serverless v2 auto-pause ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hands a cluster's auto-pause interval to its container: SecondsUntilAutoPause for an Aurora
|
||||
* cluster whose MinCapacity is 0, otherwise none, which keeps the container running.
|
||||
*/
|
||||
private void applyAutoPause(DbCluster cluster) {
|
||||
if (config.services().rds().mock() || cluster.getDbClusterArn() == null) {
|
||||
return;
|
||||
}
|
||||
Integer secondsUntilAutoPause = isAuroraEngine(cluster.getEngineIdentifier())
|
||||
? cluster.getServerlessV2SecondsUntilAutoPause()
|
||||
: null;
|
||||
containerManager.configureAutoPause(cluster.getDbClusterArn(), secondsUntilAutoPause,
|
||||
new ClusterAutoPause(accountIdFromArn(cluster.getDbClusterArn()),
|
||||
regionFromArn(cluster.getDbClusterArn()), cluster.getDbClusterIdentifier()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Aurora's conditions for pausing an idle cluster besides its zero MinCapacity: the cluster
|
||||
* and its instances are available, every instance is Aurora Serverless v2 (a provisioned one
|
||||
* keeps the writer awake), and the cluster is neither in a global database nor the target of
|
||||
* an RDS Proxy, which holds connections open to it.
|
||||
*/
|
||||
private boolean clusterMayAutoPause(String accountId, String region, String clusterId) {
|
||||
DbCluster cluster = findClusterForScope(accountId, region, clusterId);
|
||||
if (cluster == null
|
||||
|| (cluster.getStatus() != null && cluster.getStatus() != DbInstanceStatus.AVAILABLE)
|
||||
|| cluster.getServerlessV2SecondsUntilAutoPause() == null
|
||||
|| cluster.getGlobalClusterIdentifier() != null) {
|
||||
return false;
|
||||
}
|
||||
List<String> memberIds = List.copyOf(cluster.getDbClusterMembers());
|
||||
if (memberIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String memberId : memberIds) {
|
||||
DbInstance member = findInstanceForScope(accountId, region, memberId);
|
||||
if (member == null
|
||||
|| (member.getStatus() != null && member.getStatus() != DbInstanceStatus.AVAILABLE)
|
||||
|| !SERVERLESS_V2_INSTANCE_CLASS.equalsIgnoreCase(member.getDbInstanceClass())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return !isDbProxyTargetOfAccount(accountId, region, clusterId, memberIds);
|
||||
}
|
||||
|
||||
/** {@link #isRegisteredProxyTarget} for an explicit account, since auto-pause runs outside a request. */
|
||||
private boolean isDbProxyTargetOfAccount(String accountId, String region, String clusterId,
|
||||
List<String> memberIds) {
|
||||
List<DbProxyTargetGroup> targetGroups =
|
||||
proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware
|
||||
? aware.scanForAccount(accountId, key -> true)
|
||||
: proxyTargetGroups.scan(key -> true);
|
||||
return targetGroups.stream()
|
||||
.filter(targetGroup -> targetGroupBelongsTo(targetGroup, accountId, region))
|
||||
.flatMap(targetGroup -> targetGroup.getTargets().stream())
|
||||
.anyMatch(target -> ("TRACKED_CLUSTER".equals(target.getType())
|
||||
&& clusterId.equals(target.getRdsResourceId()))
|
||||
|| ("RDS_INSTANCE".equals(target.getType())
|
||||
&& memberIds.contains(target.getRdsResourceId())));
|
||||
}
|
||||
|
||||
private List<DbInstance> serverlessMembers(String accountId, String region, String clusterId) {
|
||||
DbCluster cluster = findClusterForScope(accountId, region, clusterId);
|
||||
if (cluster == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<DbInstance> members = new ArrayList<>();
|
||||
for (String memberId : List.copyOf(cluster.getDbClusterMembers())) {
|
||||
DbInstance member = findInstanceForScope(accountId, region, memberId);
|
||||
if (member != null && SERVERLESS_V2_INSTANCE_CLASS.equalsIgnoreCase(member.getDbInstanceClass())) {
|
||||
members.add(member);
|
||||
}
|
||||
}
|
||||
return members;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records an auto-pause step as the RDS-EVENT-0370 to 0374 event of each Serverless v2 instance,
|
||||
* under the cluster's own account, since auto-pause runs outside a request.
|
||||
*/
|
||||
private void recordAutoPauseEvents(String accountId, List<DbInstance> members,
|
||||
AutoPauseListener.Event event, Instant at) {
|
||||
String message = switch (event) {
|
||||
case PAUSE_INITIATED -> "Initiated pause for the DB instance.";
|
||||
case PAUSE_CANCELED -> "Pause was canceled for the DB instance.";
|
||||
case PAUSED -> "Successfully paused the DB instance.";
|
||||
case RESUME_INITIATED -> "Initiated resume for the DB instance.";
|
||||
case RESUMED -> "Successfully resumed the DB instance.";
|
||||
// Aurora emits no event while an instance stays paused; that only shows in metrics.
|
||||
case STILL_PAUSED -> null;
|
||||
};
|
||||
if (message == null) {
|
||||
return;
|
||||
}
|
||||
for (DbInstance member : members) {
|
||||
String eventId = "auto-pause:" + member.getDbInstanceArn() + ":" + event + ":" + at;
|
||||
putEventForAccount(accountId, eventId, new RdsEvent(eventId, member.getDbInstanceIdentifier(),
|
||||
"db-instance", message, AUTO_PAUSE_EVENT_CATEGORIES, at, member.getDbInstanceArn()));
|
||||
}
|
||||
}
|
||||
|
||||
private void putEventForAccount(String accountId, String eventId, RdsEvent event) {
|
||||
if (events instanceof AccountAwareStorageBackend<RdsEvent> aware) {
|
||||
aware.putForAccount(accountId, eventId, event);
|
||||
} else {
|
||||
events.put(eventId, event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes what a paused Aurora Serverless v2 instance still sends CloudWatch: a zero
|
||||
* ServerlessDatabaseCapacity, ACUUtilization and CPUUtilization, for the cluster and for each
|
||||
* instance.
|
||||
*/
|
||||
private void publishPausedCapacity(String accountId, String region, String clusterId,
|
||||
List<DbInstance> members, Instant at) {
|
||||
if (metricsService == null) {
|
||||
return;
|
||||
}
|
||||
publishZeroCapacity(accountId, region, new Dimension("DBClusterIdentifier", clusterId), at);
|
||||
for (DbInstance member : members) {
|
||||
publishZeroCapacity(accountId, region,
|
||||
new Dimension("DBInstanceIdentifier", member.getDbInstanceIdentifier()), at);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishZeroCapacity(String accountId, String region, Dimension dimension, Instant at) {
|
||||
for (String metricName : List.of("ServerlessDatabaseCapacity", "ACUUtilization", "CPUUtilization")) {
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(metricName);
|
||||
datum.setUnit("ServerlessDatabaseCapacity".equals(metricName) ? "Count" : "Percent");
|
||||
datum.setDimensions(List.of(dimension));
|
||||
datum.setTimestamp(at.getEpochSecond());
|
||||
datum.setValue(0.0);
|
||||
metricsService.publishMetricForAccount(accountId, "AWS/RDS", datum, region,
|
||||
"rds-auto-pause:" + dimension.name() + "=" + dimension.value() + ":" + metricName + ":" + at);
|
||||
}
|
||||
}
|
||||
|
||||
/** The auto-pause of one cluster's container: Aurora's pause rules, its events and its metrics. */
|
||||
private final class ClusterAutoPause implements AutoPauseListener {
|
||||
|
||||
private final String accountId;
|
||||
private final String region;
|
||||
private final String clusterId;
|
||||
|
||||
private ClusterAutoPause(String accountId, String region, String clusterId) {
|
||||
this.accountId = accountId;
|
||||
this.region = region;
|
||||
this.clusterId = clusterId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mayPause() {
|
||||
return clusterMayAutoPause(accountId, region, clusterId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAutoPause(Event event, Instant at) {
|
||||
List<DbInstance> members = serverlessMembers(accountId, region, clusterId);
|
||||
recordAutoPauseEvents(accountId, members, event, at);
|
||||
if (event == Event.PAUSED || event == Event.STILL_PAUSED) {
|
||||
publishPausedCapacity(accountId, region, clusterId, members, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether RDS holds a cluster or instance under this identifier.
|
||||
*
|
||||
@@ -3700,6 +3884,9 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
cluster.setServerlessV2SecondsUntilAutoPause(effectiveAutoPauseSeconds);
|
||||
}
|
||||
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
|
||||
if (modifiesServerlessV2Scaling) {
|
||||
applyAutoPause(cluster);
|
||||
}
|
||||
|
||||
// A cluster rotation applies to every endpoint: the cluster's own proxy and each member
|
||||
// instance's proxy hold start-time password snapshots, and member endpoints validate
|
||||
@@ -6838,6 +7025,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
cluster.setStatus(DbInstanceStatus.AVAILABLE);
|
||||
putClusterForScope(accountId, clusterRegion,
|
||||
cluster.getDbClusterIdentifier(), cluster);
|
||||
applyAutoPause(cluster);
|
||||
} catch (Exception e) {
|
||||
if (!config.services().rds().mock()) {
|
||||
try {
|
||||
|
||||
+493
@@ -0,0 +1,493 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.LongConsumer;
|
||||
|
||||
/**
|
||||
* Aurora Serverless v2 auto-pause for one RDS backend container.
|
||||
*
|
||||
* <p>Every client of the container, a proxied connection, a Data API call or a command Floci runs
|
||||
* inside it, holds a {@link RdsBackendGate.Lease} while it uses the container. Once no lease has
|
||||
* been held for {@code SecondsUntilAutoPause}, the container is frozen with {@code docker pause},
|
||||
* which keeps its data and its published port. The next lease request thaws it and waits until
|
||||
* it runs again.
|
||||
*
|
||||
* <p>The state moves from RUNNING to PAUSING, PAUSED and RESUMING, and back to RUNNING. Every
|
||||
* transition happens under {@link #lock}; the Docker calls and the listener run without it, so a
|
||||
* slow daemon or a listener waiting for the RDS service never holds up a thread that needs the
|
||||
* lock. A lease request that finds the container PAUSING cancels the pause, and one that finds it
|
||||
* RESUMING waits for the resume, so no client reaches a frozen container and none is turned away.
|
||||
*/
|
||||
final class AutoPauseController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AutoPauseController.class);
|
||||
|
||||
/** How often a paused container reports zero capacity, as a paused Aurora instance does. */
|
||||
private static final Duration PAUSED_REPORT_INTERVAL = Duration.ofMinutes(1);
|
||||
|
||||
enum State {
|
||||
RUNNING,
|
||||
PAUSING,
|
||||
PAUSED,
|
||||
RESUMING
|
||||
}
|
||||
|
||||
/** Runs a task after a delay; cancelling the returned future stops a task that has not started. */
|
||||
@FunctionalInterface
|
||||
interface Scheduler {
|
||||
Future<?> schedule(Runnable task, Duration delay);
|
||||
}
|
||||
|
||||
/** The Docker freezer. Both calls succeed when the container is already in the requested state. */
|
||||
interface Freezer {
|
||||
void pause(String containerId);
|
||||
|
||||
void unpause(String containerId);
|
||||
}
|
||||
|
||||
private final String containerId;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private final Freezer freezer;
|
||||
private final Scheduler scheduler;
|
||||
private final Executor notifier;
|
||||
private final Clock clock;
|
||||
private final Duration resumeDelay;
|
||||
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
private final Condition settled = lock.newCondition();
|
||||
|
||||
// Everything below is guarded by lock.
|
||||
private final List<Signal> pendingSignals = new ArrayList<>();
|
||||
private State state = State.RUNNING;
|
||||
private int leases;
|
||||
private Integer secondsUntilAutoPause;
|
||||
private AutoPauseListener listener = AutoPauseListener.NONE;
|
||||
// The one timer of the current state: the idle timer while RUNNING, the zero-capacity report
|
||||
// while PAUSED, the resume delay while RESUMING. A task whose token is not the current one
|
||||
// was cancelled or belongs to an earlier state, and does nothing.
|
||||
private Future<?> timer;
|
||||
private long timerToken;
|
||||
private boolean pauseCanceled;
|
||||
private boolean closed;
|
||||
private Instant lastSignal = Instant.EPOCH;
|
||||
|
||||
AutoPauseController(String containerId, String host, int port, Freezer freezer,
|
||||
Scheduler scheduler, Executor notifier, Clock clock, Duration resumeDelay) {
|
||||
this.containerId = containerId;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.freezer = freezer;
|
||||
this.scheduler = scheduler;
|
||||
this.notifier = notifier;
|
||||
this.clock = clock;
|
||||
this.resumeDelay = resumeDelay;
|
||||
}
|
||||
|
||||
boolean serves(String backendHost, int backendPort) {
|
||||
return port == backendPort && Objects.equals(host, backendHost);
|
||||
}
|
||||
|
||||
boolean runs(String candidateContainerId) {
|
||||
return containerId.equals(candidateContainerId);
|
||||
}
|
||||
|
||||
State state() {
|
||||
lock.lock();
|
||||
try {
|
||||
return state;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
int leaseCount() {
|
||||
lock.lock();
|
||||
try {
|
||||
return leases;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the idle interval after which the container pauses; null keeps it running. The idle
|
||||
* clock restarts when the interval changes, and a container paused or pausing under the old
|
||||
* interval is resumed, as Aurora resumes an instance whose scaling range changes.
|
||||
*/
|
||||
void configure(Integer seconds, AutoPauseListener newListener) {
|
||||
lock.lock();
|
||||
try {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
listener = newListener != null ? newListener : AutoPauseListener.NONE;
|
||||
if (Objects.equals(secondsUntilAutoPause, seconds)) {
|
||||
return;
|
||||
}
|
||||
secondsUntilAutoPause = seconds;
|
||||
switch (state) {
|
||||
case RUNNING -> {
|
||||
cancelTimer();
|
||||
armIdleTimer();
|
||||
}
|
||||
case PAUSING -> pauseCanceled = true;
|
||||
case PAUSED -> startTimer(this::resumeInBackground, Duration.ZERO);
|
||||
case RESUMING -> {
|
||||
// Finishing the resume arms the idle timer with the new interval.
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a lease that keeps the container awake, resuming it first when it is paused. Waits
|
||||
* while a pause or a resume is under way; a pause still in progress is cancelled.
|
||||
*
|
||||
* @throws InterruptedException when interrupted while waiting
|
||||
* @throws IllegalStateException when Docker cannot resume the container, which stays paused
|
||||
*/
|
||||
RdsBackendGate.Lease acquire() throws InterruptedException {
|
||||
lock.lock();
|
||||
try {
|
||||
while (true) {
|
||||
if (closed && state != State.PAUSING && state != State.RESUMING) {
|
||||
return RdsBackendGate.Lease.NONE;
|
||||
}
|
||||
if (state == State.RUNNING) {
|
||||
leases++;
|
||||
cancelTimer();
|
||||
return new ControllerLease();
|
||||
}
|
||||
if (state == State.PAUSED) {
|
||||
resume();
|
||||
} else {
|
||||
if (state == State.PAUSING) {
|
||||
pauseCanceled = true;
|
||||
}
|
||||
settled.await();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops auto-pausing for good, thawing the container when it is paused. A pause or a resume
|
||||
* in progress is not waited for: the thread running it thaws the container once it sees the
|
||||
* controller closed.
|
||||
*/
|
||||
void close() {
|
||||
lock.lock();
|
||||
try {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
// A resume whose timer is set has already thawed the container and only waits out
|
||||
// the resume delay; cancelling that timer must not leave its waiters behind.
|
||||
boolean resumeDelayPending = state == State.RESUMING && timer != null;
|
||||
cancelTimer();
|
||||
if (resumeDelayPending) {
|
||||
finishResume();
|
||||
} else if (state == State.PAUSED) {
|
||||
state = State.RESUMING;
|
||||
RuntimeException failure = withoutLock(() -> freezer.unpause(containerId));
|
||||
if (failure != null) {
|
||||
LOG.warnv(failure, "Could not resume auto-paused RDS container {0} before releasing it",
|
||||
containerId);
|
||||
state = State.PAUSED;
|
||||
} else {
|
||||
state = State.RUNNING;
|
||||
}
|
||||
}
|
||||
settled.signalAll();
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the idle check now rather than when the idle timer fires, for a caller that cannot wait
|
||||
* SecondsUntilAutoPause. Returns whether the container paused.
|
||||
*/
|
||||
boolean pauseIfIdle() {
|
||||
long token;
|
||||
lock.lock();
|
||||
try {
|
||||
if (!idleTimerArmed(timerToken)) {
|
||||
return false;
|
||||
}
|
||||
token = timerToken;
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
idleTimerFired(token);
|
||||
return state() == State.PAUSED;
|
||||
}
|
||||
|
||||
private void release() {
|
||||
lock.lock();
|
||||
try {
|
||||
if (leases > 0) {
|
||||
leases--;
|
||||
}
|
||||
armIdleTimer();
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void idleTimerFired(long token) {
|
||||
AutoPauseListener current;
|
||||
lock.lock();
|
||||
try {
|
||||
if (!idleTimerArmed(token)) {
|
||||
return;
|
||||
}
|
||||
current = listener;
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
// Asked without the lock: the answer comes from the RDS service, which may be busy.
|
||||
boolean allowed = mayPause(current);
|
||||
lock.lock();
|
||||
try {
|
||||
if (!idleTimerArmed(token)) {
|
||||
return;
|
||||
}
|
||||
if (!allowed) {
|
||||
armIdleTimer();
|
||||
return;
|
||||
}
|
||||
cancelTimer();
|
||||
state = State.PAUSING;
|
||||
pauseCanceled = false;
|
||||
signal(AutoPauseListener.Event.PAUSE_INITIATED);
|
||||
pause();
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean idleTimerArmed(long token) {
|
||||
return !closed && state == State.RUNNING && leases == 0 && secondsUntilAutoPause != null
|
||||
&& timer != null && token == timerToken;
|
||||
}
|
||||
|
||||
/** Freezes the container. Entered and left holding the lock, in PAUSING. */
|
||||
private void pause() {
|
||||
RuntimeException pauseFailure = withoutLock(() -> freezer.pause(containerId));
|
||||
if (pauseFailure == null && !pauseCanceled && !closed) {
|
||||
state = State.PAUSED;
|
||||
signal(AutoPauseListener.Event.PAUSED);
|
||||
armPausedReport();
|
||||
settled.signalAll();
|
||||
LOG.infov("Auto-paused idle RDS container {0} (SecondsUntilAutoPause {1})",
|
||||
containerId, String.valueOf(secondsUntilAutoPause));
|
||||
return;
|
||||
}
|
||||
if (pauseFailure != null) {
|
||||
LOG.warnv(pauseFailure, "Could not auto-pause RDS container {0}; it keeps running", containerId);
|
||||
} else {
|
||||
// A client arrived, the interval changed or the container is being released while it
|
||||
// was freezing: thaw it again rather than let anyone reach it frozen.
|
||||
RuntimeException thawFailure = withoutLock(() -> freezer.unpause(containerId));
|
||||
if (thawFailure != null) {
|
||||
LOG.warnv(thawFailure, "Could not undo the auto-pause of RDS container {0}", containerId);
|
||||
state = State.PAUSED;
|
||||
armPausedReport();
|
||||
settled.signalAll();
|
||||
return;
|
||||
}
|
||||
}
|
||||
state = State.RUNNING;
|
||||
signal(AutoPauseListener.Event.PAUSE_CANCELED);
|
||||
settled.signalAll();
|
||||
armIdleTimer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Thaws the container. Entered and left holding the lock, in PAUSED. Waiters see RESUMING
|
||||
* until the resume delay has passed.
|
||||
*/
|
||||
private void resume() {
|
||||
cancelTimer();
|
||||
state = State.RESUMING;
|
||||
signal(AutoPauseListener.Event.RESUME_INITIATED);
|
||||
RuntimeException failure = withoutLock(() -> freezer.unpause(containerId));
|
||||
if (failure != null) {
|
||||
state = State.PAUSED;
|
||||
armPausedReport();
|
||||
settled.signalAll();
|
||||
throw new IllegalStateException(
|
||||
"Could not resume auto-paused RDS container " + containerId, failure);
|
||||
}
|
||||
if (closed || resumeDelay.isZero()) {
|
||||
finishResume();
|
||||
} else {
|
||||
startTimer(this::resumeDelayElapsed, resumeDelay);
|
||||
}
|
||||
}
|
||||
|
||||
private void resumeDelayElapsed(long token) {
|
||||
lock.lock();
|
||||
try {
|
||||
if (state == State.RESUMING && token == timerToken) {
|
||||
finishResume();
|
||||
}
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void finishResume() {
|
||||
cancelTimer();
|
||||
state = State.RUNNING;
|
||||
signal(AutoPauseListener.Event.RESUMED);
|
||||
settled.signalAll();
|
||||
armIdleTimer();
|
||||
LOG.infov("Resumed auto-paused RDS container {0}", containerId);
|
||||
}
|
||||
|
||||
private void resumeInBackground(long token) {
|
||||
lock.lock();
|
||||
try {
|
||||
if (!closed && state == State.PAUSED && token == timerToken) {
|
||||
resume();
|
||||
}
|
||||
} catch (IllegalStateException e) {
|
||||
LOG.warnv(e, "Could not resume auto-paused RDS container {0}", containerId);
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void armIdleTimer() {
|
||||
if (closed || state != State.RUNNING || leases > 0 || secondsUntilAutoPause == null) {
|
||||
return;
|
||||
}
|
||||
startTimer(this::idleTimerFired, Duration.ofSeconds(secondsUntilAutoPause));
|
||||
}
|
||||
|
||||
private void armPausedReport() {
|
||||
if (!closed) {
|
||||
startTimer(this::pausedReportDue, PAUSED_REPORT_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
private void pausedReportDue(long token) {
|
||||
lock.lock();
|
||||
try {
|
||||
if (!closed && state == State.PAUSED && token == timerToken) {
|
||||
signal(AutoPauseListener.Event.STILL_PAUSED);
|
||||
armPausedReport();
|
||||
}
|
||||
} finally {
|
||||
unlockAndDispatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void startTimer(LongConsumer task, Duration delay) {
|
||||
cancelTimer();
|
||||
long token = timerToken;
|
||||
timer = scheduler.schedule(() -> task.accept(token), delay);
|
||||
}
|
||||
|
||||
private void cancelTimer() {
|
||||
if (timer != null) {
|
||||
timer.cancel(false);
|
||||
timer = null;
|
||||
}
|
||||
timerToken++;
|
||||
}
|
||||
|
||||
/** Runs a Docker call with the lock released, and returns its failure instead of throwing it. */
|
||||
private RuntimeException withoutLock(Runnable dockerCall) {
|
||||
if (lock.getHoldCount() != 1) {
|
||||
throw new IllegalStateException("Auto-pause lock must be held exactly once around a Docker call");
|
||||
}
|
||||
unlockAndDispatch();
|
||||
try {
|
||||
dockerCall.run();
|
||||
return null;
|
||||
} catch (RuntimeException e) {
|
||||
return e;
|
||||
} finally {
|
||||
lock.lock();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean mayPause(AutoPauseListener current) {
|
||||
try {
|
||||
return current.mayPause();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not tell whether RDS container {0} may auto-pause; it keeps running",
|
||||
containerId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Queues an event for the listener, stamped later than the previous one so they keep their order. */
|
||||
private void signal(AutoPauseListener.Event event) {
|
||||
Instant now = clock.instant();
|
||||
Instant at = now.isAfter(lastSignal) ? now : lastSignal.plusMillis(1);
|
||||
lastSignal = at;
|
||||
pendingSignals.add(new Signal(listener, event, at));
|
||||
}
|
||||
|
||||
/** Releases the lock, then hands the events queued under it to the notifier, in order. */
|
||||
private void unlockAndDispatch() {
|
||||
List<Signal> ready = pendingSignals.isEmpty() ? List.of() : List.copyOf(pendingSignals);
|
||||
pendingSignals.clear();
|
||||
lock.unlock();
|
||||
for (Signal signal : ready) {
|
||||
try {
|
||||
notifier.execute(() -> deliver(signal));
|
||||
} catch (RejectedExecutionException e) {
|
||||
LOG.debugv("Dropped RDS auto-pause event {0} for container {1}: {2}",
|
||||
signal.event(), containerId, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deliver(Signal signal) {
|
||||
try {
|
||||
signal.listener().onAutoPause(signal.event(), signal.at());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not report RDS auto-pause event {0} for container {1}",
|
||||
signal.event(), containerId);
|
||||
}
|
||||
}
|
||||
|
||||
private record Signal(AutoPauseListener listener, AutoPauseListener.Event event, Instant at) {
|
||||
}
|
||||
|
||||
private final class ControllerLease implements RdsBackendGate.Lease {
|
||||
|
||||
private final AtomicBoolean released = new AtomicBoolean();
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (released.compareAndSet(false, true)) {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* What the auto-pause of an RDS container asks of the cluster it belongs to, and what it reports
|
||||
* back. Both calls run on a background thread, never while the auto-pause holds its lock, so an
|
||||
* implementation may take the RDS service's lock.
|
||||
*/
|
||||
public interface AutoPauseListener {
|
||||
|
||||
AutoPauseListener NONE = new AutoPauseListener() {
|
||||
@Override
|
||||
public boolean mayPause() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAutoPause(Event event, Instant at) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The auto-pause steps Aurora reports as RDS-EVENT-0370 to 0374, plus {@code STILL_PAUSED},
|
||||
* repeated once a minute while the container stays paused.
|
||||
*/
|
||||
enum Event {
|
||||
PAUSE_INITIATED,
|
||||
PAUSE_CANCELED,
|
||||
PAUSED,
|
||||
STILL_PAUSED,
|
||||
RESUME_INITIATED,
|
||||
RESUMED
|
||||
}
|
||||
|
||||
/** Whether the cluster may pause now that it has been idle for SecondsUntilAutoPause. */
|
||||
boolean mayPause();
|
||||
|
||||
void onAutoPause(Event event, Instant at);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
/**
|
||||
* Lets a client into an RDS backend container. An Aurora Serverless v2 cluster that auto-paused is
|
||||
* resumed first, and it does not pause again while the client holds the returned lease.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface RdsBackendGate {
|
||||
|
||||
/** A gate for backends that never pause. */
|
||||
RdsBackendGate OPEN = (host, port) -> Lease.NONE;
|
||||
|
||||
/**
|
||||
* Waits until the container serving {@code host:port} can take a client, resuming it when it
|
||||
* is auto-paused, and keeps it awake until the lease is closed. A backend with no auto-pause
|
||||
* gets {@link Lease#NONE}.
|
||||
*
|
||||
* @throws InterruptedException when interrupted while a pause or resume is under way
|
||||
*/
|
||||
Lease enter(String host, int port) throws InterruptedException;
|
||||
|
||||
/** Held for as long as a client uses the backend; closing it more than once is harmless. */
|
||||
interface Lease extends AutoCloseable {
|
||||
|
||||
Lease NONE = () -> {
|
||||
};
|
||||
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
}
|
||||
+198
-6
@@ -1,10 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
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;
|
||||
@@ -15,6 +17,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.E
|
||||
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 jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
@@ -27,22 +30,32 @@ import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Manages backend Docker container lifecycle for RDS DB instances and clusters.
|
||||
* Starts postgres/mysql/mariadb containers and resolves the backend host:port for the auth proxy.
|
||||
* Every client of a container enters it through {@link #enter}, which is how an Aurora Serverless
|
||||
* v2 cluster with MinCapacity 0 knows when it is idle enough to pause and when to resume.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RdsContainerManager {
|
||||
public class RdsContainerManager implements RdsBackendGate, Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RdsContainerManager.class);
|
||||
private static final Pattern SAFE_STORAGE_COMPONENT = Pattern.compile("[A-Za-z0-9._-]+");
|
||||
@@ -59,6 +72,29 @@ public class RdsContainerManager {
|
||||
private final Set<String> claimedRuntimes = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> cleanupPending = ConcurrentHashMap.newKeySet();
|
||||
private volatile boolean dockerUnavailableLogged;
|
||||
// Auto-pause state of every running container, by runtime id. The timer thread only keeps
|
||||
// time: each task it fires runs on a virtual thread of its own, since a pause first asks the
|
||||
// RDS service whether the cluster may pause. Events reach the listener one at a time, in order.
|
||||
private final Map<String, AutoPauseController> autoPauses = new ConcurrentHashMap<>();
|
||||
private final ScheduledExecutorService autoPauseTimer = Executors.newSingleThreadScheduledExecutor(
|
||||
runnable -> {
|
||||
Thread thread = new Thread(runnable, "rds-auto-pause-timer");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
private final ExecutorService autoPauseEvents = Executors.newSingleThreadExecutor(
|
||||
Thread.ofVirtual().name("rds-auto-pause-events").factory());
|
||||
private final AutoPauseController.Freezer dockerFreezer = new AutoPauseController.Freezer() {
|
||||
@Override
|
||||
public void pause(String containerId) {
|
||||
pauseContainer(containerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unpause(String containerId) {
|
||||
unpauseContainer(containerId);
|
||||
}
|
||||
};
|
||||
|
||||
@Inject
|
||||
public RdsContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -281,6 +317,9 @@ public class RdsContainerManager {
|
||||
info.containerId(), logGroup, logStream, runtimeIdentity.region(),
|
||||
"rds:" + effectiveRuntimeId);
|
||||
handle.setLogStream(logHandle);
|
||||
// Before the handle is returned, so that the connections of every proxy started on it
|
||||
// are counted from the first one.
|
||||
registerAutoPause(effectiveRuntimeId, handle);
|
||||
activeContainers.put(effectiveRuntimeId, handle);
|
||||
|
||||
return handle;
|
||||
@@ -349,6 +388,7 @@ public class RdsContainerManager {
|
||||
}
|
||||
RdsContainerHandle active = activeContainers.get(handle.getRuntimeId());
|
||||
RdsContainerHandle effectiveHandle = active != null ? active : handle;
|
||||
releaseAutoPause(effectiveHandle.getRuntimeId());
|
||||
try {
|
||||
lifecycleManager.stopAndRemoveStrict(
|
||||
effectiveHandle.getContainerId(), effectiveHandle.getLogStream());
|
||||
@@ -411,6 +451,156 @@ public class RdsContainerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies an Aurora Serverless v2 auto-pause interval to a running container: it pauses once
|
||||
* no client has used it for that many seconds, and a null interval, for MinCapacity above 0
|
||||
* or with auto-pause turned off, keeps it running. The listener decides whether the cluster
|
||||
* may pause at that moment and is told each step.
|
||||
*/
|
||||
public void configureAutoPause(String runtimeId, Integer secondsUntilAutoPause,
|
||||
AutoPauseListener listener) {
|
||||
AutoPauseController controller = runtimeId != null ? autoPauses.get(runtimeId) : null;
|
||||
if (controller == null) {
|
||||
return;
|
||||
}
|
||||
boolean enabled = config.services().rds().auroraAutoPauseEnabled();
|
||||
controller.configure(enabled ? secondsUntilAutoPause : null, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Lease enter(String host, int port) throws InterruptedException {
|
||||
if (host == null) {
|
||||
return Lease.NONE;
|
||||
}
|
||||
for (AutoPauseController controller : autoPauses.values()) {
|
||||
if (controller.serves(host, port)) {
|
||||
return controller.acquire();
|
||||
}
|
||||
}
|
||||
return Lease.NONE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a runtime's auto-pause idle check now instead of after SecondsUntilAutoPause, which
|
||||
* the API does not let drop below 300 seconds. Returns whether the container paused.
|
||||
*/
|
||||
boolean pauseIfIdle(String runtimeId) {
|
||||
AutoPauseController controller = autoPauses.get(runtimeId);
|
||||
return controller != null && controller.pauseIfIdle();
|
||||
}
|
||||
|
||||
/**
|
||||
* A reset wipes the RDS records but leaves their containers running, as it always has. It
|
||||
* releases their auto-pause, which thaws a paused container, so none stays frozen with no
|
||||
* cluster left to resume it.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
for (String runtimeId : List.copyOf(autoPauses.keySet())) {
|
||||
releaseAutoPause(runtimeId);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdownAutoPause() {
|
||||
autoPauseTimer.shutdownNow();
|
||||
autoPauseEvents.shutdownNow();
|
||||
}
|
||||
|
||||
private void registerAutoPause(String runtimeId, RdsContainerHandle handle) {
|
||||
Duration resumeDelay = Duration.ofMillis(
|
||||
Math.max(0, config.services().rds().auroraResumeDelayMillis()));
|
||||
AutoPauseController controller = new AutoPauseController(
|
||||
handle.getContainerId(), handle.getHost(), handle.getPort(), dockerFreezer,
|
||||
this::scheduleAutoPauseTask, autoPauseEvents, Clock.systemUTC(), resumeDelay);
|
||||
// Clients find a container by its address, so the new container owns it from now on,
|
||||
// even if Docker removed the previous owner without Floci stopping it.
|
||||
for (Map.Entry<String, AutoPauseController> entry : List.copyOf(autoPauses.entrySet())) {
|
||||
if (entry.getValue().serves(handle.getHost(), handle.getPort())
|
||||
&& autoPauses.remove(entry.getKey(), entry.getValue())) {
|
||||
entry.getValue().close();
|
||||
}
|
||||
}
|
||||
AutoPauseController previous = autoPauses.put(runtimeId, controller);
|
||||
if (previous != null) {
|
||||
previous.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops a runtime's auto-pause before its container goes away, thawing it when paused. */
|
||||
private void releaseAutoPause(String runtimeId) {
|
||||
AutoPauseController controller = autoPauses.remove(runtimeId);
|
||||
if (controller != null) {
|
||||
controller.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps a container awake, resuming it first, while Floci runs a command inside it. */
|
||||
private Lease holdContainer(String containerId) {
|
||||
if (containerId == null) {
|
||||
return Lease.NONE;
|
||||
}
|
||||
for (AutoPauseController controller : autoPauses.values()) {
|
||||
if (controller.runs(containerId)) {
|
||||
try {
|
||||
return controller.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(
|
||||
"Interrupted while resuming RDS container " + containerId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Lease.NONE;
|
||||
}
|
||||
|
||||
private Future<?> scheduleAutoPauseTask(Runnable task, Duration delay) {
|
||||
try {
|
||||
return autoPauseTimer.schedule(
|
||||
() -> Thread.ofVirtual().name("rds-auto-pause").start(task),
|
||||
delay.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (RejectedExecutionException e) {
|
||||
LOG.debugv("RDS auto-pause timer is shut down; not scheduling: {0}", e.getMessage());
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
|
||||
private void pauseContainer(String containerId) {
|
||||
try {
|
||||
lifecycleManager.getDockerClient().pauseContainerCmd(containerId).exec();
|
||||
} catch (RuntimeException e) {
|
||||
// Docker refuses to pause a paused container; that one is where it should be.
|
||||
if (!isRunning(containerId, true)) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void unpauseContainer(String containerId) {
|
||||
try {
|
||||
lifecycleManager.getDockerClient().unpauseContainerCmd(containerId).exec();
|
||||
} catch (RuntimeException e) {
|
||||
// Docker refuses to unpause a container that is not paused, as after a manual
|
||||
// `docker unpause`; one still running is where it should be.
|
||||
if (!isRunning(containerId, false)) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the container runs, paused or not as asked; false when Docker cannot say. */
|
||||
private boolean isRunning(String containerId, boolean paused) {
|
||||
try {
|
||||
InspectContainerResponse.ContainerState state =
|
||||
lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getState();
|
||||
return state != null && Boolean.TRUE.equals(state.getRunning())
|
||||
&& paused == Boolean.TRUE.equals(state.getPaused());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv("Could not inspect RDS container {0}: {1}", containerId, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void addPersistenceMounts(
|
||||
ContainerBuilder.Builder specBuilder, String storageResourceId,
|
||||
String exactVolumeName, DatabaseEngine engine, String image) {
|
||||
@@ -555,9 +745,11 @@ public class RdsContainerManager {
|
||||
*/
|
||||
public void rotateMasterPassword(String containerName, String containerId, DatabaseEngine engine,
|
||||
String masterUsername, String oldPassword, String newPassword) {
|
||||
execUntilSuccess(containerName, containerId,
|
||||
passwordRotationCommand(engine, masterUsername, oldPassword, newPassword),
|
||||
"master-password rotation");
|
||||
try (Lease _ = holdContainer(containerId)) {
|
||||
execUntilSuccess(containerName, containerId,
|
||||
passwordRotationCommand(engine, masterUsername, oldPassword, newPassword),
|
||||
"master-password rotation");
|
||||
}
|
||||
}
|
||||
|
||||
static String[] passwordRotationCommand(DatabaseEngine engine, String masterUsername,
|
||||
@@ -679,7 +871,7 @@ public class RdsContainerManager {
|
||||
"pg_dumpall",
|
||||
"-U", effectiveUser
|
||||
};
|
||||
try {
|
||||
try (Lease _ = holdContainer(containerId)) {
|
||||
ContainerExecResult result = execInContainer(containerId, cmd, 120);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("pg_dumpall failed with exit code " + result.exitCode() + ": " + result.stderr());
|
||||
@@ -693,7 +885,7 @@ public class RdsContainerManager {
|
||||
public void restorePostgresSnapshot(String containerId, String masterUsername, String sqlDump) {
|
||||
String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres";
|
||||
|
||||
try {
|
||||
try (Lease _ = holdContainer(containerId)) {
|
||||
String restoreScript = postgresRestoreScript();
|
||||
|
||||
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -34,6 +35,7 @@ public class RdsAuthProxy {
|
||||
private final int handshakeTimeoutMillis;
|
||||
private final int backendConnectTimeoutMillis;
|
||||
private final Semaphore connectionPermits;
|
||||
private final RdsBackendGate backendGate;
|
||||
|
||||
private volatile boolean running;
|
||||
private ServerSocket serverSocket;
|
||||
@@ -47,7 +49,8 @@ public class RdsAuthProxy {
|
||||
int maxConnections) {
|
||||
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
|
||||
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
|
||||
backendConnectTimeoutMillis, maxConnections, null, username -> false);
|
||||
backendConnectTimeoutMillis, maxConnections, null, username -> false,
|
||||
RdsBackendGate.OPEN);
|
||||
}
|
||||
|
||||
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
|
||||
@@ -56,11 +59,11 @@ public class RdsAuthProxy {
|
||||
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
|
||||
MasterPasswordCheck passwordValidator,
|
||||
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
|
||||
int maxConnections, RdsProxyBinding binding) {
|
||||
int maxConnections, RdsProxyBinding binding, RdsBackendGate backendGate) {
|
||||
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
|
||||
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
|
||||
backendConnectTimeoutMillis, maxConnections, binding,
|
||||
username -> binding != null);
|
||||
username -> binding != null, backendGate);
|
||||
}
|
||||
|
||||
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
|
||||
@@ -70,7 +73,8 @@ public class RdsAuthProxy {
|
||||
MasterPasswordCheck passwordValidator,
|
||||
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
|
||||
int maxConnections, RdsProxyBinding binding,
|
||||
MySqlProtocolHandler.IamUserChecker iamUserChecker) {
|
||||
MySqlProtocolHandler.IamUserChecker iamUserChecker,
|
||||
RdsBackendGate backendGate) {
|
||||
this.instanceId = instanceId;
|
||||
this.backendHost = backendHost;
|
||||
this.backendPort = backendPort;
|
||||
@@ -87,6 +91,7 @@ public class RdsAuthProxy {
|
||||
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
|
||||
this.backendConnectTimeoutMillis = backendConnectTimeoutMillis;
|
||||
this.connectionPermits = new Semaphore(Math.max(1, maxConnections));
|
||||
this.backendGate = backendGate;
|
||||
}
|
||||
|
||||
public void start(int proxyPort) throws IOException {
|
||||
@@ -151,7 +156,11 @@ public class RdsAuthProxy {
|
||||
private void handleConnection(Socket client) {
|
||||
Socket backend = null;
|
||||
PostgresProtocolHandler.AuthenticatedSession session = null;
|
||||
RdsBackendGate.Lease lease = null;
|
||||
try {
|
||||
// An auto-paused Aurora backend resumes before the client is served: the client is
|
||||
// held, not refused, and the backend stays awake for as long as the connection lasts.
|
||||
lease = backendGate.enter(backendHost, backendPort);
|
||||
client.setTcpNoDelay(true);
|
||||
|
||||
// RDS only proxy-validates the master user; a non-master user passes through so the
|
||||
@@ -196,6 +205,9 @@ public class RdsAuthProxy {
|
||||
TcpStreamBridge.relay(client, backend);
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.debugv("RDS connection for instance {0} interrupted while its backend resumed", instanceId);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("RDS connection error for instance {0}: {1}", instanceId, e.getMessage());
|
||||
} finally {
|
||||
@@ -209,6 +221,9 @@ public class RdsAuthProxy {
|
||||
if (session != null) {
|
||||
closeQuietly(session.backend());
|
||||
}
|
||||
if (lease != null) {
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -20,14 +21,21 @@ public class RdsProxyManager {
|
||||
private final RdsSigV4Validator sigV4Validator;
|
||||
private final RdsProxyTlsCertificates tlsCertificates;
|
||||
private final EmulatorConfig config;
|
||||
private final RdsBackendGate backendGate;
|
||||
private final ConcurrentHashMap<String, RdsAuthProxy> proxies = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, RdsBackendGate backendGate) {
|
||||
this.sigV4Validator = sigV4Validator;
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
this.config = config;
|
||||
this.backendGate = backendGate;
|
||||
}
|
||||
|
||||
RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
|
||||
EmulatorConfig config) {
|
||||
this(sigV4Validator, tlsCertificates, config, RdsBackendGate.OPEN);
|
||||
}
|
||||
|
||||
public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
|
||||
@@ -42,7 +50,7 @@ public class RdsProxyManager {
|
||||
instanceId, backendHost, backendPort, engine, iamEnabled,
|
||||
masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator,
|
||||
rdsConfig.proxyHandshakeTimeoutMillis(), rdsConfig.proxyBackendConnectTimeoutMillis(),
|
||||
rdsConfig.proxyMaxConnections(), binding);
|
||||
rdsConfig.proxyMaxConnections(), binding, backendGate);
|
||||
try {
|
||||
proxy.start(proxyPort);
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
|
||||
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;
|
||||
@@ -53,15 +54,17 @@ public class RdsDataService implements Resettable {
|
||||
private final Duration transactionTtl;
|
||||
private final ConcurrentMap<String, TransactionContext> transactions = new ConcurrentHashMap<>();
|
||||
private final ScheduledExecutorService transactionCleanupExecutor;
|
||||
private final RdsBackendGate backendGate;
|
||||
|
||||
@Inject
|
||||
public RdsDataService(RdsDataResourceResolver resourceResolver,
|
||||
SecretsManagerService secretsManagerService,
|
||||
ObjectMapper objectMapper,
|
||||
RdsDataConnectionFactory connectionFactory,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config,
|
||||
RdsBackendGate backendGate) {
|
||||
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory,
|
||||
Duration.ofSeconds(config.services().rdsData().transactionTtlSeconds()));
|
||||
Duration.ofSeconds(config.services().rdsData().transactionTtlSeconds()), backendGate);
|
||||
}
|
||||
|
||||
RdsDataService(RdsDataResourceResolver resourceResolver,
|
||||
@@ -69,11 +72,22 @@ public class RdsDataService implements Resettable {
|
||||
ObjectMapper objectMapper,
|
||||
RdsDataConnectionFactory connectionFactory,
|
||||
Duration transactionTtl) {
|
||||
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory, transactionTtl,
|
||||
RdsBackendGate.OPEN);
|
||||
}
|
||||
|
||||
RdsDataService(RdsDataResourceResolver resourceResolver,
|
||||
SecretsManagerService secretsManagerService,
|
||||
ObjectMapper objectMapper,
|
||||
RdsDataConnectionFactory connectionFactory,
|
||||
Duration transactionTtl,
|
||||
RdsBackendGate backendGate) {
|
||||
this.resourceResolver = resourceResolver;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.connectionFactory = connectionFactory;
|
||||
this.transactionTtl = transactionTtl;
|
||||
this.backendGate = backendGate;
|
||||
this.transactionCleanupExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread thread = new Thread(r, "rds-data-transaction-cleanup");
|
||||
thread.setDaemon(true);
|
||||
@@ -95,7 +109,7 @@ public class RdsDataService implements Resettable {
|
||||
synchronized (tx) {
|
||||
if (transactions.remove(id, tx)) {
|
||||
rollbackQuietly(tx.connection);
|
||||
closeQuietly(tx.connection);
|
||||
tx.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -106,7 +120,7 @@ public class RdsDataService implements Resettable {
|
||||
synchronized (tx) {
|
||||
if (transactions.remove(id, tx)) {
|
||||
rollbackQuietly(tx.connection);
|
||||
closeQuietly(tx.connection);
|
||||
tx.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -149,13 +163,18 @@ public class RdsDataService implements Resettable {
|
||||
Credentials credentials = credentials(request, target, region);
|
||||
String database = databaseName(request, target);
|
||||
|
||||
// The transaction's connection keeps the cluster awake until it commits, rolls back or expires.
|
||||
RdsBackendGate.Lease lease = enterBackend(target);
|
||||
boolean leaseHandedOver = false;
|
||||
Connection connection = null;
|
||||
try {
|
||||
connection = connectionFactory.open(target, credentials.username(), credentials.password(), database);
|
||||
connection.setAutoCommit(false);
|
||||
String transactionId = UUID.randomUUID().toString();
|
||||
transactions.put(transactionId, new TransactionContext(
|
||||
transactionId, connection, target.engine(), target.arn(), database, region, transactionTtl));
|
||||
transactionId, connection, target.engine(), target.arn(), database, region, transactionTtl,
|
||||
lease));
|
||||
leaseHandedOver = true;
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("transactionId", transactionId);
|
||||
@@ -165,6 +184,10 @@ public class RdsDataService implements Resettable {
|
||||
closeQuietly(connection);
|
||||
}
|
||||
throw databaseError(e);
|
||||
} finally {
|
||||
if (!leaseHandedOver) {
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +207,7 @@ public class RdsDataService implements Resettable {
|
||||
} catch (SQLException e) {
|
||||
throw databaseError(e);
|
||||
} finally {
|
||||
closeQuietly(tx.connection);
|
||||
tx.close();
|
||||
}
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
@@ -208,7 +231,7 @@ public class RdsDataService implements Resettable {
|
||||
} catch (SQLException e) {
|
||||
throw databaseError(e);
|
||||
} finally {
|
||||
closeQuietly(tx.connection);
|
||||
tx.close();
|
||||
}
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
@@ -236,11 +259,28 @@ public class RdsDataService implements Resettable {
|
||||
resourceResolver.resolve(resourceArn, region);
|
||||
Credentials credentials = credentials(request, target, region);
|
||||
String database = databaseName(request, target);
|
||||
try (Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
|
||||
try (RdsBackendGate.Lease _ = enterBackend(target);
|
||||
Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
|
||||
return work.execute(connection, target.engine());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes an auto-paused Aurora cluster before the Data API uses its database, as Aurora
|
||||
* does, and keeps it from pausing again until the returned lease is closed.
|
||||
*/
|
||||
private RdsBackendGate.Lease enterBackend(RdsDataResourceResolver.DatabaseTarget target) {
|
||||
try {
|
||||
return backendGate.enter(target.host(), target.port());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AwsException("InternalServerErrorException",
|
||||
"Interrupted while the DB cluster was resuming.", 500);
|
||||
} catch (IllegalStateException e) {
|
||||
throw new AwsException("InternalServerErrorException", e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode executeOnConnection(Connection connection, DatabaseEngine engine, String sql,
|
||||
Map<String, JsonNode> parameters, boolean includeMetadata)
|
||||
throws SQLException {
|
||||
@@ -583,7 +623,7 @@ public class RdsDataService implements Resettable {
|
||||
synchronized (tx) {
|
||||
if (tx.expiresAt.isBefore(now) && transactions.remove(id, tx)) {
|
||||
rollbackQuietly(tx.connection);
|
||||
closeQuietly(tx.connection);
|
||||
tx.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -737,23 +777,33 @@ public class RdsDataService implements Resettable {
|
||||
private final String resourceArn;
|
||||
private final String database;
|
||||
private final String region;
|
||||
private final RdsBackendGate.Lease lease;
|
||||
private volatile Instant expiresAt;
|
||||
|
||||
private TransactionContext(
|
||||
String id, Connection connection, DatabaseEngine engine, String resourceArn,
|
||||
String database, String region, Duration ttl) {
|
||||
String database, String region, Duration ttl, RdsBackendGate.Lease lease) {
|
||||
this.id = id;
|
||||
this.connection = connection;
|
||||
this.engine = engine;
|
||||
this.resourceArn = resourceArn;
|
||||
this.database = database;
|
||||
this.region = region;
|
||||
this.lease = lease;
|
||||
refresh(ttl);
|
||||
}
|
||||
|
||||
private void refresh(Duration ttl) {
|
||||
this.expiresAt = Instant.now().plus(ttl);
|
||||
}
|
||||
|
||||
private void close() {
|
||||
try {
|
||||
closeQuietly(connection);
|
||||
} finally {
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record Credentials(String username, String password) {
|
||||
|
||||
Reference in new issue
Block a user