mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
refactor(dsql): put the cluster database behind a backend strategy (#8595)
This commit is contained in:
1 parent
a5064a2f5a
commit
faf2287433
13 files changed
+394
-146
No files matched your search
@@ -0,0 +1,16 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
/** The passwords the database expects of the roles Floci connects as. */
|
||||
public interface BackendCredentials {
|
||||
|
||||
/** A database that trusts its connections wants no password. */
|
||||
BackendCredentials TRUST = new BackendCredentials() {
|
||||
@Override
|
||||
public String passwordFor(String backendRole) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** The password Floci logs in with as a backend role, or null when the database wants none. */
|
||||
String passwordFor(String backendRole);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.services.dsql.model.DsqlCluster;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The PostgreSQL 16 container behind each cluster, set up as DSQL's database is. The data is
|
||||
* kept as RDS keeps an instance's (a Docker volume of its own, or a directory under the host
|
||||
* persistent path), so a cluster survives a restart of Floci when its storage does, and is removed
|
||||
* with the cluster under the same policy. The database trusts its connections, as ElastiCache's
|
||||
* backends do behind their proxy: its port is published on the loopback address only, or, when
|
||||
* Floci runs in Docker, reached on Floci's Docker network without being published. Clients reach
|
||||
* it through Floci's endpoint, which authenticates every one with its IAM token.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DockerDsqlBackend implements DsqlBackend {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DockerDsqlBackend.class);
|
||||
private static final int PORT = 5432;
|
||||
private static final String DATABASE = "postgres";
|
||||
private static final String SUPERUSER = "dbowner";
|
||||
private static final Duration READY_TIMEOUT = Duration.ofSeconds(90);
|
||||
private static final String DATA_PATH = "/var/lib/postgresql/data";
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public DockerDsqlBackend(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
ContainerDetector containerDetector, EmulatorConfig config) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/** Starts the cluster's database, waits until it answers, and sets it up as DSQL's database is. */
|
||||
@Override
|
||||
public DsqlDatabases.Backend start(DsqlCluster cluster) throws SQLException, IOException {
|
||||
String name = containerName(cluster);
|
||||
Map<String, String> labels = ContainerStorageHelper.resourceIdentityLabels(
|
||||
"dsql", cluster.getIdentifier(), cluster.getAccountId(), cluster.getRegion());
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
ContainerBuilder.Builder spec = containerBuilder.newContainer(config.services().dsql().image())
|
||||
.withName(name)
|
||||
.withEnv(List.of("POSTGRES_USER=" + SUPERUSER, "POSTGRES_DB=" + DATABASE, "POSTGRES_HOST_AUTH_METHOD=trust"))
|
||||
.withDockerNetwork(config.services().dsql().dockerNetwork())
|
||||
.withLogRotation()
|
||||
.withLabels(labels);
|
||||
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
lifecycleManager.ensureVolume(name, labels);
|
||||
spec.withNamedVolume(name, DATA_PATH);
|
||||
} else {
|
||||
String hostPath = ContainerStorageHelper.hostResourcePath(config, "dsql", cluster.getIdentifier()).toString();
|
||||
ContainerStorageHelper.ensureHostDir(containerDetector, hostPath);
|
||||
spec.withBind(hostPath, DATA_PATH);
|
||||
}
|
||||
if (containerDetector.isRunningInContainer()) {
|
||||
spec.withExposedPort(PORT);
|
||||
} else {
|
||||
spec.withLoopbackPortBinding(PORT, 0);
|
||||
}
|
||||
ContainerSpec built = spec.build();
|
||||
String containerId = lifecycleManager.create(built);
|
||||
try {
|
||||
ContainerLifecycleManager.EndpointInfo endpoint =
|
||||
lifecycleManager.startCreated(containerId, built).getEndpoint(PORT);
|
||||
DsqlDatabases.Backend backend = new DsqlDatabases.Backend(endpoint.host(), endpoint.port(), DATABASE,
|
||||
SUPERUSER, null, RoleNames.IDENTITY, BackendCredentials.TRUST);
|
||||
awaitReady(backend);
|
||||
bootstrap(backend);
|
||||
LOG.infov("DSQL cluster {0} serves from {1}:{2}", cluster.getIdentifier(), backend.host(),
|
||||
String.valueOf(backend.port()));
|
||||
return backend;
|
||||
} catch (SQLException | RuntimeException e) {
|
||||
// A database that never served does not keep running: its cluster is FAILED, and deleting
|
||||
// the cluster removes its data.
|
||||
try {
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
} catch (RuntimeException removal) {
|
||||
e.addSuppressed(removal);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the cluster's database and, with {@code dropData}, removes its volume as Floci removes
|
||||
* a deleted resource's: always with in-memory storage, otherwise when
|
||||
* {@code prune-volumes-on-delete} is on. A host directory is left in place, as RDS leaves it.
|
||||
* Throws when Docker cannot remove either, so a deletion is not taken for done.
|
||||
*/
|
||||
@Override
|
||||
public void stop(DsqlCluster cluster, boolean dropData) {
|
||||
String name = containerName(cluster);
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
if (dropData && ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
ContainerStorageHelper.removeNamedVolumeStrict(config, lifecycleManager, name);
|
||||
}
|
||||
}
|
||||
|
||||
private String containerName(DsqlCluster cluster) {
|
||||
return ContainerStorageHelper.dockerName(config, "dsql-" + cluster.getIdentifier());
|
||||
}
|
||||
|
||||
private static void awaitReady(DsqlDatabases.Backend backend) throws SQLException {
|
||||
Instant deadline = Instant.now().plus(READY_TIMEOUT);
|
||||
SQLException last = null;
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
try (Connection connection = DsqlDatabases.superuser(backend); Statement statement = connection.createStatement()) {
|
||||
statement.execute("SELECT 1");
|
||||
return;
|
||||
} catch (SQLException e) {
|
||||
last = e;
|
||||
try {
|
||||
Thread.sleep(250);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new SQLException("Interrupted while the database started", interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new SQLException("The database did not start within " + READY_TIMEOUT.toSeconds() + " s", last);
|
||||
}
|
||||
|
||||
private static void bootstrap(DsqlDatabases.Backend backend) throws SQLException {
|
||||
String script = DsqlBootstrap.render(DATABASE, SUPERUSER, DsqlEndpoint.ADMIN);
|
||||
try (Connection connection = DsqlDatabases.superuser(backend); Statement statement = connection.createStatement()) {
|
||||
statement.execute(script);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
import io.floci.aws.services.dsql.model.DsqlCluster;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/** Where a cluster's database lives, and how it is brought up and taken down. */
|
||||
public interface DsqlBackend {
|
||||
|
||||
/** Starts the cluster's database, waits until it answers, and sets it up as DSQL's database is. */
|
||||
DsqlDatabases.Backend start(DsqlCluster cluster) throws SQLException, IOException;
|
||||
|
||||
/** Stops the cluster's database and, with {@code dropData}, removes its data. */
|
||||
void stop(DsqlCluster cluster, boolean dropData);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Renders the DSQL bootstrap script for the database, owner role and admin role of one cluster.
|
||||
* The script's placeholders: {@code {{database}}}, {@code {{owner}}} and {@code {{admin}}} as
|
||||
* identifiers, always quoted; {@code {{owner_literal}}} and {@code {{admin_literal}}}
|
||||
* as SQL string literals.
|
||||
*/
|
||||
final class DsqlBootstrap {
|
||||
|
||||
private static final String RESOURCE = "/dsql/bootstrap.sql";
|
||||
|
||||
private DsqlBootstrap() {
|
||||
}
|
||||
|
||||
/** The script for one cluster's database. */
|
||||
static String render(String database, String owner, String admin) {
|
||||
return template()
|
||||
.replace("{{database}}", identifier(database))
|
||||
.replace("{{owner_literal}}", literal(owner))
|
||||
.replace("{{owner}}", identifier(owner))
|
||||
.replace("{{admin_literal}}", literal(admin))
|
||||
.replace("{{admin}}", identifier(admin));
|
||||
}
|
||||
|
||||
private static String template() {
|
||||
try (InputStream in = DsqlBootstrap.class.getResourceAsStream(RESOURCE)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("dsql/bootstrap.sql is missing from the classpath");
|
||||
}
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Always quoted, so no name needs checking against PostgreSQL's reserved words. */
|
||||
private static String identifier(String name) {
|
||||
return '"' + name.replace("\"", "\"\"") + '"';
|
||||
}
|
||||
|
||||
private static String literal(String value) {
|
||||
return "'" + value.replace("'", "''") + "'";
|
||||
}
|
||||
}
|
||||
@@ -1,167 +1,61 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.services.dsql.model.DsqlCluster;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The PostgreSQL 16 container behind each cluster, set up as DSQL's database is. The data is
|
||||
* kept as RDS keeps an instance's (a Docker volume of its own, or a directory under the host
|
||||
* persistent path), so a cluster survives a restart of Floci when its storage does, and is removed
|
||||
* with the cluster under the same policy. The database trusts its connections, as ElastiCache's
|
||||
* backends do behind their proxy: its port is published on the loopback address only, or, when
|
||||
* Floci runs in Docker, reached on Floci's Docker network without being published. Clients reach
|
||||
* it through Floci's endpoint, which authenticates every one with its IAM token.
|
||||
* The database behind each cluster. Which one it is, a PostgreSQL container per cluster or a
|
||||
* server that already runs, is the configured backend's concern; this class hands every call to it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DsqlDatabases {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DsqlDatabases.class);
|
||||
private static final int PORT = 5432;
|
||||
private static final Duration READY_TIMEOUT = Duration.ofSeconds(90);
|
||||
private static final String DATA_PATH = "/var/lib/postgresql/data";
|
||||
private final DsqlBackend strategy;
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
/** Where a cluster's database answers. */
|
||||
public record Backend(String host, int port) {
|
||||
/**
|
||||
* Where a cluster's database answers, who Floci connects as, and how role names map.
|
||||
*
|
||||
* @param superuserPassword null when the database trusts the connection
|
||||
*/
|
||||
public record Backend(String host, int port, String database, String superuser, String superuserPassword,
|
||||
RoleNames roleNames, BackendCredentials credentials) {
|
||||
public String jdbcUrl() {
|
||||
return "jdbc:postgresql://" + host + ":" + port + "/postgres";
|
||||
return "jdbc:postgresql://" + host + ":" + port + "/" + database;
|
||||
}
|
||||
|
||||
/** Never shows the password, which a logged route would otherwise carry. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Backend[host=" + host + ", port=" + port + ", database=" + database + ", superuser=" + superuser
|
||||
+ ", superuserPassword=" + (superuserPassword == null ? "null" : "***") + ", roleNames="
|
||||
+ roleNames + ", credentials=" + credentials + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
public DsqlDatabases(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
ContainerDetector containerDetector, EmulatorConfig config) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
public DsqlDatabases(DockerDsqlBackend docker) {
|
||||
this.strategy = docker;
|
||||
}
|
||||
|
||||
/** Starts the cluster's database, waits until it answers, and sets it up as DSQL's database is. */
|
||||
public Backend start(DsqlCluster cluster) throws SQLException, IOException {
|
||||
String name = containerName(cluster);
|
||||
Map<String, String> labels = ContainerStorageHelper.resourceIdentityLabels(
|
||||
"dsql", cluster.getIdentifier(), cluster.getAccountId(), cluster.getRegion());
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
ContainerBuilder.Builder spec = containerBuilder.newContainer(config.services().dsql().image())
|
||||
.withName(name)
|
||||
.withEnv(List.of("POSTGRES_USER=dbowner", "POSTGRES_DB=postgres", "POSTGRES_HOST_AUTH_METHOD=trust"))
|
||||
.withDockerNetwork(config.services().dsql().dockerNetwork())
|
||||
.withLogRotation()
|
||||
.withLabels(labels);
|
||||
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
lifecycleManager.ensureVolume(name, labels);
|
||||
spec.withNamedVolume(name, DATA_PATH);
|
||||
} else {
|
||||
String hostPath = ContainerStorageHelper.hostResourcePath(config, "dsql", cluster.getIdentifier()).toString();
|
||||
ContainerStorageHelper.ensureHostDir(containerDetector, hostPath);
|
||||
spec.withBind(hostPath, DATA_PATH);
|
||||
}
|
||||
if (containerDetector.isRunningInContainer()) {
|
||||
spec.withExposedPort(PORT);
|
||||
} else {
|
||||
spec.withLoopbackPortBinding(PORT, 0);
|
||||
}
|
||||
ContainerSpec built = spec.build();
|
||||
String containerId = lifecycleManager.create(built);
|
||||
try {
|
||||
ContainerLifecycleManager.EndpointInfo endpoint =
|
||||
lifecycleManager.startCreated(containerId, built).getEndpoint(PORT);
|
||||
Backend backend = new Backend(endpoint.host(), endpoint.port());
|
||||
awaitReady(backend);
|
||||
bootstrap(backend);
|
||||
LOG.infov("DSQL cluster {0} serves from {1}:{2}", cluster.getIdentifier(), backend.host(),
|
||||
String.valueOf(backend.port()));
|
||||
return backend;
|
||||
} catch (SQLException | IOException | RuntimeException e) {
|
||||
// A database that never served does not keep running: its cluster is FAILED, and deleting
|
||||
// the cluster removes its data.
|
||||
try {
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
} catch (RuntimeException removal) {
|
||||
e.addSuppressed(removal);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return strategy.start(cluster);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the cluster's database and, with {@code dropData}, removes its volume as Floci removes
|
||||
* a deleted resource's: always with in-memory storage, otherwise when
|
||||
* {@code prune-volumes-on-delete} is on. A host directory is left in place, as RDS leaves it.
|
||||
* Throws when Docker cannot remove either, so a deletion is not taken for done.
|
||||
*/
|
||||
/** Stops the cluster's database and, with {@code dropData}, removes its data. */
|
||||
public void stop(DsqlCluster cluster, boolean dropData) {
|
||||
String name = containerName(cluster);
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
if (dropData && ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
ContainerStorageHelper.removeNamedVolumeStrict(config, lifecycleManager, name);
|
||||
}
|
||||
strategy.stop(cluster, dropData);
|
||||
}
|
||||
|
||||
/** A superuser connection to the cluster's database, for what the endpoint checks itself. */
|
||||
public static Connection superuser(Backend backend) throws SQLException {
|
||||
return DriverManager.getConnection(backend.jdbcUrl(), "dbowner", "");
|
||||
}
|
||||
|
||||
private String containerName(DsqlCluster cluster) {
|
||||
return ContainerStorageHelper.dockerName(config, "dsql-" + cluster.getIdentifier());
|
||||
}
|
||||
|
||||
private static void awaitReady(Backend backend) throws SQLException {
|
||||
Instant deadline = Instant.now().plus(READY_TIMEOUT);
|
||||
SQLException last = null;
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
try (Connection connection = superuser(backend); Statement statement = connection.createStatement()) {
|
||||
statement.execute("SELECT 1");
|
||||
return;
|
||||
} catch (SQLException e) {
|
||||
last = e;
|
||||
try {
|
||||
Thread.sleep(250);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new SQLException("Interrupted while the database started", interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new SQLException("The database did not start within " + READY_TIMEOUT.toSeconds() + " s", last);
|
||||
}
|
||||
|
||||
private static void bootstrap(Backend backend) throws SQLException, IOException {
|
||||
String script;
|
||||
try (InputStream in = DsqlDatabases.class.getResourceAsStream("/dsql/bootstrap.sql")) {
|
||||
if (in == null) {
|
||||
throw new IOException("dsql/bootstrap.sql is missing from the classpath");
|
||||
}
|
||||
script = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
try (Connection connection = superuser(backend); Statement statement = connection.createStatement()) {
|
||||
statement.execute(script);
|
||||
}
|
||||
String password = backend.superuserPassword() == null ? "" : backend.superuserPassword();
|
||||
return DriverManager.getConnection(backend.jdbcUrl(), backend.superuser(), password);
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ public class DsqlEndpoint {
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
static final Duration EXPIRY_GRACE = Duration.ofSeconds(5);
|
||||
private static final int HANDSHAKE_TIMEOUT_MILLIS = 30_000;
|
||||
private static final String ADMIN = "admin";
|
||||
static final String ADMIN = "admin";
|
||||
|
||||
private final DsqlTlsCertificates certificates;
|
||||
private final IamService iamService;
|
||||
|
||||
@@ -237,7 +237,7 @@ final class DsqlSession {
|
||||
if (!optionSettings.isEmpty()) {
|
||||
backendStartup.put("options", backendOptions(optionSettings));
|
||||
}
|
||||
backendStartup.put("database", "postgres");
|
||||
backendStartup.put("database", target.database());
|
||||
principalArn = admission.principalArn();
|
||||
backendOut.write(PostgresWire.startupMessage(backendStartup));
|
||||
backendOut.flush();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
/** Maps the role names clients see to the ones the cluster's database has, and back. */
|
||||
public interface RoleNames {
|
||||
|
||||
/** Names are the same on both sides, as with a database of the cluster's own. */
|
||||
RoleNames IDENTITY = new RoleNames() {
|
||||
@Override
|
||||
public String toBackend(String logical) {
|
||||
return logical;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toLogical(String backend) {
|
||||
return backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIdentity() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
/** The backend name of the role called {@code logical}: a role's exact name, never a specifier. */
|
||||
String toBackend(String logical);
|
||||
|
||||
String toLogical(String backend);
|
||||
|
||||
boolean isIdentity();
|
||||
}
|
||||
Reference in new issue
Block a user