feat(rds): serve a DB cluster's instances in its VPC and resolve its endpoint names to them (#9590)

With floci.services.rds.endpoints-in-vpc on, each instance of an Aurora DB
cluster gets its own address in its VPC, as a standalone instance does, and
serves the cluster's port, which the API reference says "is managed by the
cluster". The cluster reports the names the Aurora user guide gives its
endpoints, <cluster>.cluster-<identifier>, <cluster>.cluster-ro-<identifier>
and <endpoint>.cluster-custom-<identifier>, and Floci's DNS server resolves
them to the instances as Aurora points them: the cluster endpoint to the
writer, following a failover; the reader endpoint to another instance, or
the writer when none is served; a custom endpoint to one of the instances it
holds, picked at random, and none once its static members are all deleted.
Answers live five seconds, the TTL of Aurora's DNS zones. A Multi-AZ DB
cluster, whose instances Floci does not create, and an Aurora Serverless v1
cluster, which has none, keep the proxy endpoint.

The names are routed again whenever a cluster's instances, writer or custom
endpoints change, under one lock, and are restored at restart. An IAM token
generated for any of a cluster's names is good at each of its instances, and
the proxies' certificate covers the names. StopDBCluster removes the
instances' relays and StartDBCluster serves them again; a failed instance
create forgets its name and leaves the names as they were; a cluster
restored from a snapshot serves the snapshot's port.

Refs #6273
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-27 10:17:04 -04:00
1 parent 30108fb43f
commit 9c5f57808a
17 files changed
+1164 -106

No files matched your search

+2 -2
View File
@@ -216,7 +216,7 @@ With TLS, set `FLOCI_DNS_SPOOF_AWS_ENDPOINTS` as an environment variable (or `-D
### Floci running natively
The embedded DNS server answers the names above, Cloud Map `<service>.<namespace>` names, Route 53 private zone records and, with `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true`, the endpoint names of RDS instances served in their VPC. When Floci runs in Docker it listens on its own container address, and publishing the container's port 53/udp (for example `-p 127.0.0.1:53:53/udp`) lets the host reach it as well.
The embedded DNS server answers the names above, Cloud Map `<service>.<namespace>` names, Route 53 private zone records and, with `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true`, the endpoint names of RDS instances and clusters served in their VPC. When Floci runs in Docker it listens on its own container address, and publishing the container's port 53/udp (for example `-p 127.0.0.1:53:53/udp`) lets the host reach it as well.
When Floci runs natively, it starts up to two listeners:
@@ -522,7 +522,7 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT` | `false` | Report the requested `Port` instead of the proxy port in `Describe*` |
| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | Serve a DB instance in a VPC at its own address, on its `Port`, under its RDS endpoint name |
| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | Serve a DB instance in a VPC at its own address, on its `Port`, under its RDS endpoint name, and resolve a DB cluster's endpoint names to its instances |
| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port |
| `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them |
| `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL Docker image |
+35 -14
View File
@@ -348,7 +348,7 @@ they belong to, as the model requires. An omitted `Enabled` activates the subscr
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First host port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last host port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT` | `false` | `true` = `Describe*` reports the requested `Port` instead of the proxy port; connect via the proxy port |
| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | `true` = a standalone instance serves its `Port` at its own address in its VPC, under its RDS endpoint name; see [Endpoints in a VPC](#endpoints-in-a-vpc) |
| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | `true` = a DB instance serves its `Port` at its own address in its VPC, under its RDS endpoint name, and a DB cluster's endpoint names resolve to its instances; see [Endpoints in a VPC](#endpoints-in-a-vpc) |
| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port |
| `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them |
| `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances |
@@ -375,8 +375,8 @@ host port; for example, requesting `5432` with the default
`7001`-`7099` range returns a port in that range. Ports outside AWS's valid
`1150`-`65535` interval are rejected.
Set `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true` for a standalone instance to serve its requested `Port` for real, at
its own address in its VPC; see [Endpoints in a VPC](#endpoints-in-a-vpc).
Set `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true` for an instance, or a cluster's instances, to serve the requested
`Port` for real, at their own addresses in their VPC; see [Endpoints in a VPC](#endpoints-in-a-vpc).
Set `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT=true` to make `Describe*` report the requested `Port`
instead (for example so Terraform's `port` does not show a diff). The proxy still listens in the proxy
@@ -575,8 +575,8 @@ another VPC, which it does not move back.
## Endpoints in a VPC
With `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true`, a standalone DB instance gets its own address in its VPC, as on RDS,
instead of sharing Floci's address on a proxy port:
With `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true`, a DB instance gets its own address in its VPC, as on RDS, instead of
sharing Floci's address on a proxy port:
- The instance is served in the subnet of its DB subnet group in its Availability Zone, or the group's first subnet
when none is in it, at an address EC2 leases from that subnet. An instance created without a DB subnet group is in
@@ -589,8 +589,10 @@ instead of sharing Floci's address on a proxy port:
- `DescribeDBInstances` reports that port and the name RDS gives the instance,
`<instance>.<identifier>.<region>.rds.amazonaws.com`. The identifier is twelve letters and digits, the same for
every instance of an account in a Region, as the RDS user guide describes it. Floci's DNS server answers the name
with the instance's address while it runs, and with no address while it is stopped. In the China Regions the name
ends in `amazonaws.com.cn`: AWS publishes no China example, so that shape is Floci's reading.
with the instance's address while it runs, and with no address while it is stopped. The answer lives five seconds,
as "Aurora DNS zones use a short TTL of five seconds" (AWS Knowledge Center), the zone an account's instance and
cluster names in a Region share. In the China Regions the name ends in `amazonaws.com.cn`: AWS publishes no China
example, so that shape is Floci's reading.
- A relay container at the address forwards each connection to the instance's auth proxy, so IAM authentication,
TLS and the master login work as they do on the proxy port. The relay is on the VPC's network and on RDS's Docker
network (`FLOCI_SERVICES_RDS_DOCKER_NETWORK`, else `FLOCI_SERVICES_DOCKER_NETWORK`, else Floci's own), and reaches
@@ -604,6 +606,24 @@ instead of sharing Floci's address on a proxy port:
After a blue/green switchover the new production instance answers on the blue name and address.
- While a relay holds an address, `DeleteSubnet` and `DeleteVpc` refuse to remove its subnet and VPC, as they do for
a subnet a network interface is in.
- Each instance of an Aurora DB cluster is served the same way, at its own address, on the cluster's `Port` or its
engine's default: the API reference says an Aurora instance's port "is managed by the cluster", so a `Port` given
to `CreateDBInstance` for a cluster's instance is not used. Two clusters can both serve 5432. A cluster restored
from a snapshot without a `Port` of its own serves the port the snapshot reports, as the API reference gives that
default. `StopDBCluster` removes the instances' relays and `StartDBCluster` serves them again. A Multi-AZ DB
cluster, whose instances Floci does not create, and an Aurora Serverless v1 cluster (`EngineMode` `serverless`),
which has none, keep the proxy endpoint, where their database is reached.
- `DescribeDBClusters` and `DescribeDBClusterEndpoints` report the names the Aurora user guide gives a cluster's
endpoints, `<cluster>.cluster-<identifier>.<region>.rds.amazonaws.com` for the cluster endpoint,
`<cluster>.cluster-ro-<identifier>...` for the reader endpoint and `<endpoint>.cluster-custom-<identifier>...` for
a custom endpoint. They resolve to the cluster's instances as Aurora points them: the cluster endpoint to the
writer, so a `FailoverDBCluster` moves it to the new writer; the reader endpoint to one of the other instances, or
to the writer when none of them is served; and a custom endpoint to one of the instances it holds (its static
members, or every instance it does not exclude, without the writer for a `READER` endpoint), picked at random, as
Aurora's DNS does. A name with no instance served behind it resolves to no address, as does a custom endpoint whose
static members have all been deleted. So does a cluster with no instance yet, as on AWS: "Until you create the
primary DB instance, the DB cluster endpoints remain in the Creating status" (Aurora user guide). An IAM authentication token
generated for any of a cluster's names is good at each of its instances, as is one for the instance's own name.
- A `DeleteDBInstance` whose relays Docker does not confirm removed, its current one or one a subnet move left,
fails, and the instance keeps its proxy port, so a relay never forwards to another database; a retry removes them.
A `StopDBInstance` stops all the same, and the next start, a delete or a restart removes the relay. Until a relay
@@ -617,12 +637,12 @@ host, still connects through the proxy port, which keeps listening in the proxy
the name and port `DescribeDBInstances` reports.
The name resolves to the private address alone: `PubliclyAccessible` changes nothing, and the address is IPv4 only.
A state reset removes the relays with the instances.
A state reset removes the relays with the instances, and the cluster names with the clusters.
The setting needs Docker-backed VPC networks (`FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED`, on by default) and does
nothing in mock mode. The relay runs EC2's socat image (`FLOCI_SERVICES_EC2_SOCAT_IMAGE`). An instance's VPC security
groups do not filter traffic to its address, even with security-group enforcement on. Aurora and Multi-AZ DB
clusters, their member instances and DB proxies keep the proxy endpoint on Floci's address.
groups do not filter traffic to its address, even with security-group enforcement on. DB proxies keep the proxy
endpoint on Floci's address.
## Modifying a DB instance
@@ -984,10 +1004,11 @@ A `READER` endpoint leaves out the cluster's current writer, so after a failover
instance no longer shows among its members, as Aurora adjusts `READER` membership. Member names match
the cluster's instances regardless of case and are stored as the cluster spells them.
Custom endpoints are modelled, not routed: a custom endpoint reports the cluster's own endpoint host
(read from the cluster each time, so it follows a restart onto another proxy port), so it is
reachable, but connections through it go where the cluster endpoint sends them rather than being
spread across the chosen members.
Outside [Endpoints in a VPC](#endpoints-in-a-vpc), custom endpoints are modelled, not routed: a custom
endpoint reports the cluster's own endpoint host (read from the cluster each time, so it follows a
restart onto another proxy port), so it is reachable, but connections through it go where the
cluster endpoint sends them rather than being spread across the chosen members. With endpoints in
their VPC, a custom endpoint has its own name, which resolves to the instances it holds.
## Data API endpoint
@@ -2137,7 +2137,8 @@ public interface EmulatorConfig {
/**
* When true, a DB instance in a subnet with a Docker-backed VPC network gets its own address there and
* serves the Port it was created with, or its engine's default, under the endpoint name RDS gives it,
* which Floci's DNS server answers. Off, every endpoint is Floci's address and a proxy port.
* which Floci's DNS server answers. A DB cluster's instances serve its port the same way, and its cluster,
* reader and custom endpoint names resolve to them. Off, every endpoint is Floci's address and a proxy port.
*/
@WithDefault("false")
boolean endpointsInVpc();
@@ -51,6 +51,20 @@ public final class AwsEndpoints {
+ region + ".rds." + AwsRegions.dnsSuffixFor(region);
}
/**
* A DB cluster endpoint's address, {@code <name>.<type>-<identifier>.<region>.rds.<dnsSuffix>}, with the
* {@link #rdsEndpointIdentifier} of its account and region. The Aurora user guide gives the three types: a
* cluster's writer endpoint is {@code mydbcluster.cluster-c7tj4example.us-east-1.rds.amazonaws.com}, its reader
* endpoint {@code mydbcluster.cluster-ro-...} and a custom endpoint {@code myendpoint.cluster-custom-...}.
*
* @param name the cluster's identifier, or the custom endpoint's
* @param type {@code cluster}, {@code cluster-ro} or {@code cluster-custom}
*/
public static String rdsClusterEndpointHost(String name, String type, String accountId, String region) {
return name.toLowerCase(Locale.ROOT) + "." + type + "-" + rdsEndpointIdentifier(accountId, region) + "."
+ region + ".rds." + AwsRegions.dnsSuffixFor(region);
}
/** {@code <apiId>.execute-api.<region>.<dnsSuffix>}. */
public static String executeApiHost(String apiId, String region) {
return apiId + "." + host("execute-api", region);
@@ -11,13 +11,19 @@ import java.util.Optional;
/**
* Answers the endpoint names of DB instances served in their VPC, with {@code endpoints-in-vpc} on: an instance's
* {@code <instance>.<identifier>.<region>.rds.<dnsSuffix>} resolves to its address while a relay serves it there, and
* to no address while it is stopped. RDS owns these names, so the answer comes before Floci's own AWS names, which
* would otherwise resolve them to Floci. The names come from {@link RdsEndpointAddresses}' index, so a lookup reads
* no stored instance.
* to no address while it is stopped. A DB cluster's endpoint names resolve to the address of an instance they point
* at. RDS owns these names, so the answer comes before Floci's own AWS names, which would otherwise resolve them to
* Floci. The names come from {@link RdsEndpointAddresses}' index, so a lookup reads no stored instance.
*
* <p>The answer lives five seconds, as "Aurora DNS zones use a short TTL of five seconds" (AWS Knowledge Center), so
* a client follows a failover, or the next random pick of a custom endpoint, as it would on AWS. An account's
* instance and cluster endpoints of a Region share one zone, the identifier in their names.
*/
@ApplicationScoped
public class RdsDnsRecordSource implements DnsRecordSource {
static final int TTL_SECONDS = 5;
private final RdsEndpointAddresses endpointAddresses;
public RdsDnsRecordSource(RdsEndpointAddresses endpointAddresses) {
@@ -37,7 +43,7 @@ public class RdsDnsRecordSource implements DnsRecordSource {
if (type != 1 || address.isEmpty()) {
return Optional.of(DnsAnswer.noData());
}
return Optional.of(DnsAnswer.records(List.of(address.get()), DnsAnswer.DEFAULT_TTL_SECONDS));
return Optional.of(DnsAnswer.records(List.of(address.get()), TTL_SECONDS));
}
@Override
@@ -15,6 +15,7 @@ import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.VpcAddressRelays;
import io.floci.aws.services.ec2.VpcContainerLeases;
import io.floci.aws.services.ec2.VpcDependencyProvider;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbEndpoint;
import io.floci.aws.services.rds.model.DbInstance;
import jakarta.enterprise.context.ApplicationScoped;
@@ -28,6 +29,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
/**
* DB instance endpoints served in their VPC, with {@code endpoints-in-vpc} on. As RDS places an instance in a subnet
@@ -37,6 +39,10 @@ import java.util.concurrent.ConcurrentHashMap;
* instance's auth proxy, so IAM authentication, TLS and the master login work as they do on the proxy port, and two
* instances can both serve 5432.
*
* <p>A DB cluster's instances are served the same way, on the cluster's port, and the cluster's endpoint names
* resolve to them, as Aurora points its endpoints at its instances: the cluster endpoint at the writer, the reader
* endpoint at a reader, and a custom endpoint at one of the instances it holds ({@link ClusterName}).
*
* <p>The endpoint keeps its relay id, subnet and address on the instance record: a restart serves it again at the
* same address, and a blue/green switchover moves them with the endpoint, as it moves the proxy port. Without
* Docker-backed VPC networks, in mock mode, or with the setting off, instances keep the proxy endpoint on Floci's
@@ -57,6 +63,21 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea
* name staying known while it is stopped, until it is deleted or taken out of its VPC.
*/
private final Map<String, String> relayIdsByHost = new ConcurrentHashMap<>();
/** The endpoint names of each DB cluster in its VPC, lowercase, and the instances they resolve to. */
private final Map<String, ClusterName> clusterNamesByHost = new ConcurrentHashMap<>();
/**
* A DB cluster endpoint name and the instances it resolves to: one of {@code hosts}, at random among those served,
* as Aurora's custom endpoints "distribute connections across instances passively, using DNS to return the IP
* address of one of the instances randomly"; with none of them served, one of {@code otherwise}, as the reader
* endpoint of a cluster with no available replica "connects to the primary instance" (Aurora user guide).
*
* @param clusterResourceId the cluster's {@code DbClusterResourceId}
* @param hosts the endpoint names of the instances, as {@link #endpoint} gives them
* @param otherwise the endpoint names of the instances to resolve to when none of {@code hosts} is served
*/
public record ClusterName(String clusterResourceId, List<String> hosts, List<String> otherwise) {
}
@Inject
public RdsEndpointAddresses(EmulatorConfig config, Ec2Service ec2Service, RegionResolver regionResolver,
@@ -175,6 +196,40 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea
return instance.getRequestedPort() != null ? instance.getRequestedPort() : instance.getEngine().defaultPort();
}
/**
* Whether a DB cluster's endpoints are in its VPC: endpoints go in their VPC and the cluster has a subnet for its
* instances to be served in.
*/
public boolean inVpc(DbCluster cluster) {
return enabled() && cluster.getSubnetAvailabilityZones() != null
&& !cluster.getSubnetAvailabilityZones().isEmpty();
}
/** The cluster endpoint a DB cluster in its VPC reports: its RDS name, and the port its instances serve. */
public static DbEndpoint clusterEndpoint(DbCluster cluster, String accountId, String region) {
return new DbEndpoint(AwsEndpoints.rdsClusterEndpointHost(cluster.getDbClusterIdentifier(), "cluster",
accountId, region), servedPort(cluster));
}
/** The reader endpoint a DB cluster in its VPC reports. */
public static DbEndpoint readerEndpoint(DbCluster cluster, String accountId, String region) {
return new DbEndpoint(AwsEndpoints.rdsClusterEndpointHost(cluster.getDbClusterIdentifier(), "cluster-ro",
accountId, region), servedPort(cluster));
}
/** The name of a custom endpoint of a DB cluster in its VPC. */
public static String customEndpointHost(String endpointId, String accountId, String region) {
return AwsEndpoints.rdsClusterEndpointHost(endpointId, "cluster-custom", accountId, region);
}
/**
* The port a DB cluster's instances serve: the Port it was created with, or its engine's default. An instance of
* the cluster serves it too, as the API reference says an Aurora instance's port "is managed by the cluster".
*/
public static int servedPort(DbCluster cluster) {
return cluster.getRequestedPort() != null ? cluster.getRequestedPort() : cluster.getEngine().defaultPort();
}
/**
* Serves the instance's endpoint at its address, relayed to its auth proxy on {@code proxyPort}, records the
* address on the instance, the one it held before when the subnet still has it, and makes its name known.
@@ -277,14 +332,63 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea
return relays.address(instance.getVpcEndpointId()).isPresent();
}
/** Whether {@code host} is the name of an endpoint in its VPC Floci knows, served or stopped. */
public boolean names(String host) {
return relayIdsByHost.containsKey(host.toLowerCase(Locale.ROOT));
/**
* Makes a DB cluster's endpoint names known, each resolving to the instances {@code names} gives it, in place of
* the names it had before: adding or deleting an instance, a failover and a change to a custom endpoint route the
* cluster's names again.
*
* @param names each name of the cluster, as {@link AwsEndpoints} gives it, and the instances it resolves to
*/
public void route(String clusterResourceId, Map<String, ClusterName> names) {
// The new names first, so a lookup between the two steps finds every name the cluster keeps.
clusterNamesByHost.putAll(names);
clusterNamesByHost.entrySet().removeIf(entry -> entry.getValue().clusterResourceId().equals(clusterResourceId)
&& !names.containsKey(entry.getKey()));
}
/** The address the endpoint named {@code host} is served at now; empty while it is stopped, or unknown. */
/** Forgets a DB cluster's endpoint names, as the cluster goes. */
public void forgetCluster(String clusterResourceId) {
clusterNamesByHost.values().removeIf(name -> name.clusterResourceId().equals(clusterResourceId));
}
/**
* Whether {@code host} is one of the endpoint names of the DB cluster {@code clusterResourceId}: each of its
* instances is reached by them, so an IAM token generated for one is good at the instance.
*/
public boolean namesCluster(String clusterResourceId, String host) {
ClusterName name = clusterNamesByHost.get(host.toLowerCase(Locale.ROOT));
return name != null && name.clusterResourceId().equals(clusterResourceId);
}
/** Whether {@code host} is the name of an endpoint in its VPC Floci knows, served or stopped. */
public boolean names(String host) {
String lower = host.toLowerCase(Locale.ROOT);
return relayIdsByHost.containsKey(lower) || clusterNamesByHost.containsKey(lower);
}
/**
* The address the endpoint named {@code host} is served at now: an instance's own, or, for a DB cluster endpoint
* name, that of one of the instances it resolves to. Empty while none of them is served, or when the name is
* unknown.
*/
public Optional<String> addressOf(String host) {
return relays.address(relayIdsByHost.get(host.toLowerCase(Locale.ROOT)));
String lower = host.toLowerCase(Locale.ROOT);
ClusterName clusterName = clusterNamesByHost.get(lower);
if (clusterName == null) {
return relays.address(relayIdsByHost.get(lower));
}
Optional<String> address = anyServed(clusterName.hosts());
return address.isPresent() ? address : anyServed(clusterName.otherwise());
}
private Optional<String> anyServed(List<String> hosts) {
List<String> served = hosts.stream()
.map(relayIdsByHost::get)
.map(relays::address)
.flatMap(Optional::stream)
.toList();
return served.isEmpty() ? Optional.empty()
: Optional.of(served.get(ThreadLocalRandom.current().nextInt(served.size())));
}
@Override
@@ -302,10 +406,11 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea
relays.stopAll();
}
/** A reset wipes the instances whose names the index holds. */
/** A reset wipes the instances and clusters whose names the index holds. */
@Override
public void clear() {
relayIdsByHost.clear();
clusterNamesByHost.clear();
}
/** Writes down again the relays a reset could not remove, whose placements the storage wipe took. */
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsEndpoints;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.BackupWindows;
@@ -224,6 +225,11 @@ public class RdsService implements Resettable, ResourceProvider {
private final RdsEndpointAddresses endpointAddresses;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final Set<String> reportedMemberRelayFailures = ConcurrentHashMap.newKeySet();
/**
* Held while a cluster's endpoint names are worked out and published, so the last change to a cluster's instances
* or custom endpoints is the one its names show: those changes hold different locks.
*/
private final Object clusterNameRoutes = new Object();
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;
@@ -855,9 +861,9 @@ public class RdsService implements Resettable, ResourceProvider {
// Always reserve a unique port (even in mock) so endpoints stay distinct and usedPorts
// is consistent; mock mode only skips starting the container and auth proxy. An endpoint in its
// VPC serves its Port at its own address, so its proxy port is any free one: two instances can both
// ask for the same Port.
boolean endpointInVpc = isBlank(dbClusterIdentifier) && endpointAddresses != null
&& endpointAddresses.enabled();
// ask for the same Port. A cluster's instance goes in its VPC with its cluster.
boolean endpointInVpc = endpointAddresses != null && endpointAddresses.enabled()
&& (isBlank(dbClusterIdentifier) || clusterInVpc(effectiveRegion, dbClusterIdentifier));
int proxyPort = endpointInVpc ? reserveProxyPortBehindVpcEndpoint(requestedPort)
: reserveProxyPort(requestedPort);
@@ -1065,6 +1071,9 @@ public class RdsService implements Resettable, ResourceProvider {
boolean proxyStartAttempted = false;
boolean memberMutationStarted = false;
try {
if (currentCluster != null) {
placeMemberEndpoint(instance, currentCluster, proxyPort);
}
if (manageInstancePassword) {
attachManagedMasterUserSecret(
instance, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId);
@@ -1095,6 +1104,7 @@ public class RdsService implements Resettable, ResourceProvider {
currentCluster.setClusterWriterIdentifier(currentCluster.resolveWriterIdentifier());
}
putClusterForScope(accountId, effectiveRegion, dbClusterIdentifier, currentCluster);
routeClusterNames(currentCluster);
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
@@ -1112,8 +1122,8 @@ public class RdsService implements Resettable, ResourceProvider {
throw failure;
}
}
LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}",
id, engine, endpoint.address(), String.valueOf(endpoint.port()));
LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}", id, engine,
instance.getEndpoint().address(), String.valueOf(instance.getEndpoint().port()));
return instance;
}
@@ -1161,8 +1171,10 @@ public class RdsService implements Resettable, ResourceProvider {
&& !hasFailedWalRollback(rollbackFailure)) {
try {
if (!scopedKeyExists(instances, accountId, dbResourceKey(region, id))) {
if (clusterRollback != null || cleanupFailedStandaloneResources(
failure, instance, region, managedPassword, mock)) {
boolean cleaned = clusterRollback != null ? forgetInVpc(failure, instance)
: cleanupFailedStandaloneResources(
failure, instance, region, managedPassword, mock);
if (cleaned) {
releaseProxyPort(proxyPort);
}
}
@@ -1182,6 +1194,7 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getDbClusterMembers().addAll(clusterRollback.originalMembers());
cluster.setClusterWriterIdentifier(clusterRollback.originalWriter());
putClusterForScope(accountId, region, cluster.getDbClusterIdentifier(), cluster);
routeClusterNames(cluster);
} catch (RuntimeException | Error rollbackFailure) {
cleanupComplete = false;
addSuppressedUnlessSelf(failure, rollbackFailure);
@@ -1200,6 +1213,8 @@ public class RdsService implements Resettable, ResourceProvider {
if (clusterRollback == null) {
cleanupComplete = cleanupFailedStandaloneResources(failure, instance, region, managedPassword, mock);
} else if (!forgetInVpc(failure, instance)) {
cleanupComplete = false;
}
boolean instanceRemoved = !tombstoneWriteNeeded;
@@ -1238,6 +1253,20 @@ public class RdsService implements Resettable, ResourceProvider {
}
}
/**
* {@link #forgetInVpc(DbInstance)} for a failed create: false, with the failure noted on {@code failure}, when
* the relay still forwards to the instance's proxy port, which the record keeps until a delete removes it.
*/
private boolean forgetInVpc(Throwable failure, DbInstance instance) {
try {
forgetInVpc(instance);
return true;
} catch (RuntimeException cleanupFailure) {
addSuppressedUnlessSelf(failure, cleanupFailure);
return false;
}
}
private boolean hasFailedWalRollback(Throwable failure) {
// WalStorage adds suppressed failures only when recovery of an appended record fails.
return failure instanceof UncheckedIOException ioFailure
@@ -1246,14 +1275,7 @@ public class RdsService implements Resettable, ResourceProvider {
private boolean cleanupFailedStandaloneResources(
Throwable failure, DbInstance instance, String region, boolean managedPassword, boolean mock) {
boolean cleanupComplete = true;
try {
forgetInVpc(instance);
} catch (RuntimeException cleanupFailure) {
// The relay still forwards to the instance's proxy port, which the record keeps until a delete removes it.
cleanupComplete = false;
addSuppressedUnlessSelf(failure, cleanupFailure);
}
boolean cleanupComplete = forgetInVpc(failure, instance);
if (!mock && instance.getDockerVolumeName() != null) {
try {
if (instance.getContainerId() != null) {
@@ -2822,15 +2844,19 @@ public class RdsService implements Resettable, ResourceProvider {
.orElseThrow(() -> new AwsException("DBClusterSnapshotNotFoundFault",
"DB cluster snapshot data for " + resolvedSnapshotId + " not found.", 404));
String restoredMode = engineMode != null && !engineMode.isBlank() ? engineMode : snapshot.getEngineMode();
// Where its instances serve the port in its VPC, the API reference's default: "The same port as the original
// DB cluster". A cluster on the proxy endpoint keeps a free proxy port, as the original may still hold its own.
Integer restoredPort = namesResolveToInstances(engine, restoredMode)
? portFromSource(port, snapshot.getPort()) : port;
DbCluster cluster = createDbClusterWithPort(clusterId, engine,
engineVersion != null && !engineVersion.isBlank() ? engineVersion : snapshot.getEngineVersion(),
snapshot.getMasterUsername(), snapshot.getMasterPassword(),
databaseName != null && !databaseName.isBlank() ? databaseName : snapshot.getDatabaseName(),
Boolean.TRUE.equals(iamEnabled),
parameterGroupName, dbSubnetGroupName, availabilityZone, false, effectiveRegion,
null, null, null, false, null,
engineMode != null && !engineMode.isBlank() ? engineMode : snapshot.getEngineMode(),
snapshot.isStorageEncrypted(), port, deletionProtection);
null, null, null, false, null, restoredMode, snapshot.isStorageEncrypted(), restoredPort,
deletionProtection);
if (tags != null && !tags.isEmpty()) {
cluster.getTags().putAll(tags);
putClusterForScope(accountId, effectiveRegion, clusterId, cluster);
@@ -4779,13 +4805,7 @@ public class RdsService implements Resettable, ResourceProvider {
if (!config.services().rds().mock()) {
proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
try {
stopServingInVpc(instance);
} catch (RuntimeException e) {
// Still tracked, the relay forwards to the port the stopped instance keeps; the next start or a
// delete removes it.
LOG.warnv(e, "DB instance {0} stops with its relay still present", id);
}
stopServingStoppedInVpc(instance);
if (instance.getContainerId() != null) {
try {
containerManager.stop(buildHandle(instance));
@@ -4948,6 +4968,7 @@ public class RdsService implements Resettable, ResourceProvider {
}
if (!mock) {
proxyManager.stopProxy(rdsResourceRelayKey(member.getDbInstanceArn(), memberId));
stopServingStoppedInVpc(member);
}
member.setStatus(DbInstanceStatus.STOPPED);
member.setContainerHost(null);
@@ -4996,9 +5017,7 @@ public class RdsService implements Resettable, ResourceProvider {
if (isDsqlReservedPort(cluster.getProxyPort())) {
int port = allocateProxyPort();
cluster.setProxyPort(port);
DbEndpoint endpoint = advertised(proxyEndpoint(port), cluster.getRequestedPort());
cluster.setEndpoint(endpoint);
cluster.setReaderEndpoint(endpoint);
setClusterEndpoints(cluster, port);
}
refreshManagedMasterUserSecret(cluster, effectiveRegion);
cluster.setStatus(DbInstanceStatus.STARTING);
@@ -5332,8 +5351,14 @@ public class RdsService implements Resettable, ResourceProvider {
String region, String accountId, String resourceId) {
boolean tokensBoundToEndpoint = engine != DatabaseEngine.POSTGRES
|| config.services().rds().iamTokenEndpointBinding();
if (endpointAddresses == null || !endpointAddresses.enabled()) {
return new RdsProxyBinding(advertisedHost, publishedPort, region, accountId, resourceId,
tokensBoundToEndpoint);
}
// A cluster's endpoint names resolve to its instances in its VPC, so the cluster's proxy and each of its
// instances' (whose resource id is the cluster's) take a token generated for any of them.
return new RdsProxyBinding(advertisedHost, publishedPort, region, accountId, resourceId,
tokensBoundToEndpoint);
tokensBoundToEndpoint, host -> endpointAddresses.namesCluster(resourceId, host));
}
private static boolean hasBackend(String host, int port) {
@@ -5425,9 +5450,7 @@ public class RdsService implements Resettable, ResourceProvider {
relayEndpoint.port(), instanceRegion, accountId,
backendIdentity.dbUserResourceId()));
proxyStarted = true;
if (started != null) {
serveInVpc(instance, relayPort);
}
serveInVpc(instance, relayPort);
} catch (RuntimeException e) {
if (proxyStarted) {
proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
@@ -5545,7 +5568,7 @@ public class RdsService implements Resettable, ResourceProvider {
if (relayEndpoint == null) {
relayPort = allocateProxyPort();
allocatedRelayPort = true;
relayEndpoint = advertised(proxyEndpoint(relayPort), cluster.getRequestedPort());
relayEndpoint = clusterEndpoint(cluster, relayPort);
}
proxyManager.startProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id),
cluster.getDbClusterArn(),
@@ -5571,7 +5594,7 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.setProxyPort(relayPort);
cluster.setEndpoint(relayEndpoint);
if (cluster.getReaderEndpoint() == null) {
cluster.setReaderEndpoint(relayEndpoint);
cluster.setReaderEndpoint(clusterReaderEndpoint(cluster, relayPort));
}
if (cluster.getStatus() == DbInstanceStatus.FAILED) {
cluster.setStatus(DbInstanceStatus.AVAILABLE);
@@ -5795,6 +5818,7 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.setClusterWriterIdentifier(cluster.resolveWriterIdentifier());
putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster);
dropFromClusterEndpoints(effectiveRegion, clusterId, id);
routeClusterNames(cluster);
}
}
@@ -5995,8 +6019,13 @@ public class RdsService implements Resettable, ResourceProvider {
String effectiveSecretKmsKeyId = manageMasterUserPassword
? resolveManagedSecretKmsKeyId(masterUserSecretKmsKeyId, effectiveRegion) : null;
// Always reserve a unique port (even in mock) so endpoints stay distinct and usedPorts
// is consistent; mock mode only skips starting the container and auth proxy.
int proxyPort = reserveProxyPort(requestedPort);
// is consistent; mock mode only skips starting the container and auth proxy. With endpoints in
// their VPC, a cluster's instances serve its Port at their own addresses, so its proxy port is
// any free one, as an instance's is.
boolean endpointsInVpc = endpointAddresses != null && endpointAddresses.enabled()
&& namesResolveToInstances(effectiveEngineName(engineParam), engineMode);
int proxyPort = endpointsInVpc ? reserveProxyPortBehindVpcEndpoint(requestedPort)
: reserveProxyPort(requestedPort);
if (manageMasterUserPassword && (masterPassword == null || masterPassword.isBlank())) {
masterPassword = generatedMasterPassword();
}
@@ -6051,6 +6080,9 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.setDbClusterResourceId(clusterResourceId);
cluster.setDbClusterArn(clusterArn);
if (clusterInVpc(cluster)) {
setClusterEndpoints(cluster, proxyPort);
}
if (manageMasterUserPassword) {
attachManagedMasterUserSecret(cluster, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId);
@@ -6121,8 +6153,9 @@ 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()));
routeClusterNames(cluster);
LOG.infov("DB cluster {0} created (mock={1}), engine={2}, endpoint={3}:{4}", id, String.valueOf(mock),
engine, cluster.getEndpoint().address(), String.valueOf(cluster.getEndpoint().port()));
return cluster;
}
@@ -6766,9 +6799,14 @@ public class RdsService implements Resettable, ResourceProvider {
throw failure;
}
releaseProxyPort(cluster.getProxyPort());
// Custom endpoints belong to their cluster and go with it.
// Custom endpoints belong to their cluster and go with it, and so do its names.
clusterEndpointsOf(effectiveRegion, id).forEach(endpoint -> clusterEndpoints.delete(
clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier())));
if (endpointAddresses != null && cluster.getDbClusterResourceId() != null) {
synchronized (clusterNameRoutes) {
endpointAddresses.forgetCluster(cluster.getDbClusterResourceId());
}
}
if (retained != null) {
clusterAutomatedBackups.put(dbResourceKey(effectiveRegion, cluster.getDbClusterResourceId()), retained);
}
@@ -7173,6 +7211,8 @@ public class RdsService implements Resettable, ResourceProvider {
}
cluster.setClusterWriterIdentifier(target);
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
// The cluster endpoint now resolves to the new writer, as Aurora moves it on failover.
routeClusterNames(cluster);
LOG.infov("DB cluster {0}: {1} is now the writer", id, target);
return cluster;
}
@@ -9443,8 +9483,9 @@ public class RdsService implements Resettable, ResourceProvider {
/**
* The Port an instance made from a source takes in its VPC when its request names none: RDS gives a restore "the
* same port as the original DB instance" and a read replica the port it "inherits ... from the source DB
* instance" (the API reference's defaults), and a green instance is made from its blue one. Outside a VPC the
* Port stays as the request gave it, which leaves the proxy endpoint as it was.
* instance" (the API reference's defaults), and a green instance is made from its blue one. A cluster restored
* from a snapshot takes "the same port as the original DB cluster", the one its snapshot reports. Outside a VPC
* the Port stays as the request gave it, which leaves the proxy endpoint as it was.
*/
private Integer portFromSource(Integer requested, Integer sourcePort) {
if (requested != null || endpointAddresses == null || !endpointAddresses.enabled()) {
@@ -9522,6 +9563,160 @@ public class RdsService implements Resettable, ResourceProvider {
return advertised(proxyEndpoint(proxyPort), instance.getRequestedPort());
}
/**
* The cluster endpoint a cluster on {@code proxyPort} reports: its name in its VPC when its endpoints are there,
* otherwise the proxy endpoint.
*/
private DbEndpoint clusterEndpoint(DbCluster cluster, int proxyPort) {
if (clusterInVpc(cluster)) {
return RdsEndpointAddresses.clusterEndpoint(cluster, accountIdFromArn(cluster.getDbClusterArn()),
regionResolver.regionOf(cluster.getDbClusterArn()));
}
return advertised(proxyEndpoint(proxyPort), cluster.getRequestedPort());
}
/** The reader endpoint a cluster on {@code proxyPort} reports; outside its VPC, the cluster endpoint. */
private DbEndpoint clusterReaderEndpoint(DbCluster cluster, int proxyPort) {
if (clusterInVpc(cluster)) {
return RdsEndpointAddresses.readerEndpoint(cluster, accountIdFromArn(cluster.getDbClusterArn()),
regionResolver.regionOf(cluster.getDbClusterArn()));
}
return clusterEndpoint(cluster, proxyPort);
}
private void setClusterEndpoints(DbCluster cluster, int proxyPort) {
cluster.setEndpoint(clusterEndpoint(cluster, proxyPort));
cluster.setReaderEndpoint(clusterReaderEndpoint(cluster, proxyPort));
}
/** {@link #clusterInVpc(DbCluster)} for the cluster of the request's account named {@code clusterId}. */
private boolean clusterInVpc(String region, String clusterId) {
DbCluster cluster = findClusterForScope(currentAccountId(), region, clusterId);
return cluster != null && clusterInVpc(cluster);
}
/** Whether the cluster's endpoints are in its VPC, where its instances serve them. */
private boolean clusterInVpc(DbCluster cluster) {
return endpointAddresses != null
&& namesResolveToInstances(cluster.getEngineIdentifier(), cluster.getEngineMode())
&& endpointAddresses.inVpc(cluster);
}
/**
* Whether a cluster's endpoint names have instances to resolve to: an Aurora cluster's do, the instances
* CreateDBInstance adds to it. A Multi-AZ DB cluster, whose instances Floci does not create, and an Aurora
* Serverless v1 cluster ({@code EngineMode} {@code serverless}), which has none, keep the proxy endpoint, where
* their database is reached.
*/
private static boolean namesResolveToInstances(String engineIdentifier, String engineMode) {
return isAuroraEngine(engineIdentifier) && !"serverless".equalsIgnoreCase(engineMode);
}
/** Whether the cluster reports the endpoint names of its VPC, as a restart that turned the setting off finds. */
private boolean namedInVpc(DbCluster cluster) {
if (cluster.getEndpoint() == null || cluster.getDbClusterArn() == null) {
return false;
}
return cluster.getEndpoint().address().equals(RdsEndpointAddresses.clusterEndpoint(cluster,
accountIdFromArn(cluster.getDbClusterArn()), regionResolver.regionOf(cluster.getDbClusterArn()))
.address());
}
/**
* Makes a cluster's endpoint names resolve to its instances as they stand now, as Aurora points them: the cluster
* endpoint at the writer, the reader endpoint at the other instances, or at the writer when there are none, and
* each custom endpoint at the instances it holds. Called whenever the instances, the writer or a custom endpoint
* change; outside its VPC the cluster has no such names. The proxies' certificate covers the names, which TLS
* clients check the instances' certificate against.
*/
private void routeClusterNames(DbCluster cluster) {
if (endpointAddresses == null || cluster.getDbClusterResourceId() == null) {
return;
}
Collection<String> hosts;
synchronized (clusterNameRoutes) {
hosts = publishClusterNames(cluster);
}
for (String host : hosts) {
try {
proxyManager.coverTlsHost(host);
} catch (RuntimeException e) {
// The name still resolves; only a client that checks the certificate's names refuses it.
LOG.warnv(e, "The RDS proxies' certificate does not cover {0}", host);
}
}
}
/** Publishes the cluster's endpoint names as {@link #routeClusterNames} describes, and returns them. */
private Collection<String> publishClusterNames(DbCluster cluster) {
String resourceId = cluster.getDbClusterResourceId();
if (!clusterInVpc(cluster)) {
endpointAddresses.forgetCluster(resourceId);
return List.of();
}
String accountId = accountIdFromArn(cluster.getDbClusterArn());
String region = regionResolver.regionOf(cluster.getDbClusterArn());
String writer = cluster.resolveWriterIdentifier();
List<String> members = List.copyOf(cluster.getDbClusterMembers());
Function<List<String>, List<String>> hostsOf = ids -> ids.stream()
.map(id -> AwsEndpoints.rdsInstanceHost(id, accountId, region))
.toList();
List<String> writerHosts = hostsOf.apply(writer == null ? List.of() : List.of(writer));
Map<String, RdsEndpointAddresses.ClusterName> names = new LinkedHashMap<>();
names.put(RdsEndpointAddresses.clusterEndpoint(cluster, accountId, region).address(),
new RdsEndpointAddresses.ClusterName(resourceId, writerHosts, List.of()));
names.put(RdsEndpointAddresses.readerEndpoint(cluster, accountId, region).address(),
new RdsEndpointAddresses.ClusterName(resourceId,
hostsOf.apply(members.stream().filter(member -> !member.equals(writer)).toList()),
writerHosts));
// In the cluster's account, which a restart reads outside any request.
List<DbClusterEndpoint> customs = RequestScopes.callAs(accountId, region,
() -> clusterEndpointsOf(region, cluster.getDbClusterIdentifier()));
for (DbClusterEndpoint custom : customs) {
String host = RdsEndpointAddresses.customEndpointHost(custom.getDbClusterEndpointIdentifier(), accountId,
region);
names.put(host, new RdsEndpointAddresses.ClusterName(resourceId,
hostsOf.apply(customEndpointMembers(custom, members, writer)), List.of()));
}
endpointAddresses.route(resourceId, names);
return names.keySet();
}
/**
* Gives an instance of a cluster whose endpoints are in its VPC its own endpoint there, as a standalone instance
* gets one: it serves the cluster's port, as the API reference says an Aurora instance's port "is managed by the
* cluster", and the cluster's names resolve to it.
*/
private void placeMemberEndpoint(DbInstance member, DbCluster cluster, int proxyPort) {
if (!clusterInVpc(cluster)) {
return;
}
member.setRequestedPort(cluster.getRequestedPort());
if (endpointAddresses.assign(member)) {
member.setEndpoint(instanceEndpoint(member, proxyPort));
// Known from now on, so the name resolves to no address rather than to Floci until it is served.
endpointAddresses.remember(member, accountIdFromArn(member.getDbInstanceArn()),
regionResolver.regionOf(member.getDbInstanceArn()));
}
}
/**
* The instances a custom endpoint holds now: for one with an exclusion list, every instance it does not exclude,
* as the API reference says of ExcludedMembers ("All other eligible instances are reachable through the custom
* endpoint"); otherwise its static members, and none once deletes have taken them all. A {@code READER} endpoint
* leaves out the writer.
*/
static List<String> customEndpointMembers(DbClusterEndpoint endpoint, List<String> members, String writer) {
boolean readerOnly = "READER".equals(endpoint.getCustomEndpointType());
List<String> excluded = endpoint.getExcludedMembers();
boolean exclusionList = endpoint.isExclusionList() || !excluded.isEmpty();
return members.stream()
.filter(member -> exclusionList ? !excluded.contains(member)
: endpoint.getStaticMembers().contains(member))
.filter(member -> !readerOnly || !member.equals(writer))
.toList();
}
/** Serves a standalone instance's endpoint in its VPC, relayed to its running proxy, when it has one there. */
private void serveInVpc(DbInstance instance) {
serveInVpc(instance, instance.getProxyPort());
@@ -9560,6 +9755,17 @@ public class RdsService implements Resettable, ResourceProvider {
}
}
/** Stops serving the endpoint of an instance that stops, which stops all the same when Docker keeps the relay. */
private void stopServingStoppedInVpc(DbInstance instance) {
try {
stopServingInVpc(instance);
} catch (RuntimeException e) {
// Still tracked, the relay forwards to the port the stopped instance keeps; the next start or a
// delete removes it.
LOG.warnv(e, "DB instance {0} stops with its relay still present", instance.getDbInstanceIdentifier());
}
}
/**
* Whether a relay of the instance's endpoint in its VPC may still run, forwarding to its proxy port: one that
* serves, or one whose start Docker left unclear. A new instance has no relay it moved off.
@@ -9581,22 +9787,30 @@ public class RdsService implements Resettable, ResourceProvider {
}
/**
* Puts a restored standalone instance's endpoint in its VPC, or takes it out, as {@code endpoints-in-vpc}
* now says: the setting may have changed across the restart.
* Puts a restored instance's endpoint in its VPC, or takes it out, as {@code endpoints-in-vpc} now says: the
* setting may have changed across the restart. An instance of a cluster goes in with its cluster.
*/
private void placeRestoredEndpoint(DbInstance instance) {
if (endpointAddresses == null || !isBlank(instance.getDbClusterIdentifier())) {
if (endpointAddresses == null) {
return;
}
DbCluster cluster = isBlank(instance.getDbClusterIdentifier()) ? null
: findClusterForScope(accountIdFromArn(instance.getDbInstanceArn()),
regionResolver.regionOf(instance.getDbInstanceArn()), instance.getDbClusterIdentifier());
boolean wanted = cluster != null ? clusterInVpc(cluster)
: isBlank(instance.getDbClusterIdentifier()) && endpointAddresses.enabled();
endpointAddresses.removeStaleRelays(instance);
if (RdsEndpointAddresses.inVpc(instance) && !endpointAddresses.enabled()) {
if (RdsEndpointAddresses.inVpc(instance) && !wanted) {
try {
endpointAddresses.unassign(instance);
} catch (RuntimeException e) {
LOG.warnv(e, "DB instance {0} keeps its endpoint in its VPC until its relay can be removed",
instance.getDbInstanceIdentifier());
}
} else if (!RdsEndpointAddresses.inVpc(instance)) {
} else if (!RdsEndpointAddresses.inVpc(instance) && wanted) {
if (cluster != null) {
instance.setRequestedPort(cluster.getRequestedPort());
}
endpointAddresses.assign(instance);
}
if (RdsEndpointAddresses.inVpc(instance)) {
@@ -9633,6 +9847,9 @@ public class RdsService implements Resettable, ResourceProvider {
/** {@link #connectablePort(DbInstance)} for a cluster. */
public int connectablePort(DbCluster cluster) {
if (clusterInVpc(cluster) && cluster.getEndpoint() != null) {
return cluster.getEndpoint().port();
}
return advertises(cluster.getRequestedPort())
? connectablePort(cluster.getProxyPort()) : cluster.getEndpoint().port();
}
@@ -10383,11 +10600,10 @@ public class RdsService implements Resettable, ResourceProvider {
// brings its container back. Its endpoint keeps its port when that port is free.
int port = claimRestoredProxyPort(
persistedPortOwners, cluster.getDbClusterArn(), cluster.getProxyPort());
if (port != cluster.getProxyPort()) {
// endpoints-in-vpc may have changed across the restart, which moves the names in or out.
if (port != cluster.getProxyPort() || clusterInVpc(cluster) || namedInVpc(cluster)) {
cluster.setProxyPort(port);
DbEndpoint endpoint = advertised(proxyEndpoint(port), cluster.getRequestedPort());
cluster.setEndpoint(endpoint);
cluster.setReaderEndpoint(endpoint);
setClusterEndpoints(cluster, port);
putClusterForScope(accountIdFromArn(cluster.getDbClusterArn()),
regionResolver.regionOf(cluster.getDbClusterArn()), cluster.getDbClusterIdentifier(),
cluster);
@@ -10404,6 +10620,7 @@ public class RdsService implements Resettable, ResourceProvider {
cluster);
}
refreshManagedMasterUserSecret(cluster, regionResolver.regionOf(cluster.getDbClusterArn()));
routeClusterNames(cluster);
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to restore stopped RDS cluster {0}", cluster.getDbClusterIdentifier());
}
@@ -10434,10 +10651,10 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getDbClusterIdentifier(), cluster);
continue;
}
DbEndpoint endpoint = advertised(proxyEndpoint(proxyPort), cluster.getRequestedPort());
cluster.setEndpoint(endpoint);
cluster.setReaderEndpoint(endpoint);
setClusterEndpoints(cluster, proxyPort);
refreshManagedMasterUserSecret(cluster, clusterRegion);
// Known whatever comes of the backend, so the names resolve to the instances once they are served.
routeClusterNames(cluster);
String image = imageForEngine(cluster.getEngine(), cluster.getEngineVersion());
restoredHandle = containerManager.tryStart(
cluster.getDbClusterArn(), cluster.getDbClusterIdentifier(),
@@ -10624,9 +10841,7 @@ public class RdsService implements Resettable, ResourceProvider {
proxyBinding(instance.getEngine(), instance.getEndpoint().address(),
instance.getEndpoint().port(), instanceRegion, accountId,
backendIdentity.dbUserResourceId()));
if (restoredHandle != null) {
serveInVpc(instance);
}
serveInVpc(instance);
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, instanceRegion,
@@ -12895,15 +13110,17 @@ public class RdsService implements Resettable, ResourceProvider {
endpoint.setDbClusterIdentifier(cluster.getDbClusterIdentifier());
endpoint.setDbClusterEndpointResourceIdentifier("cluster-endpoint-"
+ UUID.randomUUID().toString().replace("-", "").substring(0, 24).toLowerCase(Locale.ROOT));
endpoint.setEndpoint(clusterEndpointHost(cluster));
endpoint.setEndpoint(customEndpointHost(cluster, id));
endpoint.setStatus("available");
endpoint.setEndpointType("CUSTOM");
endpoint.setCustomEndpointType(customType);
endpoint.setStaticMembers(staticMembers != null ? new ArrayList<>(staticMembers) : new ArrayList<>());
endpoint.setExcludedMembers(excludedMembers != null ? new ArrayList<>(excludedMembers) : new ArrayList<>());
endpoint.setExclusionList(staticMembers == null || staticMembers.isEmpty());
endpoint.setDbClusterEndpointArn(regionResolver.buildArn("rds", effectiveRegion, "cluster-endpoint:" + id));
endpoint.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());
clusterEndpoints.put(key, endpoint);
routeClusterNames(cluster);
return endpoint;
}
@@ -12929,7 +13146,11 @@ public class RdsService implements Resettable, ResourceProvider {
endpoint.setCustomEndpointType(customType);
endpoint.setStaticMembers(newStatic != null ? new ArrayList<>(newStatic) : new ArrayList<>());
endpoint.setExcludedMembers(newExcluded != null ? new ArrayList<>(newExcluded) : new ArrayList<>());
if (listsGiven) {
endpoint.setExclusionList(newStatic == null || newStatic.isEmpty());
}
clusterEndpoints.put(clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier()), endpoint);
routeClusterNames(cluster);
return currentView(endpoint, cluster);
}
@@ -12938,8 +13159,11 @@ public class RdsService implements Resettable, ResourceProvider {
String effectiveRegion = effectiveRegion(region);
DbClusterEndpoint endpoint = requireClusterEndpoint(effectiveRegion, endpointId);
clusterEndpoints.delete(clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier()));
DbClusterEndpoint deleted = currentView(endpoint,
findClusterForScope(currentAccountId(), effectiveRegion, endpoint.getDbClusterIdentifier()));
DbCluster cluster = findClusterForScope(currentAccountId(), effectiveRegion, endpoint.getDbClusterIdentifier());
if (cluster != null) {
routeClusterNames(cluster);
}
DbClusterEndpoint deleted = currentView(endpoint, cluster);
deleted.setStatus("deleting");
return deleted;
}
@@ -13011,11 +13235,12 @@ public class RdsService implements Resettable, ResourceProvider {
}
/**
* A custom endpoint as it stands now. Its address follows the cluster's endpoint, which a
* restart can move to another proxy port. A READER endpoint leaves out the cluster's current
* writer, as Aurora adjusts READER membership on failover and promotion (user guide).
* A custom endpoint as it stands now. Its address is its own name in the cluster's VPC, and
* otherwise follows the cluster's endpoint, which a restart can move to another proxy port. A
* READER endpoint leaves out the cluster's current writer, as Aurora adjusts READER membership
* on failover and promotion (user guide).
*/
private static DbClusterEndpoint currentView(DbClusterEndpoint stored, DbCluster cluster) {
private DbClusterEndpoint currentView(DbClusterEndpoint stored, DbCluster cluster) {
DbClusterEndpoint view = new DbClusterEndpoint();
view.setDbClusterEndpointIdentifier(stored.getDbClusterEndpointIdentifier());
view.setDbClusterIdentifier(stored.getDbClusterIdentifier());
@@ -13029,7 +13254,8 @@ public class RdsService implements Resettable, ResourceProvider {
List<String> staticMembers = new ArrayList<>(stored.getStaticMembers());
String host = stored.getEndpoint();
if (cluster != null) {
host = clusterEndpointHost(cluster) != null ? clusterEndpointHost(cluster) : host;
String current = customEndpointHost(cluster, stored.getDbClusterEndpointIdentifier());
host = current != null ? current : host;
String writer = cluster.resolveWriterIdentifier();
if ("READER".equals(stored.getCustomEndpointType()) && writer != null) {
staticMembers.removeIf(writer::equalsIgnoreCase);
@@ -13061,6 +13287,18 @@ public class RdsService implements Resettable, ResourceProvider {
return cluster.getEndpoint() != null ? cluster.getEndpoint().address() : null;
}
/**
* A custom endpoint's address: its own name in its cluster's VPC, where it resolves to the instances it holds;
* otherwise the cluster's endpoint host, which reaches the cluster's database.
*/
private String customEndpointHost(DbCluster cluster, String endpointId) {
if (clusterInVpc(cluster)) {
return RdsEndpointAddresses.customEndpointHost(endpointId, accountIdFromArn(cluster.getDbClusterArn()),
regionResolver.regionOf(cluster.getDbClusterArn()));
}
return clusterEndpointHost(cluster);
}
private DbClusterEndpoint requireClusterEndpoint(String region, String endpointId) {
if (isBlank(endpointId)) {
throw new AwsException("InvalidParameterValue", "DBClusterEndpointIdentifier is required.", 400);
@@ -13132,6 +13370,7 @@ public class RdsService implements Resettable, ResourceProvider {
.toList();
}
/** A deleted instance drops out of the static and exclusion lists that name it. */
private void dropFromClusterEndpoints(String region, String clusterId, String instanceId) {
for (DbClusterEndpoint endpoint : clusterEndpointsOf(region, clusterId)) {
@@ -26,6 +26,12 @@ public class DbClusterEndpoint {
private String customEndpointType;
private List<String> staticMembers = new ArrayList<>();
private List<String> excludedMembers = new ArrayList<>();
/**
* Whether the endpoint holds every instance its exclusion list leaves, as one created or modified with
* ExcludedMembers, or with neither list, does. Otherwise it holds its static members alone, and none once deletes
* empty the list; so does one stored before this was recorded whose lists are both empty, whose kind is unknown.
*/
private boolean exclusionList;
private String dbClusterEndpointArn;
private Map<String, String> tags = new LinkedHashMap<>();
@@ -58,6 +64,9 @@ public class DbClusterEndpoint {
public List<String> getExcludedMembers() { return excludedMembers; }
public void setExcludedMembers(List<String> excludedMembers) { this.excludedMembers = excludedMembers; }
public boolean isExclusionList() { return exclusionList; }
public void setExclusionList(boolean exclusionList) { this.exclusionList = exclusionList; }
public String getDbClusterEndpointArn() { return dbClusterEndpointArn; }
public void setDbClusterEndpointArn(String dbClusterEndpointArn) { this.dbClusterEndpointArn = dbClusterEndpointArn; }
@@ -1,5 +1,7 @@
package io.floci.aws.services.rds.proxy;
import java.util.function.Predicate;
/**
* The identity a running RDS proxy publishes and that IAM auth tokens are validated against:
* the endpoint the token must have been generated for (host, port, region) and the scope of
@@ -14,20 +16,34 @@ package io.floci.aws.services.rds.proxy;
* MySQL endpoints always require that; PostgreSQL endpoints unless
* {@code services.rds.iam-token-endpoint-binding} is turned off for
* tokens generated for a name the endpoint does not publish.
* @param otherNames the other names the endpoint is reached by now, such as the cluster, reader
* and custom endpoint names of the DB cluster an instance is a member of,
* which resolve to the instance's own address
*/
public record RdsProxyBinding(String advertisedHost, int publishedPort, String region,
String accountId, String resourceId, boolean tokensBoundToEndpoint) {
String accountId, String resourceId, boolean tokensBoundToEndpoint,
Predicate<String> otherNames) {
/** For an endpoint reached by its advertised name alone. */
public static final Predicate<String> NO_OTHER_NAMES = host -> false;
public RdsProxyBinding(String advertisedHost, int publishedPort, String region,
String accountId, String resourceId, boolean tokensBoundToEndpoint) {
this(advertisedHost, publishedPort, region, accountId, resourceId, tokensBoundToEndpoint, NO_OTHER_NAMES);
}
/**
* Whether a token generated for {@code host} names this endpoint. Besides the advertised
* host, the loopback names count: Floci advertises the name containers reach it by
* ({@code host.docker.internal} natively, its own address in Docker) while a client on the
* host connects to the loopback interface, and both are the same proxy. The published port
* still has to match, so a token for a different instance on the same host is refused.
* host connects to the loopback interface, and both are the same proxy. So do the
* {@link #otherNames}. The published port still has to match, so a token for a different
* instance on the same host is refused.
*/
public boolean acceptsHost(String host) {
return advertisedHost.equalsIgnoreCase(host)
|| "localhost".equalsIgnoreCase(host)
|| "127.0.0.1".equals(host);
|| "127.0.0.1".equals(host)
|| (host != null && otherNames.test(host));
}
}
@@ -172,6 +172,14 @@ public class RdsProxyManager {
this.forceSsl = forceSsl;
}
/**
* Puts {@code host} on the proxies' TLS certificate, for a name clients reach a proxy by besides the one it
* advertises, such as a DB cluster's endpoint names, which resolve to its instances.
*/
public void coverTlsHost(String host) {
tlsCertificates.ensureHost(host);
}
public synchronized void updateMasterPassword(String instanceId, String newPassword) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {
+1 -1
View File
@@ -655,7 +655,7 @@ floci:
proxy-base-port: 7001
proxy-max-port: 7099
# advertise-requested-port: false # FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT; true = Describe* reports the requested Port, not the proxy port
# endpoints-in-vpc: false # FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC; true = an instance in a VPC serves its Port at its own address and RDS endpoint name
# endpoints-in-vpc: false # FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC; true = an instance in a VPC serves its Port at its own address and RDS endpoint name, and a cluster's endpoint names resolve to its instances
# endpoint-host: localhost # Hostname clients use; enables published-port translation in Docker
# iam-token-endpoint-binding: true # FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING; false accepts PostgreSQL IAM tokens generated for another hostname or port
# Omit image overrides to adapt Floci's built-in images to EngineVersion.
@@ -91,6 +91,18 @@ class AwsEndpointsTest {
PartitionMatrix.assertHostIn(partitionCase, AwsEndpoints.rdsInstanceHost("db1", "123456789012", region));
}
@ParameterizedTest
@MethodSource("io.floci.aws.testing.PartitionMatrix#cases")
void aDbClusterEndpointHostCarriesItsTypeBeforeTheIdentifier(PartitionCase partitionCase) {
String region = partitionCase.region();
String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", region);
assertEquals("orders.cluster-ro-" + identifier + "." + region + ".rds." + partitionCase.dnsSuffix(),
AwsEndpoints.rdsClusterEndpointHost("Orders", "cluster-ro", "123456789012", region));
PartitionMatrix.assertHostIn(partitionCase,
AwsEndpoints.rdsClusterEndpointHost("orders", "cluster", "123456789012", region));
}
@Test
void theRdsEndpointIdentifierIsTwelveLettersAndDigitsALetterFirst() {
String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", "us-east-1");
@@ -16,7 +16,7 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** An instance's endpoint name in its VPC resolves to the address its relay holds. */
/** An endpoint name in its VPC resolves to the address of the relay behind it. */
class RdsDnsRecordSourceTest {
private static final String NAME = "db1.abcdefghijkl.us-east-1.rds.amazonaws.com";
@@ -41,6 +41,11 @@ class RdsDnsRecordSourceTest {
assertEquals(List.of("10.0.1.20"), source.resolveAuthoritative(NAME + ".", 1).orElseThrow().addresses());
}
@Test
void theAnswerLivesFiveSecondsAsAuroraDnsZonesDo() {
assertEquals(5, source.resolveAuthoritative(NAME, 1).orElseThrow().ttlSeconds());
}
@Test
void anEndpointHasNoIpv6Address() {
DnsAnswer answer = source.resolveAuthoritative(NAME, 28).orElseThrow();
@@ -8,6 +8,7 @@ import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.VpcRelayFixture;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.rds.model.DatabaseEngine;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbEndpoint;
import io.floci.aws.services.rds.model.DbInstance;
import io.floci.aws.services.rds.model.DbInstanceStatus;
@@ -15,10 +16,12 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -32,7 +35,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Where an instance's endpoint in its VPC is served, and what it reports. */
/** Where an instance's endpoint in its VPC is served, what it reports, and what a cluster's names resolve to. */
class RdsEndpointAddressesTest {
private static final String ACCOUNT = "123456789012";
@@ -261,6 +264,95 @@ class RdsEndpointAddressesTest {
assertFalse(addresses.serving(instance));
}
@Test
void aClusterNameResolvesToOneOfItsServedInstancesAtRandom() {
DbInstance first = served("db1", 7001);
DbInstance second = served("db2", 7002);
addresses.stop(served("db3", 7003));
String name = AwsEndpoints.rdsClusterEndpointHost("reports", "cluster-custom", ACCOUNT, REGION);
addresses.route("cluster-1", Map.of(name, clusterName("cluster-1", List.of("db1", "db2", "db3"), List.of())));
Set<String> answers = new HashSet<>();
for (int i = 0; i < 200; i++) {
answers.add(addresses.addressOf(name.toUpperCase()).orElseThrow());
}
assertEquals(Set.of(first.getVpcEndpointAddress(), second.getVpcEndpointAddress()), answers);
assertTrue(addresses.names(name));
}
@Test
void aClusterNameWithNoInstanceServedResolvesToTheOtherwiseInstances() {
DbInstance writer = served("writer", 7001);
String reader = AwsEndpoints.rdsClusterEndpointHost("orders", "cluster-ro", ACCOUNT, REGION);
addresses.route("cluster-1", Map.of(reader, clusterName("cluster-1", List.of("gone"), List.of("writer"))));
assertEquals(Optional.of(writer.getVpcEndpointAddress()), addresses.addressOf(reader));
addresses.route("cluster-1", Map.of(reader, clusterName("cluster-1", List.of(), List.of())));
assertTrue(addresses.names(reader));
assertEquals(Optional.empty(), addresses.addressOf(reader));
}
@Test
void routingAClusterAgainReplacesItsNamesAndLeavesOtherClustersAlone() {
String reports = AwsEndpoints.rdsClusterEndpointHost("reports", "cluster-custom", ACCOUNT, REGION);
String writer = AwsEndpoints.rdsClusterEndpointHost("orders", "cluster", ACCOUNT, REGION);
String other = AwsEndpoints.rdsClusterEndpointHost("other", "cluster", ACCOUNT, REGION);
addresses.route("cluster-1", Map.of(reports, clusterName("cluster-1", List.of(), List.of()),
writer, clusterName("cluster-1", List.of(), List.of())));
addresses.route("cluster-2", Map.of(other, clusterName("cluster-2", List.of(), List.of())));
addresses.route("cluster-1", Map.of(writer, clusterName("cluster-1", List.of(), List.of())));
assertFalse(addresses.names(reports));
assertTrue(addresses.namesCluster("cluster-1", writer.toUpperCase()));
assertFalse(addresses.namesCluster("cluster-2", writer));
assertTrue(addresses.namesCluster("cluster-2", other));
addresses.forgetCluster("cluster-1");
assertFalse(addresses.names(writer));
assertTrue(addresses.names(other));
addresses.clear();
assertFalse(addresses.names(other));
}
@Test
void aClusterIsInItsVpcWithASubnetAndEndpointsInTheirVpc() {
DbCluster cluster = new DbCluster();
cluster.setDbClusterIdentifier("Orders");
cluster.setEngine(DatabaseEngine.MYSQL);
cluster.setSubnetAvailabilityZones(new LinkedHashMap<>(Map.of("subnet-a", "us-east-1a")));
assertTrue(addresses.inVpc(cluster));
assertEquals(new DbEndpoint(AwsEndpoints.rdsClusterEndpointHost("orders", "cluster", ACCOUNT, REGION), 3306),
RdsEndpointAddresses.clusterEndpoint(cluster, ACCOUNT, REGION));
cluster.setRequestedPort(6000);
assertEquals(new DbEndpoint(AwsEndpoints.rdsClusterEndpointHost("orders", "cluster-ro", ACCOUNT, REGION), 6000),
RdsEndpointAddresses.readerEndpoint(cluster, ACCOUNT, REGION));
when(config.services().rds().endpointsInVpc()).thenReturn(false);
assertFalse(addresses.inVpc(cluster));
when(config.services().rds().endpointsInVpc()).thenReturn(true);
cluster.setSubnetAvailabilityZones(new LinkedHashMap<>());
assertFalse(addresses.inVpc(cluster));
}
/** An instance served at its own address, with its name known. */
private DbInstance served(String id, int proxyPort) {
DbInstance instance = instance(id, "us-east-1a", null);
addresses.assign(instance);
addresses.serve(instance, ACCOUNT, REGION, proxyPort);
return instance;
}
private static RdsEndpointAddresses.ClusterName clusterName(String clusterResourceId, List<String> instances,
List<String> otherwise) {
return new RdsEndpointAddresses.ClusterName(clusterResourceId,
instances.stream().map(id -> AwsEndpoints.rdsInstanceHost(id, ACCOUNT, REGION)).toList(),
otherwise.stream().map(id -> AwsEndpoints.rdsInstanceHost(id, ACCOUNT, REGION)).toList());
}
private static DbInstance instance(String id, String availabilityZone, Integer requestedPort) {
DbInstance instance = new DbInstance(id, DatabaseEngine.POSTGRES, "16.3", "admin", "secret", "app",
"db.t3.micro", 20, DbInstanceStatus.AVAILABLE, null, false, null, null, Instant.now(), 7001);
@@ -12,17 +12,22 @@ import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DBCluster;
import software.amazon.awssdk.services.rds.model.DBInstance;
import java.time.Duration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -37,13 +42,16 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
* its subnet under the endpoint name RDS gives it, which Floci's DNS server answers with that address. A client on the
* VPC's Docker network, the stand-in for a container in the same VPC, signs in through each address and sees each
* database's own data. A stopped instance's name has no address, and a started one is served again at the address it
* had.
* had. A real Aurora PostgreSQL cluster's instances serve its port the same way, and its cluster endpoint name
* resolves to the writer, before and after a failover, and its reader endpoint name to the reader.
*
* <p>A Docker end-to-end check: it runs real database and relay containers. The client connects by address, as
* Floci's DNS server is not reachable from containers on every runner.
* Floci's DNS server is not reachable from containers on every runner. The tests share the default VPC, whose Docker
* network goes once they have all run.
*/
@QuarkusTest
@TestProfile(RdsEndpointsInVpcDockerNightlyIntegrationTest.Profile.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
@Timeout(value = 10, unit = TimeUnit.MINUTES)
class RdsEndpointsInVpcDockerNightlyIntegrationTest {
@@ -77,6 +85,9 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest {
@Inject
VpcNetworkManager vpcNetworkManager;
/** The VPCs the tests served endpoints in, whose Docker networks go after the last test. */
private final Set<String> vpcIds = new LinkedHashSet<>();
@BeforeEach
void requireDocker() {
assumeTrue(DockerAvailability.answers(dockerClient), "Docker must be available for the endpoints-in-VPC check");
@@ -87,13 +98,13 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest {
String first = "vpc-one-" + UUID.randomUUID().toString().substring(0, 8);
String second = "vpc-two-" + UUID.randomUUID().toString().substring(0, 8);
String client = null;
String vpcId = null;
try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), ACCOUNT, Region.US_EAST_1)) {
try {
for (String id : List.of(first, second)) {
rds.createDBInstance(r -> r.dbInstanceIdentifier(id).engine("postgres").engineVersion("16.3")
.masterUsername("admin").masterUserPassword(PASSWORD).dbName("appdb")
.dbInstanceClass("db.t3.micro").allocatedStorage(20).port(5432));
vpcIds.add(rdsService.getDbInstance(id).getVpcId());
}
String firstName = AwsEndpoints.rdsInstanceHost(first, ACCOUNT, REGION);
String secondName = AwsEndpoints.rdsInstanceHost(second, ACCOUNT, REGION);
@@ -107,7 +118,7 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest {
String secondAddress = address(secondName);
assertNotEquals(firstAddress, secondAddress);
vpcId = rdsService.getDbInstance(first).getVpcId();
String vpcId = rdsService.getDbInstance(first).getVpcId();
String network = vpcNetworkManager.networkNameFor(ACCOUNT, REGION, vpcId).orElseThrow();
String image = dockerClient.inspectContainerCmd(rdsService.getDbInstance(first).getContainerId())
.exec().getConfig().getImage();
@@ -143,9 +154,83 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest {
if (client != null) {
dockerClient.removeContainerCmd(client).withForce(true).exec();
}
if (vpcId != null) {
vpcNetworkManager.deleteVpcNetwork(ACCOUNT, REGION, vpcId);
}
}
@Test
void aClustersNamesResolveToItsInstancesWhichServeItsPort() throws Exception {
String clusterId = "vpc-cluster-" + UUID.randomUUID().toString().substring(0, 8);
String writer = clusterId + "-1";
String reader = clusterId + "-2";
String client = null;
try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), ACCOUNT, Region.US_EAST_1)) {
try {
rds.createDBCluster(r -> r.dbClusterIdentifier(clusterId).engine("aurora-postgresql")
.engineVersion("16.3").masterUsername("admin").masterUserPassword(PASSWORD)
.databaseName("appdb").port(5432));
vpcIds.add(rdsService.getDbCluster(clusterId).getVpcId());
for (String id : List.of(writer, reader)) {
rds.createDBInstance(r -> r.dbInstanceIdentifier(id).dbClusterIdentifier(clusterId)
.engine("aurora-postgresql").dbInstanceClass("db.r6g.large"));
}
String clusterName = AwsEndpoints.rdsClusterEndpointHost(clusterId, "cluster", ACCOUNT, REGION);
String readerName = AwsEndpoints.rdsClusterEndpointHost(clusterId, "cluster-ro", ACCOUNT, REGION);
DBCluster described = rds.describeDBClusters(r -> r.dbClusterIdentifier(clusterId)).dbClusters()
.getFirst();
assertEquals(clusterName, described.endpoint());
assertEquals(readerName, described.readerEndpoint());
assertEquals(5432, described.port());
String writerAddress = address(AwsEndpoints.rdsInstanceHost(writer, ACCOUNT, REGION));
String readerAddress = address(AwsEndpoints.rdsInstanceHost(reader, ACCOUNT, REGION));
assertNotEquals(writerAddress, readerAddress);
assertEquals(writerAddress, address(clusterName));
assertEquals(readerAddress, address(readerName));
String vpcId = rdsService.getDbCluster(clusterId).getVpcId();
String network = vpcNetworkManager.networkNameFor(ACCOUNT, REGION, vpcId).orElseThrow();
String image = dockerClient.inspectContainerCmd(rdsService.getDbCluster(clusterId).getContainerId())
.exec().getConfig().getImage();
client = dockerClient.createContainerCmd(image)
.withEntrypoint("sleep")
.withCmd("600")
.withHostConfig(HostConfig.newHostConfig().withNetworkMode(network))
.exec().getId();
dockerClient.startContainerCmd(client).exec();
assertEquals("written", psql(client, address(clusterName),
"CREATE TABLE IF NOT EXISTS marker(v text PRIMARY KEY); "
+ "INSERT INTO marker VALUES ('written') ON CONFLICT DO NOTHING; SELECT v FROM marker;"));
assertEquals("written", psql(client, address(readerName), "SELECT v FROM marker;"));
rds.failoverDBCluster(r -> r.dbClusterIdentifier(clusterId).targetDBInstanceIdentifier(reader));
assertEquals(readerAddress, address(clusterName));
assertEquals(writerAddress, address(readerName));
assertEquals("written", psql(client, address(clusterName), "SELECT v FROM marker;"));
} finally {
for (String id : List.of(writer, reader)) {
try {
rds.deleteDBInstance(r -> r.dbInstanceIdentifier(id).skipFinalSnapshot(true));
} catch (RuntimeException ignored) {
// Not created, or already gone: nothing of it is left to remove.
}
}
try {
rds.deleteDBCluster(r -> r.dbClusterIdentifier(clusterId).skipFinalSnapshot(true));
} catch (RuntimeException ignored) {
// Not created, or already gone.
}
}
} finally {
if (client != null) {
dockerClient.removeContainerCmd(client).withForce(true).exec();
}
}
}
@AfterAll
void removeVpcNetworks() {
for (String vpcId : vpcIds) {
vpcNetworkManager.deleteVpcNetwork(ACCOUNT, REGION, vpcId);
}
}
@@ -15,6 +15,8 @@ import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.rds.container.RdsContainerHandle;
import io.floci.aws.services.rds.container.RdsContainerManager;
import io.floci.aws.services.rds.model.BlueGreenDeployment;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbClusterEndpoint;
import io.floci.aws.services.rds.model.DbEndpoint;
import io.floci.aws.services.rds.model.DbInstance;
import io.floci.aws.services.rds.model.DbInstanceSettings;
@@ -28,6 +30,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -59,7 +62,8 @@ import static org.mockito.Mockito.when;
/**
* With {@code endpoints-in-vpc} on, a standalone instance serves the Port it was created with at its own address in
* its subnet, under the name RDS gives it, through every step of its life; the relay is a real
* its subnet, under the name RDS gives it, through every step of its life, and a cluster's instances serve the
* cluster's port the same way, its endpoint names resolving to them; the relay is a real
* {@link io.floci.aws.services.ec2.VpcAddressRelays} over a mocked EC2 and Docker.
*/
@ResourceLock(ParallelLocks.PORTS)
@@ -82,6 +86,7 @@ class RdsEndpointsInVpcTest {
private DockerHostResolver hostResolver;
private RdsEndpointAddresses endpointAddresses;
private StorageBackend<String, DbInstance> instances;
private StorageBackend<String, DbCluster> clusters;
private RdsService rdsService;
@BeforeEach
@@ -120,6 +125,7 @@ class RdsEndpointsInVpcTest {
when(hostResolver.resolveOn(any())).thenReturn("host.docker.internal");
endpointAddresses = newEndpointAddresses();
instances = new FailingStore();
clusters = new InMemoryStorage<>();
rdsService = newService(instances);
}
@@ -887,6 +893,427 @@ class RdsEndpointsInVpcTest {
any(), any(), any());
}
@Test
void aClustersInstanceServesTheClustersPortAtItsOwnAddressUnderItsName() {
DbCluster cluster = createCluster("orders", 6000);
// The API reference: an Aurora instance's port "is managed by the cluster".
DbInstance writer = createMember("orders-1", "orders", 3306);
String name = AwsEndpoints.rdsInstanceHost("orders-1", ACCOUNT, REGION);
assertEquals(new DbEndpoint(name, 6000), writer.getEndpoint());
assertEquals("10.0.1.20", writer.getVpcEndpointAddress());
assertEquals(new DbEndpoint(clusterHost("orders", "cluster"), 6000), cluster.getEndpoint());
assertEquals(new DbEndpoint(clusterHost("orders", "cluster-ro"), 6000), cluster.getReaderEndpoint());
assertEquals(6000, rdsService.connectablePort(cluster));
verify(fixture.builder).withCmd(List.of("TCP-LISTEN:6000,fork,reuseaddr,nodelay,backlog=4096",
"TCP:host.docker.internal:" + writer.getProxyPort() + ",nodelay"));
assertNotEquals(cluster.getProxyPort(), writer.getProxyPort());
assertEquals(Optional.of("10.0.1.20"), endpointAddresses.addressOf(name));
}
@Test
void aClusterCreatedWithoutAPortHasItsInstancesServeTheEnginesDefault() {
createCluster("orders", null);
assertEquals(5432, createMember("orders-1", "orders", null).getEndpoint().port());
assertEquals(5432, rdsService.getDbCluster("orders").getEndpoint().port());
}
@Test
void twoClustersBothServe5432EachInstanceAtItsOwnAddress() {
createCluster("first", 5432);
createCluster("second", 5432);
DbInstance first = createMember("first-1", "first", null);
DbInstance second = createMember("second-1", "second", null);
assertEquals(5432, first.getEndpoint().port());
assertEquals(5432, second.getEndpoint().port());
assertNotEquals(first.getVpcEndpointAddress(), second.getVpcEndpointAddress());
assertEquals(Optional.of(first.getVpcEndpointAddress()),
endpointAddresses.addressOf(clusterHost("first", "cluster")));
assertEquals(Optional.of(second.getVpcEndpointAddress()),
endpointAddresses.addressOf(clusterHost("second", "cluster")));
}
@Test
void twoClustersBothServeAPortInTheProxyRange() {
DbCluster first = createCluster("first", 7050);
DbCluster second = createCluster("second", 7050);
assertEquals(7050, first.getEndpoint().port());
assertEquals(7050, second.getEndpoint().port());
assertNotEquals(first.getProxyPort(), second.getProxyPort());
}
@Test
void aStoppedClusterKeepsItsNamesAcrossARestartAndLeavesItsVpcWithTheSetting() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
rdsService.stopDbCluster("orders", REGION);
RdsEndpointAddresses restarted = newEndpointAddresses();
RdsService service = newService(instances, restarted);
service.restorePersistedRuntime();
assertEquals(clusterHost("orders", "cluster"), service.getDbCluster("orders").getEndpoint().address());
assertTrue(restarted.names(clusterHost("orders", "cluster")));
assertEquals(Optional.empty(), restarted.addressOf(clusterHost("orders", "cluster")));
when(config.services().rds().endpointsInVpc()).thenReturn(false);
RdsEndpointAddresses off = newEndpointAddresses();
RdsService offService = newService(instances, off);
offService.restorePersistedRuntime();
DbCluster cluster = offService.getDbCluster("orders");
assertEquals("localhost", cluster.getEndpoint().address());
assertEquals(cluster.getEndpoint(), cluster.getReaderEndpoint());
assertFalse(RdsEndpointAddresses.inVpc(offService.getDbInstance(writer.getDbInstanceIdentifier())));
}
@Test
void theClusterEndpointResolvesToTheWriterAndFollowsAFailover() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
DbInstance reader = createMember("orders-2", "orders", null);
String clusterName = clusterHost("orders", "cluster");
String readerName = clusterHost("orders", "cluster-ro");
assertEquals(Optional.of(writer.getVpcEndpointAddress()), endpointAddresses.addressOf(clusterName));
for (int i = 0; i < 20; i++) {
assertEquals(Optional.of(reader.getVpcEndpointAddress()), endpointAddresses.addressOf(readerName));
}
rdsService.failoverDbCluster("orders", "orders-2", REGION);
assertEquals(Optional.of(reader.getVpcEndpointAddress()), endpointAddresses.addressOf(clusterName));
assertEquals(Optional.of(writer.getVpcEndpointAddress()), endpointAddresses.addressOf(readerName));
}
@Test
void theReaderEndpointResolvesToTheWriterOfAClusterWithNoOtherInstance() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
assertEquals(Optional.of(writer.getVpcEndpointAddress()),
endpointAddresses.addressOf(clusterHost("orders", "cluster-ro")));
}
@Test
void aClusterWithNoInstanceHasItsNamesKnownWithNoAddress() {
createCluster("orders", 5432);
assertTrue(endpointAddresses.names(clusterHost("orders", "cluster")));
assertTrue(endpointAddresses.names(clusterHost("orders", "cluster-ro")));
assertEquals(Optional.empty(), endpointAddresses.addressOf(clusterHost("orders", "cluster")));
assertEquals(Optional.empty(), endpointAddresses.addressOf(clusterHost("orders", "cluster-ro")));
}
@Test
void aCustomEndpointHasItsOwnNameAndResolvesToTheInstancesItHolds() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
DbInstance first = createMember("orders-2", "orders", null);
DbInstance second = createMember("orders-3", "orders", null);
DbClusterEndpoint reports = rdsService.createDbClusterEndpoint(REGION, "orders", "reports", "ANY",
List.of("orders-2"), null, Map.of());
rdsService.createDbClusterEndpoint(REGION, "orders", "readers", "READER", null, List.of("orders-2"), Map.of());
rdsService.createDbClusterEndpoint(REGION, "orders", "all", "ANY", null, List.of("orders-3"), Map.of());
String reportsName = AwsEndpoints.rdsClusterEndpointHost("reports", "cluster-custom", ACCOUNT, REGION);
assertEquals(reportsName, reports.getEndpoint());
assertEquals(reportsName, rdsService.describeDbClusterEndpoints(REGION, "orders", "reports", null, null, null)
.endpoints().get(0).getEndpoint());
assertEquals(Optional.of(first.getVpcEndpointAddress()), endpointAddresses.addressOf(reportsName));
// A READER endpoint leaves out the writer; an exclusion list holds every other instance.
assertEquals(Optional.of(second.getVpcEndpointAddress()), endpointAddresses.addressOf(
AwsEndpoints.rdsClusterEndpointHost("readers", "cluster-custom", ACCOUNT, REGION)));
String allName = AwsEndpoints.rdsClusterEndpointHost("all", "cluster-custom", ACCOUNT, REGION);
for (int i = 0; i < 20; i++) {
assertTrue(List.of(writer.getVpcEndpointAddress(), first.getVpcEndpointAddress())
.contains(endpointAddresses.addressOf(allName).orElseThrow()));
}
rdsService.modifyDbClusterEndpoint(REGION, "reports", null, List.of("orders-3"), null);
assertEquals(Optional.of(second.getVpcEndpointAddress()), endpointAddresses.addressOf(reportsName));
rdsService.deleteDbClusterEndpoint(REGION, "reports");
assertFalse(endpointAddresses.names(reportsName));
}
@Test
void aStaticCustomEndpointWhoseMembersAreAllDeletedResolvesToNoAddress() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
createMember("orders-2", "orders", null);
rdsService.createDbClusterEndpoint(REGION, "orders", "reports", "ANY", List.of("orders-2"), null, Map.of());
rdsService.createDbClusterEndpoint(REGION, "orders", "everyone", "ANY", null, null, Map.of());
String reportsName = AwsEndpoints.rdsClusterEndpointHost("reports", "cluster-custom", ACCOUNT, REGION);
rdsService.deleteDbInstance("orders-2", REGION);
assertTrue(endpointAddresses.names(reportsName));
assertEquals(Optional.empty(), endpointAddresses.addressOf(reportsName));
// One created with neither list holds every instance.
assertEquals(Optional.of(writer.getVpcEndpointAddress()), endpointAddresses.addressOf(
AwsEndpoints.rdsClusterEndpointHost("everyone", "cluster-custom", ACCOUNT, REGION)));
rdsService.modifyDbClusterEndpoint(REGION, "reports", null, null, List.of());
assertEquals(Optional.of(writer.getVpcEndpointAddress()), endpointAddresses.addressOf(reportsName));
}
@Test
void aCustomEndpointStoredBeforeItsKindWasRecordedHoldsOnlyWhatItsListsSay() {
List<String> members = List.of("writer", "first", "second");
DbClusterEndpoint emptied = new DbClusterEndpoint();
emptied.setCustomEndpointType("ANY");
DbClusterEndpoint excluding = new DbClusterEndpoint();
excluding.setCustomEndpointType("ANY");
excluding.setExcludedMembers(new ArrayList<>(List.of("first")));
DbClusterEndpoint listing = new DbClusterEndpoint();
listing.setCustomEndpointType("READER");
listing.setStaticMembers(new ArrayList<>(List.of("writer", "second")));
assertEquals(List.of(), RdsService.customEndpointMembers(emptied, members, "writer"));
assertEquals(List.of("writer", "second"), RdsService.customEndpointMembers(excluding, members, "writer"));
assertEquals(List.of("second"), RdsService.customEndpointMembers(listing, members, "writer"));
}
@Test
void aMultiAzOrServerlessV1ClusterKeepsTheProxyEndpoint() {
DbCluster multiAz = rdsService.createDbCluster("multi-az", "postgres", "16.3", "admin", "password", "app",
false, null, null, null, false, REGION, null, null, null, false, null, null, false, 7050);
DbCluster serverless = rdsService.createDbCluster("serverless", "aurora-mysql", "8.0", "admin", "password",
"app", false, null, null, null, false, REGION, null, null, null, false, null, "serverless", false,
null);
for (DbCluster cluster : List.of(multiAz, serverless)) {
assertEquals("localhost", cluster.getEndpoint().address());
assertFalse(endpointAddresses.names(clusterHost(cluster.getDbClusterIdentifier(), "cluster")));
}
// A Port in the proxy range is the proxy port, as it is with the setting off.
assertEquals(7050, multiAz.getProxyPort());
DbInstance member = createMember("serverless-1", "serverless", 7060);
assertFalse(RdsEndpointAddresses.inVpc(member));
assertEquals(7060, member.getProxyPort());
}
@Test
void aTokenGeneratedForAnyOfAClustersNamesIsGoodAtItsInstances() {
createCluster("orders", 5432);
createCluster("other", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
rdsService.createDbClusterEndpoint(REGION, "orders", "reports", "ANY", null, null, Map.of());
ArgumentCaptor<RdsProxyBinding> binding = ArgumentCaptor.forClass(RdsProxyBinding.class);
verify(proxyManager).startProxy(any(), any(), any(), anyBoolean(), eq(writer.getProxyPort()), any(),
anyInt(), eq(writer.getEndpoint().address()), any(), any(), any(), any(), binding.capture());
assertEquals(5432, binding.getValue().publishedPort());
assertTrue(binding.getValue().acceptsHost(writer.getEndpoint().address()));
assertTrue(binding.getValue().acceptsHost(clusterHost("orders", "cluster").toUpperCase()));
assertTrue(binding.getValue().acceptsHost(clusterHost("orders", "cluster-ro")));
assertTrue(binding.getValue().acceptsHost(
AwsEndpoints.rdsClusterEndpointHost("reports", "cluster-custom", ACCOUNT, REGION)));
assertFalse(binding.getValue().acceptsHost(clusterHost("other", "cluster")));
verify(proxyManager, atLeastOnce()).coverTlsHost(clusterHost("orders", "cluster-ro"));
}
@Test
void stoppingAClusterRemovesItsInstancesRelaysAndStartingServesThemAgain() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
String address = writer.getVpcEndpointAddress();
rdsService.stopDbCluster("orders", REGION);
assertTrue(fixture.present.isEmpty());
assertEquals(Optional.empty(), endpointAddresses.addressOf(clusterHost("orders", "cluster")));
assertTrue(endpointAddresses.names(clusterHost("orders", "cluster")));
rdsService.startDbCluster("orders", REGION);
assertEquals(1, fixture.present.size());
assertEquals(Optional.of(address), endpointAddresses.addressOf(clusterHost("orders", "cluster")));
}
@Test
void deletingAnInstanceDropsItFromTheNamesAndDeletingTheClusterForgetsThem() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
DbInstance reader = createMember("orders-2", "orders", null);
rdsService.deleteDbInstance("orders-1", REGION);
assertFalse(fixture.present.contains("relay-1"));
assertFalse(endpointAddresses.names(writer.getEndpoint().address()));
// The remaining instance is the writer now.
assertEquals(Optional.of(reader.getVpcEndpointAddress()),
endpointAddresses.addressOf(clusterHost("orders", "cluster")));
rdsService.deleteDbInstance("orders-2", REGION);
rdsService.deleteDbCluster("orders", REGION);
assertTrue(fixture.present.isEmpty());
assertFalse(endpointAddresses.names(clusterHost("orders", "cluster")));
assertFalse(endpointAddresses.names(clusterHost("orders", "cluster-ro")));
}
@Test
void anInstanceWhoseCreateFailsLeavesNoNameBehind() {
createCluster("orders", 5432);
((FailingStore) instances).failNextAvailableWrite = true;
assertThrows(RuntimeException.class, () -> createMember("orders-1", "orders", null));
assertFalse(endpointAddresses.names(AwsEndpoints.rdsInstanceHost("orders-1", ACCOUNT, REGION)));
assertTrue(fixture.present.isEmpty());
assertTrue(rdsService.getDbCluster("orders").getDbClusterMembers().isEmpty());
assertEquals(Optional.empty(), endpointAddresses.addressOf(clusterHost("orders", "cluster")));
}
@Test
void aClusterInItsVpcIsConnectableOnThePortItReportsWhateverAdvertiseRequestedPortSays() {
when(config.services().rds().advertiseRequestedPort()).thenReturn(true);
DbCluster cluster = createCluster("orders", 6000);
assertEquals(6000, rdsService.connectablePort(cluster));
assertEquals(clusterHost("orders", "cluster"), cluster.getEndpoint().address());
}
@Test
void anInstanceOfAClusterWithNoDatabaseYetHasItsNameKnownWithNoAddress() {
when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(null);
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
assertTrue(endpointAddresses.names(writer.getEndpoint().address()));
assertEquals(Optional.empty(), endpointAddresses.addressOf(writer.getEndpoint().address()));
assertTrue(fixture.present.isEmpty());
}
@Test
void anInstanceWhoseFailedCreateLeavesItsRelayIsNoLongerBehindTheClustersNames() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
((FailingStore) instances).failNextAvailableWrite = true;
doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager)
.removeIfExistsStrict("relay-2");
assertThrows(RuntimeException.class, () -> createMember("orders-2", "orders", null));
assertTrue(fixture.present.contains("relay-2"));
for (int i = 0; i < 20; i++) {
assertEquals(Optional.of(writer.getVpcEndpointAddress()),
endpointAddresses.addressOf(clusterHost("orders", "cluster-ro")));
}
}
@Test
void aRestartServesAClustersInstancesAndNamesAgain() {
createCluster("orders", 5432);
DbInstance writer = createMember("orders-1", "orders", null);
String address = writer.getVpcEndpointAddress();
endpointAddresses.stopManagedContainers();
RdsEndpointAddresses restarted = newEndpointAddresses();
newService(instances, restarted).restorePersistedRuntime();
assertEquals(Optional.of(address), restarted.addressOf(clusterHost("orders", "cluster")));
assertEquals(Optional.of(address), restarted.addressOf(clusterHost("orders", "cluster-ro")));
assertEquals(Optional.of(address), restarted.addressOf(writer.getEndpoint().address()));
}
@Test
void aRestartWithTheSettingOffTakesAClusterOutOfItsVpc() {
createCluster("orders", 5432);
createMember("orders-1", "orders", null);
endpointAddresses.stopManagedContainers();
when(config.services().rds().endpointsInVpc()).thenReturn(false);
RdsEndpointAddresses restarted = newEndpointAddresses();
RdsService service = newService(instances, restarted);
service.restorePersistedRuntime();
DbCluster cluster = service.getDbCluster("orders");
DbInstance member = service.getDbInstance("orders-1");
assertEquals("localhost", cluster.getEndpoint().address());
assertEquals(cluster.getEndpoint(), cluster.getReaderEndpoint());
assertEquals(cluster.getProxyPort(), cluster.getEndpoint().port());
assertFalse(RdsEndpointAddresses.inVpc(member));
assertEquals("localhost", member.getEndpoint().address());
}
@Test
void aRestartWithTheSettingOnPutsAClusterInItsVpcWithItsInstancesOnItsPort() {
when(config.services().rds().endpointsInVpc()).thenReturn(false);
createCluster("orders", 6000);
createMember("orders-1", "orders", 3306);
createCluster("archive", 5432);
rdsService.stopDbCluster("archive", REGION);
when(config.services().rds().endpointsInVpc()).thenReturn(true);
RdsEndpointAddresses restarted = newEndpointAddresses();
RdsService service = newService(instances, restarted);
service.restorePersistedRuntime();
DbInstance member = service.getDbInstance("orders-1");
assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("orders-1", ACCOUNT, REGION), 6000),
member.getEndpoint());
assertEquals(Optional.of(member.getVpcEndpointAddress()),
restarted.addressOf(clusterHost("orders", "cluster")));
assertEquals(new DbEndpoint(clusterHost("orders", "cluster"), 6000),
service.getDbCluster("orders").getEndpoint());
assertEquals(new DbEndpoint(clusterHost("archive", "cluster-ro"), 5432),
service.getDbCluster("archive").getReaderEndpoint());
assertTrue(restarted.names(clusterHost("archive", "cluster")));
}
@Test
void aMultiAzClusterRestoredFromASnapshotTakesAFreeProxyPortWhileItsOriginalHoldsItsOwn() {
DbCluster original = rdsService.createDbCluster("multi-az", "postgres", "16.3", "admin", "password", "app",
false, null, null, null, false, REGION, null, null, null, false, null, null, false, 7050);
when(containerManager.createPostgresSnapshot(any(), any())).thenReturn("DUMP");
rdsService.createDbClusterSnapshot("multi-az-snap", "multi-az", Map.of(), REGION);
DbCluster restored = rdsService.restoreDbClusterFromSnapshot("multi-az-copy", "multi-az-snap", "postgres",
null, null, null, null, null, null, null, null, false, Map.of(), REGION);
assertEquals(7050, original.getProxyPort());
assertNotEquals(7050, restored.getProxyPort());
assertEquals("localhost", restored.getEndpoint().address());
}
@Test
void aClusterRestoredFromASnapshotServesItsOriginalsPort() {
createCluster("orders", 6000);
when(containerManager.createPostgresSnapshot(any(), any())).thenReturn("DUMP");
rdsService.createDbClusterSnapshot("orders-snap", "orders", Map.of(), REGION);
DbCluster restored = rdsService.restoreDbClusterFromSnapshot("orders-copy", "orders-snap",
"aurora-postgresql", null, null, null, null, null, null, null, null, false, Map.of(), REGION);
assertEquals(new DbEndpoint(clusterHost("orders-copy", "cluster"), 6000), restored.getEndpoint());
}
private DbCluster createCluster(String id, Integer port) {
return rdsService.createDbCluster(id, "aurora-postgresql", "16.3", "admin", "password", "app", false, null,
null, null, false, REGION, null, null, null, false, null, null, false, port);
}
private DbInstance createMember(String id, String clusterId, Integer port) {
return rdsService.createDbInstance(id, "aurora-postgresql", "16.3", null, null, "app", "db.r6g.large", 20,
false, null, null, clusterId, null, false, false, null, Map.of(), List.of(), null, null, true,
DbInstanceSettings.defaults(), null, port);
}
private static String clusterHost(String clusterId, String type) {
return AwsEndpoints.rdsClusterEndpointHost(clusterId, type, ACCOUNT, REGION);
}
private DbInstance create(String id, String engine, Integer port) {
return rdsService.createDbInstance(id, engine, "mysql".equals(engine) ? "8.0.36" : "16.3", "admin", "password", "app", "db.t3.micro", 20, false,
null, null, null, null, false, false, null, Map.of(), List.of(), null, null, true,
@@ -899,7 +1326,7 @@ class RdsEndpointsInVpcTest {
private RdsService newService(StorageBackend<String, DbInstance> store, RdsEndpointAddresses addresses) {
return new RdsService(containerManager, proxyManager, ec2Service, new RegionResolver(REGION, ACCOUNT),
config, store, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
config, store, clusters, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), null, null, null, addresses);
}
@@ -334,6 +334,24 @@ class RdsSigV4ValidatorTest {
new RdsProxyBinding("db.example.local", 3306, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
}
@Test
void validateAcceptsATokenForAnotherNameTheEndpointIsReachedBy() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String token = SigV4TokenTestHelper.createRdsToken(
"orders.cluster-abcdefghijkl.us-east-1.rds.amazonaws.com", 3307, "admin", "AKIDRDS", "secret-rds",
Instant.now().minusSeconds(60), 900);
assertTrue(validator.validate(token, "admin", new RdsProxyBinding("db.example.local", 3307, "us-east-1",
"123456789012", "db-ABCDEFGHIJKL01234", true,
"orders.cluster-abcdefghijkl.us-east-1.rds.amazonaws.com"::equals)));
assertFalse(validator.validate(token, "admin", new RdsProxyBinding("db.example.local", 3307, "us-east-1",
"123456789012", "db-ABCDEFGHIJKL01234", true, "other.example.local"::equals)));
assertFalse(validator.validate(token, "admin", new RdsProxyBinding("db.example.local", 3306, "us-east-1",
"123456789012", "db-ABCDEFGHIJKL01234", true,
"orders.cluster-abcdefghijkl.us-east-1.rds.amazonaws.com"::equals)));
}
@Test
void validateRejectsTokenSignedForAnotherHost() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");