diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index d077039ad5..51d363bc6f 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -242,6 +242,8 @@ grep -q 'RdsAwsDockerNightlyIntegrationTest' "$SHARD_FILE" && [ -n "$SQLSERVER_I REDSHIFT_PG_IMAGE="$(grep -oE 'image-version: *postgres:[^ ]+' src/main/resources/application.yml | awk '{print $2}')" grep -qE '/redshift/|/cloudformation/' "$SHARD_FILE" && [ -n "$REDSHIFT_PG_IMAGE" ] && pull "$REDSHIFT_PG_IMAGE" grep -qE '/rds/|/rdsdata/' "$SHARD_FILE" && pull postgres:16.3-alpine +# RdsEndpointsInVpcDockerNightlyIntegrationTest serves each instance through a relay on EC2's socat image. +starts RdsEndpointsInVpcDockerNightlyIntegrationTest && configured_image ec2 socat-image # The template-database restore fixture selects its own PostgreSQL image. # Read that override so its first CreateDBInstance does not also have to pull PostGIS. POSTGIS_TEST="$(find src/test/java -name RdsTemplateDatabaseRestoreDockerNightlyIntegrationTest.java -print -quit)" diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index d91603361c..faa6652406 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -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 `.` names and Route 53 private zone records. 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 `.` 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. When Floci runs natively, it starts up to two listeners: @@ -522,6 +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_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 | diff --git a/docs/services/rds.md b/docs/services/rds.md index fb88eab456..7c1d4d0ee9 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -348,6 +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_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 | @@ -374,6 +375,9 @@ 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_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 range, so connect to that port; a restore without `Port` reports the proxy port. With the flag on, IAM @@ -569,6 +573,57 @@ no groups or an instance stored before these defaults, and `sg-00000000` only wh before it changes anything, and a rollback leaves the groups of an instance the update moved to 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: + +- 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 + the default VPC. +- It serves the `Port` it was created with, or its engine's default (5432 for PostgreSQL, 3306 for MySQL and + MariaDB, 1433 for SQL Server), so two instances can both serve 5432, or any other port, the proxy range's + included. Without a `Port` of its own, a snapshot or point in time restore serves its original instance's port, a + read replica its source's, and the green instance of a blue/green deployment its blue instance's, as the API + reference gives those defaults. +- `DescribeDBInstances` reports that port and the name RDS gives the instance, + `...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. +- 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 + Floci there: with Floci in a container, at its address on that network, which Floci is on as RDS's database + containers need it to be. IAM authentication tokens bind to the name and port, + and the managed master-user secret carries them. +- A stop removes the relay and a start serves the instance again at the address it had; a restart of Floci does the + same. A `ModifyDBInstance` that names another `DBSubnetGroupName` serves the instance in a subnet of that group; + a running instance keeps its old address until the new subnet serves it, and keeps it when that subnet has no + address to give, until the next start, restart of Floci or backend retry makes the move. + 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. +- 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 + is confirmed removed, no other database is given the proxy port it forwards to, and one a restart cannot remove + keeps its address and its subnet in use. + +The address is on the VPC's Docker network, so the containers Floci runs in that VPC (EC2 instances, ECS tasks, +Lambda functions, EKS pods) reach it, and so does a host whose container addresses are routable, such as Linux. They +resolve the name through Floci's DNS server. A client that cannot reach the address, such as one on a Docker Desktop +host, still connects through the proxy port, which keeps listening in the proxy range; its IAM token is generated for +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. + +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. + ## Modifying a DB instance `ModifyDBInstance` applies `DBInstanceClass` and `AllocatedStorage`, and diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 8d8e038f89..9d7691ee10 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2134,6 +2134,14 @@ public interface EmulatorConfig { @WithDefault("false") boolean advertiseRequestedPort(); + /** + * 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. + */ + @WithDefault("false") + boolean endpointsInVpc(); + /** Empty when Floci should adapt its built-in image to the requested engine version. */ Optional defaultPostgresImage(); diff --git a/src/main/java/io/floci/aws/core/common/AwsEndpoints.java b/src/main/java/io/floci/aws/core/common/AwsEndpoints.java index 702549d16c..7dca80e10d 100644 --- a/src/main/java/io/floci/aws/core/common/AwsEndpoints.java +++ b/src/main/java/io/floci/aws/core/common/AwsEndpoints.java @@ -1,5 +1,8 @@ package io.floci.aws.core.common; +import java.nio.charset.StandardCharsets; +import java.util.Locale; + /** * The AWS hostnames the emulator hands back for a region: every one is * {@code ..} with the region's partition suffix, plus the handful of @@ -10,6 +13,9 @@ package io.floci.aws.core.common; */ public final class AwsEndpoints { + private static final String RDS_ENDPOINT_IDENTIFIER_CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static final int RDS_ENDPOINT_IDENTIFIER_LENGTH = 12; + private AwsEndpoints() { } @@ -18,6 +24,33 @@ public final class AwsEndpoints { return AwsPartitions.forRegionOrCommercial(region).regionalHostname(service, region); } + /** + * The identifier every RDS endpoint of an account in a region carries, {@code abcdefghijkl} in + * {@code db1.abcdefghijkl.us-east-1.rds.amazonaws.com}. The RDS user guide calls it "a unique identifier + * for a specific combination of AWS Region and AWS account" that "doesn't change" for it, so all of an + * account's DB instances in a region share it. Floci derives its twelve letters and digits from the two, a + * letter first, so it stays the same across restarts without being stored. + */ + public static String rdsEndpointIdentifier(String accountId, String region) { + byte[] digest = Digests.sha256((accountId + ":" + region).getBytes(StandardCharsets.UTF_8)); + StringBuilder identifier = new StringBuilder(RDS_ENDPOINT_IDENTIFIER_LENGTH); + identifier.append(RDS_ENDPOINT_IDENTIFIER_CHARACTERS.charAt(Math.floorMod(digest[0], 26))); + for (int i = 1; i < RDS_ENDPOINT_IDENTIFIER_LENGTH; i++) { + identifier.append(RDS_ENDPOINT_IDENTIFIER_CHARACTERS.charAt( + Math.floorMod(digest[i], RDS_ENDPOINT_IDENTIFIER_CHARACTERS.length()))); + } + return identifier.toString(); + } + + /** + * A DB instance's endpoint address, {@code ...rds.}, with the + * {@link #rdsEndpointIdentifier} of its account and region. + */ + public static String rdsInstanceHost(String dbInstanceIdentifier, String accountId, String region) { + return dbInstanceIdentifier.toLowerCase(Locale.ROOT) + "." + rdsEndpointIdentifier(accountId, region) + "." + + region + ".rds." + AwsRegions.dnsSuffixFor(region); + } + /** {@code .execute-api..}. */ public static String executeApiHost(String apiId, String region) { return apiId + "." + host("execute-api", region); diff --git a/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java b/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java index f17c899ece..ce030625e7 100644 --- a/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java +++ b/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java @@ -59,6 +59,32 @@ public class CurrentContainerNetworkResolver { return resolve().map(CurrentContainerNetwork::ipAddress); } + /** + * Floci's own address on {@code network}, empty when Floci is not in a container, is not on that network or its + * container cannot be inspected. Unlike {@link #resolveContainerIp} it is not cached: Floci joins networks as it + * runs, an EC2 VPC's among them. + */ + public Optional resolveContainerIpOn(String network) { + if (!containerDetector.isRunningInContainer()) { + return Optional.empty(); + } + String containerId = currentContainerId(); + if (containerId.isBlank()) { + return Optional.empty(); + } + try { + Map networks = dockerClient.inspectContainerCmd(containerId).exec() + .getNetworkSettings().getNetworks(); + return Optional.ofNullable(networks == null ? null : networks.get(network)) + .filter(this::isUsable) + .map(ContainerNetwork::getIpAddress); + } catch (Exception e) { + LOG.debugv("Could not inspect current Docker container {0} for its address on {1}: {2}", containerId, + network, e.getMessage()); + return Optional.empty(); + } + } + public OptionalInt resolvePublishedPort(int containerPort) { OptionalInt cachedPublishedPort = cachedPublishedPorts.get(containerPort); if (cachedPublishedPort != null) { diff --git a/src/main/java/io/floci/aws/core/common/docker/DockerHostResolver.java b/src/main/java/io/floci/aws/core/common/docker/DockerHostResolver.java index ece594133a..03eea2be0c 100644 --- a/src/main/java/io/floci/aws/core/common/docker/DockerHostResolver.java +++ b/src/main/java/io/floci/aws/core/common/docker/DockerHostResolver.java @@ -88,6 +88,24 @@ public class DockerHostResolver { return HOST_DOCKER_INTERNAL; } + /** + * The address a container on {@code network} reaches Floci at. Floci in a container answers on every network it is + * on, and Docker isolates one user-defined network from another, so a container on one of them other than the one + * {@link #resolve()} picks reaches Floci only at its address there. Otherwise, and with an override configured, + * the address {@link #resolve()} gives. + */ + public String resolveOn(String network) { + Optional override = config.services().lambda().dockerHostOverride(); + if ((override.isEmpty() || override.get().isBlank()) && currentContainerNetworkResolver != null + && containerDetector.isRunningInContainer()) { + Optional address = currentContainerNetworkResolver.resolveContainerIpOn(network); + if (address.isPresent()) { + return address.get(); + } + } + return resolve(); + } + /** True when the Floci JVM is running natively on a Linux host (not on Docker Desktop). */ public boolean isLinuxHost() { String os = System.getProperty("os.name", "").toLowerCase(); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index e7bc0ad12a..289dbf03f9 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -545,6 +545,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab : vpcNetworkManager.effectiveVpcCidr(accountId, region, vpcId); } + /** + * The IPv4 range a subnet's addresses on its VPC's Docker network come from, which a substituted CIDR makes differ + * from the declared one. + */ + public Optional effectiveSubnetCidr(String accountId, String region, String subnetId) { + return vpcNetworkManager == null ? Optional.empty() + : vpcNetworkManager.effectiveSubnetCidr(accountId, region, subnetId); + } + /** * Re-claims prefixes a persisted container holder leased before a restart, as {@link #reserveVpcPrivateIp} does an * address, skipping one an instance, interface or container holds an address of now. Docker is asked as diff --git a/src/main/java/io/floci/aws/services/ec2/VpcAddressRelays.java b/src/main/java/io/floci/aws/services/ec2/VpcAddressRelays.java new file mode 100644 index 0000000000..71c97cf5fe --- /dev/null +++ b/src/main/java/io/floci/aws/services/ec2/VpcAddressRelays.java @@ -0,0 +1,379 @@ +package io.floci.aws.services.ec2; + +import com.github.dockerjava.api.model.Container; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.core.common.docker.SocatTcpRelay; +import io.quarkus.runtime.annotations.RegisterForReflection; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +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 java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Endpoints served at their own address in a subnet, as an AWS service puts a network interface in a subnet for an + * endpoint of a resource it runs there. A relay container joins the VPC's Docker network at an address EC2 leases + * from the subnet, listens on the endpoint's port and forwards each connection to the Floci listener that serves the + * endpoint, so endpoints in one VPC can share a port, each at its own address. + * + *

A relay holds no state worth keeping: {@link #stopAll} removes every one when Floci stops, and a restart serves + * each endpoint again at the address it held, which the owning service keeps with the endpoint. The relay also + * listens on its address on Floci's own network, which no endpoint reports. The leases, and the subnet and VPC + * dependencies they answer for EC2, are {@link VpcContainerLeases}'. + * + *

Every relay that may exist is written down in its {@link Placements}, from just before it starts until Docker + * confirms it removed, so one Docker leaves behind is never lost: its target port stays taken + * ({@link #targetsPort}), and a restart removes it or, when Docker still does not confirm that, leases its address + * again ({@link #recoverAll}). + */ +public final class VpcAddressRelays { + + private static final Logger LOG = Logger.getLogger(VpcAddressRelays.class); + private static final int LOCK_STRIPES = 64; + + private final VpcContainerLeases leases; + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final EmulatorConfig config; + private final String service; + private final String image; + /** The network the relays share with Floci, or null for Floci's default. */ + private final String network; + private final Placements placements; + /** The relay serving each endpoint, by the endpoint's relay id. */ + private final Map served = new ConcurrentHashMap<>(); + /** Locks by endpoint, striped so they stay bounded: a serve and a stop of one endpoint never interleave. */ + private final Object[] locks = new Object[LOCK_STRIPES]; + + /** + * @param leases leases the relays' addresses + * @param containerBuilder builds the relay containers + * @param lifecycleManager starts and removes them + * @param config names and labels them + * @param service the service whose endpoints they serve, as the {@code io.floci.service} label and the + * first part of a relay's name, such as {@code "rds-endpoint"} + * @param image an image whose entrypoint can be set to {@code socat} + * @param network the network the relays share with Floci, which they reach their targets on, as a + * service's {@code docker-network} setting names it, or null for Floci's default + * @param placements where the relays that may exist are written down, to outlive a restart + */ + public VpcAddressRelays(VpcContainerLeases leases, ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, EmulatorConfig config, String service, + String image, String network, Placements placements) { + this.leases = leases; + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.config = config; + this.service = service; + this.image = image; + this.network = network; + this.placements = placements; + for (int i = 0; i < LOCK_STRIPES; i++) { + locks[i] = new Object(); + } + } + + /** + * One endpoint to serve: its {@code port} at an address of {@code subnetId}, relayed to {@code targetHost} on + * {@code targetPort}. + * + * @param id the endpoint's relay id, unique among the service's endpoints and valid in a Docker name + * @param vpcId the VPC the resource names beside its subnet, or null when it names none + * @param name the endpoint, for the log + */ + @RegisterForReflection + public record Relay(String id, String accountId, String region, String vpcId, String subnetId, int port, + String targetHost, int targetPort, String name) { + } + + /** A relay that may exist, and the address it was given. */ + @RegisterForReflection + public record Placement(Relay relay, String address) { + } + + /** + * Where the relays that may exist are written down. The owning service keeps them in its own storage, so they + * outlive a restart. + */ + public interface Placements { + void put(Placement placement); + + void remove(Placement placement); + + List all(); + + /** Placements kept in memory only, gone with the process. */ + static Placements inMemory() { + Map kept = new ConcurrentHashMap<>(); + return new Placements() { + @Override + public void put(Placement placement) { + kept.put(placement.relay().id(), placement); + } + + @Override + public void remove(Placement placement) { + kept.remove(placement.relay().id(), placement); + } + + @Override + public List all() { + return new ArrayList<>(kept.values()); + } + }; + } + } + + private record Served(Relay relay, String containerId, String address) { + } + + /** + * Serves {@code relay} and returns its address: at {@code preferredAddress}, the address the endpoint held before, + * when the subnet still has it to give, and at the next free one otherwise. A relay already serving the same + * endpoint the same way is kept, and one serving it another way, such as to another target port, is replaced, + * keeping its address when it can. + * + * @throws IllegalStateException when the subnet has no address to give: EC2 does not know it, its VPC has no + * Docker-backed network, or every address is held; or when Docker does not + * confirm the endpoint's earlier relay removed, which stays as it was + */ + public String serve(Relay relay, String preferredAddress) { + synchronized (lock(relay.id())) { + return serveLocked(relay, preferredAddress); + } + } + + private String serveLocked(Relay relay, String preferredAddress) { + Served current = served.get(relay.id()); + if (current != null && current.relay().equals(relay) && running(current.containerId())) { + return current.address(); + } + String wanted = current != null ? current.address() : preferredAddress; + stopLocked(relay.id()); + // Docker refuses a second container under the name, so one it still has, however it came to be, goes. + lifecycleManager.removeIfExistsStrict(containerName(relay.id())); + ContainerSpec spec = containerBuilder.newContainer(image) + .withName(containerName(relay.id())) + .withDockerNetwork(Optional.ofNullable(network)) + .withHostDockerInternalOnLinux() + .withEntrypoint(List.of("socat")) + .withCmd(List.of(SocatTcpRelay.listen(relay.port()), + SocatTcpRelay.connect(relay.targetHost(), relay.targetPort()))) + .withLabels(labels(relay)) + .withLogRotation() + .build(); + AtomicReference joinedContainer = new AtomicReference<>(); + AtomicReference address = new AtomicReference<>(); + try { + String containerId = lifecycleManager.createAndStart(spec, created -> { + VpcContainerLeases.Lease lease = leases.join(relay.accountId(), relay.region(), relay.vpcId(), + relay.subnetId(), created, relay.name(), wanted) + .orElseThrow(() -> new IllegalStateException("Subnet " + relay.subnetId() + + " has no address to serve " + relay.name() + " at")); + joinedContainer.set(created); + address.set(lease.address()); + placements.put(new Placement(relay, lease.address())); + }).containerId(); + served.put(relay.id(), new Served(relay, containerId, address.get())); + LOG.infov("{0} served at {1}:{2,number,#}, relayed to {3}:{4,number,#}", relay.name(), address.get(), + relay.port(), relay.targetHost(), relay.targetPort()); + return address.get(); + } catch (RuntimeException e) { + String joined = joinedContainer.get(); + if (joined != null) { + try { + lifecycleManager.removeIfExistsStrict(joined); + leases.releaseIfGone(joined); + placements.remove(new Placement(relay, address.get())); + } catch (RuntimeException removal) { + // Docker may run the relay all the same: tracked, it keeps its address, its owner keeps what it + // forwards to, and a later stop removes it. + served.put(relay.id(), new Served(relay, joined, address.get())); + e.addSuppressed(removal); + } + } + throw e; + } + } + + /** + * Stops serving the endpoint: its relay is removed, by the container it is and by its name, and its address is + * given back. Nothing happens, and Docker is not asked, for an endpoint no relay serves and none is written down + * for. + * + * @throws IllegalStateException when Docker does not confirm the relay removed: it is still tracked, keeping its + * address, so the caller keeps what the relay forwards to, and a later stop or + * serve tries again + */ + public void stop(String id) { + if (id == null) { + return; + } + synchronized (lock(id)) { + stopLocked(id); + } + } + + private void stopLocked(String id) { + Served current = served.get(id); + List placed = placements.all().stream().filter(placement -> placement.relay().id().equals(id)) + .toList(); + if (current == null && placed.isEmpty()) { + return; + } + try { + if (current != null) { + lifecycleManager.removeIfExistsStrict(current.containerId()); + } + lifecycleManager.removeIfExistsStrict(containerName(id)); + } catch (RuntimeException e) { + throw new IllegalStateException("Docker did not confirm the relay of endpoint " + id + " removed", e); + } + if (current != null) { + served.remove(id, current); + leases.releaseIfGone(current.containerId()); + } + placed.forEach(placements::remove); + } + + /** + * Removes every relay, as Floci stops or resets: a restart serves each endpoint again at the address it held. A + * relay Docker does not confirm removed is logged and stays tracked and written down, which the next start takes + * up ({@link #recoverAll}). + */ + public void stopAll() { + for (String id : List.copyOf(served.keySet())) { + try { + stop(id); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the relay of endpoint {0}", id); + } + } + } + + /** + * As Floci starts, takes up every relay an earlier Floci left. One written down is removed when Docker confirms + * it, and otherwise tracked with its address leased again, so its subnet and VPC stay in use and nothing else is + * given the address, until a later stop or serve removes it; its target port stays taken either way until then. + * One of this Floci's relays Docker still has that is not written down, as a crash before its placement was + * written leaves, holds no address and is removed. + */ + public void recoverAll() { + Set placed = new HashSet<>(); + for (Placement placement : placements.all()) { + String id = placement.relay().id(); + placed.add(id); + synchronized (lock(id)) { + if (served.containsKey(id)) { + continue; + } + String name = containerName(id); + try { + lifecycleManager.removeIfExistsStrict(name); + placements.remove(placement); + } catch (RuntimeException e) { + LOG.warnv(e, "{0} keeps the relay an earlier Floci left, at {1}, until it can be removed", + placement.relay().name(), placement.address()); + leases.reclaim(placement.relay().accountId(), placement.relay().region(), + placement.relay().subnetId(), name, List.of(placement.address()), + placement.relay().name()) + .ifPresent(lease -> served.put(id, new Served(placement.relay(), name, lease.address()))); + } + } + } + for (Container survivor : ownRelays()) { + String id = ContainerStorageHelper.labelValue(survivor.getLabels(), ContainerStorageHelper.RESOURCE_ID_LABEL); + if (id == null || (!placed.contains(id) && !served.containsKey(id))) { + lifecycleManager.removeIfExists(survivor.getId()); + } + } + } + + /** + * Writes down again every relay still tracked, after a reset wiped the service's storage: one Docker did not + * confirm removed as the reset stopped it keeps its target port taken, and the next start takes it up. + */ + public void rewritePlacements() { + for (Served current : List.copyOf(served.values())) { + placements.put(new Placement(current.relay(), current.address())); + } + } + + private List ownRelays() { + try { + return ContainerStorageHelper.CONTAINER_LABEL_ALIASES.listByLabels( + Map.of(ContainerStorageHelper.SERVICE_LABEL, service, + ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)), + filter -> lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) + .withLabelFilter(filter).exec(), + Container::getId); + } catch (RuntimeException e) { + LOG.warnv("Could not list the {0} relays an earlier Floci may have left: {1}", service, e.getMessage()); + return List.of(); + } + } + + /** + * The Docker network a relay joins besides its VPC's: the service's own, else the global one, else Floci's own, as + * {@link ContainerBuilder#resolveDockerNetwork} picks it. A relay reaches its target over this network. + */ + public Optional network() { + return containerBuilder.resolveDockerNetwork(Optional.ofNullable(network)); + } + + /** Whether a relay that may exist forwards to {@code port}, which must then not be given to anything else. */ + public boolean targetsPort(int port) { + return placements.all().stream().anyMatch(placement -> placement.relay().targetPort() == port); + } + + /** The address the endpoint is served at, while a relay serves it. */ + public Optional address(String id) { + Served current = id == null ? null : served.get(id); + return Optional.ofNullable(current == null ? null : current.address()); + } + + /** Whether a relay of the account holds an address in the subnet, as {@link VpcContainerLeases#holdsSubnet}. */ + public boolean holdsSubnet(String accountId, String region, String subnetId) { + return leases.holdsSubnet(accountId, region, subnetId); + } + + /** Whether a relay of the account is on the VPC's network, as {@link VpcContainerLeases#holdsVpc}. */ + public boolean holdsVpc(String accountId, String region, String vpcId) { + return leases.holdsVpc(accountId, region, vpcId); + } + + private Object lock(String id) { + return locks[Math.floorMod(id.hashCode(), LOCK_STRIPES)]; + } + + String containerName(String id) { + return ContainerStorageHelper.dockerName(config, service + "-" + id); + } + + private Map labels(Relay relay) { + Map labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels( + service, relay.id(), relay.accountId(), relay.region())); + labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)); + return labels; + } + + private boolean running(String containerId) { + try { + return Boolean.TRUE.equals(lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec() + .getState().getRunning()); + } catch (RuntimeException e) { + LOG.debugv("Relay container {0} could not be inspected: {1}", containerId, e.getMessage()); + return false; + } + } +} diff --git a/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java b/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java index f91ed68bb7..4f93a7d08c 100644 --- a/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java +++ b/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java @@ -88,6 +88,18 @@ public final class VpcContainerLeases { */ public Optional join(String accountId, String region, String expectedVpcId, String subnetId, String containerId, String name) { + return join(accountId, region, expectedVpcId, subnetId, containerId, name, null); + } + + /** + * {@link #join(String, String, String, String, String, String)} at {@code preferredAddress} when the subnet's + * range holds it and nothing else does, as a restart serves an endpoint at the address it had, and at the next + * free address otherwise. + * + * @param preferredAddress the address to take back, or null for the next free one + */ + public Optional join(String accountId, String region, String expectedVpcId, String subnetId, + String containerId, String name, String preferredAddress) { if (ec2 == null || subnetId == null) { return Optional.empty(); } @@ -102,7 +114,9 @@ public final class VpcContainerLeases { expectedVpcId, subnetId, vpcId); return; } - Optional address = ec2.allocateVpcPrivateIp(accountId, region, subnetId); + Optional address = preferredAddress != null + && ec2.reserveVpcPrivateIp(accountId, region, subnetId, preferredAddress) + ? Optional.of(preferredAddress) : ec2.allocateVpcPrivateIp(accountId, region, subnetId); if (address.isEmpty()) { return; } @@ -140,7 +154,9 @@ public final class VpcContainerLeases { } return RequestScopes.callAs(accountId, region, () -> { List subnets = ec2.describeSubnets(region, List.of(subnetId), Map.of()); - Optional cidr = subnets.size() == 1 ? Cidr4.parse(subnets.getFirst().getCidrBlock()) + // EC2 leases from the range the VPC's Docker network uses, which a substituted CIDR moves off the declared. + Optional cidr = subnets.size() == 1 + ? ec2.effectiveSubnetCidr(accountId, region, subnetId).flatMap(Cidr4::parse) : Optional.empty(); if (cidr.isEmpty()) { return Optional.empty(); diff --git a/src/main/java/io/floci/aws/services/rds/RdsDnsRecordSource.java b/src/main/java/io/floci/aws/services/rds/RdsDnsRecordSource.java new file mode 100644 index 0000000000..a79c8a19cf --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/RdsDnsRecordSource.java @@ -0,0 +1,47 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.core.common.dns.DnsAnswer; +import io.floci.aws.core.common.dns.DnsRecordSource; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.List; +import java.util.Locale; +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 ...rds.} 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. + */ +@ApplicationScoped +public class RdsDnsRecordSource implements DnsRecordSource { + + private final RdsEndpointAddresses endpointAddresses; + + public RdsDnsRecordSource(RdsEndpointAddresses endpointAddresses) { + this.endpointAddresses = endpointAddresses; + } + + @Override + public Optional resolveAuthoritative(String name, int type) { + if (name == null || !name.toLowerCase(Locale.ROOT).contains(".rds.") || !endpointAddresses.enabled()) { + return Optional.empty(); + } + String host = name.endsWith(".") ? name.substring(0, name.length() - 1) : name; + if (!endpointAddresses.names(host)) { + return Optional.empty(); + } + Optional address = endpointAddresses.addressOf(host); + if (type != 1 || address.isEmpty()) { + return Optional.of(DnsAnswer.noData()); + } + return Optional.of(DnsAnswer.records(List.of(address.get()), DnsAnswer.DEFAULT_TTL_SECONDS)); + } + + @Override + public Optional resolveIpv4(String name) { + return Optional.empty(); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java b/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java new file mode 100644 index 0000000000..0fcc9f1146 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java @@ -0,0 +1,316 @@ +package io.floci.aws.services.rds; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsEndpoints; +import io.floci.aws.core.common.ContainerTeardown; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.DockerHostResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +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.DbEndpoint; +import io.floci.aws.services.rds.model.DbInstance; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * DB instance endpoints served in their VPC, with {@code endpoints-in-vpc} on. As RDS places an instance in a subnet + * of its DB subnet group, an instance's endpoint gets its own address in the subnet of its Availability Zone, where it + * serves the Port it was created with, or its engine's default, under the name RDS gives it, + * {@code ...rds.}. A relay at that 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, and two + * instances can both serve 5432. + * + *

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 + * address. + */ +@ApplicationScoped +public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTeardown, Resettable { + + static final String SERVICE = "rds-endpoint"; + private static final Logger LOG = Logger.getLogger(RdsEndpointAddresses.class); + + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final DockerHostResolver dockerHostResolver; + private final VpcAddressRelays relays; + /** + * The relay id of each endpoint name Floci knows, lowercase: Floci's DNS server answers from it, an instance's + * name staying known while it is stopped, until it is deleted or taken out of its VPC. + */ + private final Map relayIdsByHost = new ConcurrentHashMap<>(); + + @Inject + public RdsEndpointAddresses(EmulatorConfig config, Ec2Service ec2Service, RegionResolver regionResolver, + ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, + DockerHostResolver dockerHostResolver, StorageFactory storageFactory) { + this(config, regionResolver, dockerHostResolver, new VpcAddressRelays( + new VpcContainerLeases(ec2Service, "RDS endpoint", lifecycleManager::getDockerClient), + containerBuilder, lifecycleManager, config, SERVICE, config.services().ec2().socatImage(), + config.services().rds().dockerNetwork().orElse(null), + stored(storageFactory.create("rds", "rds-endpoint-relays.json", + new TypeReference>() {})))); + } + + /** The relays that may exist, kept with RDS's records so a restart finds every one. */ + private static VpcAddressRelays.Placements stored(AccountAwareStorageBackend store) { + return new VpcAddressRelays.Placements() { + @Override + public void put(VpcAddressRelays.Placement placement) { + store.putForAccount(placement.relay().accountId(), placement.relay().id(), placement); + } + + @Override + public void remove(VpcAddressRelays.Placement placement) { + store.deleteForAccount(placement.relay().accountId(), placement.relay().id()); + } + + @Override + public List all() { + return store.scanAllAccounts(); + } + }; + } + + RdsEndpointAddresses(EmulatorConfig config, RegionResolver regionResolver, DockerHostResolver dockerHostResolver, + VpcAddressRelays relays) { + this.config = config; + this.regionResolver = regionResolver; + this.dockerHostResolver = dockerHostResolver; + this.relays = relays; + } + + /** Whether new endpoints go in their VPC: the setting on, outside mock mode, with Docker-backed VPC networks. */ + public boolean enabled() { + return config.services().rds().endpointsInVpc() && !config.services().rds().mock() + && config.services().ec2().vpcNetworks().enabled() && !config.services().ec2().mock(); + } + + /** + * Gives a standalone instance an endpoint in its VPC, served in the subnet of its Availability Zone, or the + * first subnet of its DB subnet group when none is in it. False, leaving the instance as it was, when endpoints + * do not go in their VPC or the instance has no subnet. + */ + public boolean assign(DbInstance instance) { + String subnetId = enabled() ? subnetFor(instance) : null; + if (subnetId == null) { + return false; + } + instance.setVpcEndpointId(newRelayId()); + instance.setVpcEndpointSubnetId(subnetId); + instance.setVpcEndpointAddress(null); + return true; + } + + /** A relay id no endpoint has, valid in a Docker name. */ + public static String newRelayId() { + return UUID.randomUUID().toString().replace("-", "").substring(0, 20); + } + + /** + * Stops the relay of an endpoint that has moved on to another relay, as a move to another subnet does once the + * new relay serves. + * + * @throws IllegalStateException when Docker does not confirm the relay removed + */ + public void stopRelay(String relayId) { + relays.stop(relayId); + } + + /** + * Takes an instance's endpoint out of its VPC: its relay goes, and with it the address and the name. + * + * @throws IllegalStateException when Docker does not confirm the relay removed; the instance is left as it was + */ + public void unassign(DbInstance instance) { + forget(instance); + instance.setVpcEndpointId(null); + instance.setVpcEndpointSubnetId(null); + instance.setVpcEndpointAddress(null); + } + + static String subnetFor(DbInstance instance) { + Map subnets = instance.getSubnetAvailabilityZones(); + if (subnets == null || subnets.isEmpty()) { + return null; + } + return subnets.entrySet().stream() + .filter(subnet -> Objects.equals(subnet.getValue(), instance.getAvailabilityZone())) + .map(Map.Entry::getKey) + .findFirst() + .orElse(subnets.keySet().iterator().next()); + } + + /** Whether the instance's endpoint is served in its VPC. */ + public static boolean inVpc(DbInstance instance) { + return instance.getVpcEndpointId() != null; + } + + /** The endpoint an instance in its VPC reports: its RDS name, and the port it serves. */ + public static DbEndpoint endpoint(DbInstance instance, String accountId, String region) { + return new DbEndpoint(AwsEndpoints.rdsInstanceHost(instance.getDbInstanceIdentifier(), accountId, region), + servedPort(instance)); + } + + /** The Port the instance was created with, or its engine's default. */ + public static int servedPort(DbInstance instance) { + return instance.getRequestedPort() != null ? instance.getRequestedPort() : instance.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. + * + * @throws IllegalStateException when the subnet has no address to give, or Docker does not confirm an earlier + * relay of the endpoint removed + */ + public void serve(DbInstance instance, String accountId, String region, int proxyPort) { + removeStaleRelays(instance); + String address = relays.serve(relay(instance, accountId, region, proxyPort), instance.getVpcEndpointAddress()); + instance.setVpcEndpointAddress(address); + remember(instance, accountId, region); + } + + /** + * As Floci starts, takes up every relay an earlier Floci left: removed, or held with its address when Docker does + * not confirm that ({@link VpcAddressRelays#recoverAll}). + */ + public void recoverRelays() { + relays.recoverAll(); + } + + /** Whether a relay that may exist forwards to the proxy port {@code port}, which no other database may get. */ + public boolean targetsPort(int port) { + return relays.targetsPort(port); + } + + // The relay reaches the proxy at Floci's address on the network it joins besides its VPC's, as RDS's database + // containers on that network are reached. + private VpcAddressRelays.Relay relay(DbInstance instance, String accountId, String region, int proxyPort) { + return new VpcAddressRelays.Relay(instance.getVpcEndpointId(), accountId, region, instance.getVpcId(), + instance.getVpcEndpointSubnetId(), servedPort(instance), + dockerHostResolver.resolveOn(relays.network().orElse(null)), proxyPort, + "DB instance " + instance.getDbInstanceIdentifier()); + } + + /** + * Makes the instance's endpoint name known under its identifier now, for one not served yet, such as a stopped + * instance after a restart, or one whose identifier a blue/green switchover changed. + */ + public void remember(DbInstance instance, String accountId, String region) { + String id = instance.getVpcEndpointId(); + relayIdsByHost.values().removeIf(id::equals); + relayIdsByHost.put(endpoint(instance, accountId, region).address().toLowerCase(Locale.ROOT), id); + } + + /** + * Stops serving the instance's endpoint; the record keeps its address for the next {@link #serve}, and its name + * stays known. + * + * @throws IllegalStateException when Docker does not confirm the relay removed: it still serves, and a later stop + * tries again + */ + public void stop(DbInstance instance) { + relays.stop(instance.getVpcEndpointId()); + } + + /** + * Stops serving the instance's endpoint for good, as the instance goes: its relay, the relays it moved off, and + * then its name. + * + * @throws IllegalStateException when Docker does not confirm one of the relays removed; the name stays known, and + * the relays not removed stay with the instance + */ + public void forget(DbInstance instance) { + stop(instance); + removeStaleRelays(instance); + if (!instance.getStaleVpcEndpointIds().isEmpty()) { + throw new IllegalStateException("Docker did not confirm the relays " + instance.getStaleVpcEndpointIds() + + " of DB instance " + instance.getDbInstanceIdentifier() + " removed"); + } + String id = instance.getVpcEndpointId(); + relayIdsByHost.values().removeIf(id::equals); + } + + /** + * Removes the relays the instance's endpoint moved off, as a serve, a delete and a restart do. Those Docker does + * not confirm removed stay with the instance for the next try. + */ + public void removeStaleRelays(DbInstance instance) { + instance.getStaleVpcEndpointIds().removeIf(relayId -> { + try { + relays.stop(relayId); + return true; + } catch (RuntimeException e) { + LOG.warnv(e, "DB instance {0} keeps relay {1} until it can be removed", + instance.getDbInstanceIdentifier(), relayId); + return false; + } + }); + } + + /** Whether a relay is tracked under {@code relayId}, one that serves or one whose start Docker left unclear. */ + public boolean tracks(String relayId) { + return relays.address(relayId).isPresent(); + } + + /** Whether a relay serves the instance's endpoint now. */ + public boolean serving(DbInstance instance) { + 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)); + } + + /** The address the endpoint named {@code host} is served at now; empty while it is stopped, or unknown. */ + public Optional addressOf(String host) { + return relays.address(relayIdsByHost.get(host.toLowerCase(Locale.ROOT))); + } + + @Override + public boolean hasSubnetDependency(String region, String subnetId) { + return relays.holdsSubnet(regionResolver.getAccountId(), region, subnetId); + } + + @Override + public boolean hasVpcDependency(String region, String vpcId) { + return relays.holdsVpc(regionResolver.getAccountId(), region, vpcId); + } + + @Override + public void stopManagedContainers() { + relays.stopAll(); + } + + /** A reset wipes the instances whose names the index holds. */ + @Override + public void clear() { + relayIdsByHost.clear(); + } + + /** Writes down again the relays a reset could not remove, whose placements the storage wipe took. */ + @Override + public void afterReset() { + relays.rewritePlacements(); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/RdsService.java b/src/main/java/io/floci/aws/services/rds/RdsService.java index 096ad78356..92cfc409e5 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -220,6 +220,8 @@ public class RdsService implements Resettable, ResourceProvider { // Null when a test constructs the service without CloudWatch; auto-pause then reports no metrics. private final CloudWatchMetricsService metricsService; private final RdsEventPublisher eventPublisher; + /** Serves instance endpoints in their VPC with endpoints-in-vpc on; null in tests that build none. */ + private final RdsEndpointAddresses endpointAddresses; private final Set usedPorts = ConcurrentHashMap.newKeySet(); private final Set reportedMemberRelayFailures = ConcurrentHashMap.newKeySet(); private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$"); @@ -262,7 +264,7 @@ public class RdsService implements Resettable, ResourceProvider { CloudWatchMetricsService metricsService) { this(containerManager, proxyManager, ec2Service, regionResolver, config, storageFactory, secretsManagerService, dockerHostResolver, currentContainerNetworkResolver, taggingService, - kmsService, metricsService, null); + kmsService, metricsService, null, null); } @Inject @@ -278,7 +280,8 @@ public class RdsService implements Resettable, ResourceProvider { ResourceGroupsTaggingService taggingService, KmsService kmsService, CloudWatchMetricsService metricsService, - RdsEventPublisher eventPublisher) { + RdsEventPublisher eventPublisher, + RdsEndpointAddresses endpointAddresses) { this.containerManager = containerManager; this.proxyManager = proxyManager; this.ec2Service = ec2Service; @@ -291,6 +294,7 @@ public class RdsService implements Resettable, ResourceProvider { this.taggingService = taggingService; this.metricsService = metricsService; this.eventPublisher = eventPublisher; + this.endpointAddresses = endpointAddresses; this.instances = storageFactory.create("rds", "rds-instances.json", new TypeReference>() {}); this.eventSubscriptions = storageFactory.create("rds", "rds-event-subscriptions.json", @@ -447,7 +451,7 @@ public class RdsService implements Resettable, ResourceProvider { this(containerManager, proxyManager, ec2Service, regionResolver, config, instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups, secretsManagerService, dockerHostResolver, currentContainerNetworkResolver, proxies, proxyTargetGroups, optionGroups, taggingService, - kmsService, null); + kmsService, null, null); } RdsService(RdsContainerManager containerManager, @@ -468,7 +472,8 @@ public class RdsService implements Resettable, ResourceProvider { StorageBackend optionGroups, ResourceGroupsTaggingService taggingService, KmsService kmsService, - RdsEventPublisher eventPublisher) { + RdsEventPublisher eventPublisher, + RdsEndpointAddresses endpointAddresses) { this.containerManager = containerManager; this.proxyManager = proxyManager; this.ec2Service = ec2Service; @@ -489,6 +494,7 @@ public class RdsService implements Resettable, ResourceProvider { this.taggingService = taggingService; this.metricsService = null; this.eventPublisher = eventPublisher; + this.endpointAddresses = endpointAddresses; this.globalClusters = new InMemoryStorage<>(); this.snapshots = new InMemoryStorage<>(); this.clusterSnapshots = new InMemoryStorage<>(); @@ -508,6 +514,9 @@ public class RdsService implements Resettable, ResourceProvider { } public void restorePersistedRuntime() { + if (endpointAddresses != null) { + endpointAddresses.recoverRelays(); + } Map persistedPortOwners = reservePersistedProxyPorts(); restoreClusters(persistedPortOwners); restoreInstances(persistedPortOwners); @@ -844,8 +853,13 @@ public class RdsService implements Resettable, ResourceProvider { String effectiveSecretKmsKeyId = manageInstancePassword ? 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. 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(); + int proxyPort = endpointInVpc ? reserveProxyPortBehindVpcEndpoint(requestedPort) + : reserveProxyPort(requestedPort); String backendHost = null; int backendPort = 0; @@ -964,6 +978,12 @@ public class RdsService implements Resettable, ResourceProvider { instance.setDeletionProtection(Boolean.TRUE.equals(deletionProtection)); instance.setDbiResourceId(dbiResourceId); instance.setDbInstanceArn(dbInstanceArn); + if (isBlank(dbClusterIdentifier) && endpointAddresses != null && endpointAddresses.assign(instance)) { + endpoint = instanceEndpoint(instance, proxyPort); + instance.setEndpoint(endpoint); + // Known from now on, so the name resolves to no address rather than to Floci until it is served. + endpointAddresses.remember(instance, currentAccountId(), effectiveRegion); + } } catch (RuntimeException | Error failure) { releaseProxyPort(proxyPort); throw failure; @@ -1064,6 +1084,7 @@ public class RdsService implements Resettable, ResourceProvider { accountId, instanceRegion, id, user, pw), proxyBinding(engine, instance.getEndpoint().address(), instance.getEndpoint().port(), instanceRegion, accountId, backendIdentity.dbUserResourceId())); + serveInVpc(instance); } if (currentCluster != null) { @@ -1197,13 +1218,15 @@ public class RdsService implements Resettable, ResourceProvider { boolean releasePort = proxyStopped && instanceRemoved; if (!instanceRemoved) { DbEndpoint originalEndpoint = instance.getEndpoint(); - if (proxyStopped) { + // A relay Docker did not remove still forwards to the proxy port, so the record keeps it reserved. + boolean portFreed = proxyStopped && !servedInVpc(instance); + if (portFreed) { instance.setProxyPort(0); instance.setEndpoint(null); } try { putInstanceForScope(accountId, region, id, instance); - releasePort = proxyStopped; + releasePort = portFreed; } catch (RuntimeException | Error rollbackFailure) { instance.setProxyPort(proxyPort); instance.setEndpoint(originalEndpoint); @@ -1224,6 +1247,13 @@ 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); + } if (!mock && instance.getDockerVolumeName() != null) { try { if (instance.getContainerId() != null) { @@ -1580,7 +1610,7 @@ public class RdsService implements Resettable, ResourceProvider { snapshot.getMasterUsername(), snapshot.getMasterPassword(), snapshot.getDbName(), targetClass, snapshot.getAllocatedStorage(), Boolean.TRUE.equals(iamEnabled), null, dbSubnetGroupName, null, availabilityZone, multiAz, false, null, tags, vpcSecurityGroupIds, - null, effectiveRegion, true, restoreSettings, null, requestedPort); + null, effectiveRegion, true, restoreSettings, null, portFromSource(requestedPort, snapshot.getPort())); if (!config.services().rds().mock()) { try { @@ -1698,7 +1728,7 @@ public class RdsService implements Resettable, ResourceProvider { request.autoMinorVersionUpgrade() == null || request.autoMinorVersionUpgrade(), // Deletion protection is turned on only once the copy succeeds, so a failed copy can // still remove the target it created. - settings, request.publiclyAccessible(), request.port(), null); + settings, request.publiclyAccessible(), portFromSource(request.port(), portOf(source)), null); if (!config.services().rds().mock()) { try { @@ -2310,7 +2340,7 @@ public class RdsService implements Resettable, ResourceProvider { dbSubnetGroupName, null, request.availabilityZone(), Boolean.TRUE.equals(request.multiAz()), false, null, tags, vpcSecurityGroupIds, optionGroupName, effectiveRegion, autoMinorVersionUpgrade, settings, - request.publiclyAccessible()); + request.publiclyAccessible(), portFromSource(null, portOf(source))); linkReadReplica(source, replica); if (!config.services().rds().mock() @@ -4217,6 +4247,7 @@ public class RdsService implements Resettable, ResourceProvider { if (newSubnetGroup != null) { instance.setDbSubnetGroupName(dbSubnetGroupName); instance.setVpcId(newSubnetGroup.getVpcId()); + instance.setSubnetAvailabilityZones(newSubnetGroup.getSubnetAvailabilityZones()); } if (securityGroupIdsAfter != null) { instance.setVpcSecurityGroupIds(securityGroupIdsAfter); @@ -4249,6 +4280,11 @@ public class RdsService implements Resettable, ResourceProvider { rdsResourceRelayKey(instance.getDbInstanceArn(), id), iamEnabled); } + if (newSubnetGroup != null && !clusterMember && endpointAddresses != null + && RdsEndpointAddresses.inVpc(instance)) { + moveEndpointInVpc(instance, effectiveRegion); + } + if (restartForUpgrade) { restartForMinorEngineUpgrade(instance, previousEngineVersion, effectiveRegion); } @@ -4257,6 +4293,78 @@ public class RdsService implements Resettable, ResourceProvider { return instance; } + /** + * Moves an instance's endpoint to a subnet of the DB subnet group it moved to, as the instance moves with its + * group: a running instance is served there now ({@link #serveInVpc}), and one that is not running when it next + * starts. A relay the move leaves that Docker does not confirm removed stays with the instance + * ({@link DbInstance#getStaleVpcEndpointIds}), so the proxy port it forwards to is kept until it is gone. + */ + private void moveEndpointInVpc(DbInstance instance, String region) { + String accountId = accountIdFromArn(instance.getDbInstanceArn()); + if (hasBackend(instance.getContainerHost(), instance.getContainerPort())) { + serveInVpc(instance); + } else { + String oldRelayId = instance.getVpcEndpointId(); + instance.setVpcEndpointId(RdsEndpointAddresses.newRelayId()); + instance.setVpcEndpointSubnetId(RdsEndpointAddresses.subnetFor(instance)); + instance.setVpcEndpointAddress(null); + endpointAddresses.remember(instance, accountId, region); + stopRelayMovedOff(instance, oldRelayId); + } + putInstanceForScope(accountId, region, instance.getDbInstanceIdentifier(), instance); + } + + /** + * Serves a running instance's endpoint in a subnet of its DB subnet group in place of the one it is served in, + * which belongs to the group it moved off, under a new relay id: the old relay goes once the new one serves. When + * the new subnet cannot serve it, the instance keeps the old relay, endpoint and subnet, and the next serve tries + * again. A new relay whose start Docker left unclear stays with the instance, as the old one does when Docker + * does not confirm it removed. + */ + private void moveServedEndpoint(DbInstance instance, String accountId, String region, int proxyPort) { + String oldRelayId = instance.getVpcEndpointId(); + String oldSubnetId = instance.getVpcEndpointSubnetId(); + String oldAddress = instance.getVpcEndpointAddress(); + String newRelayId = RdsEndpointAddresses.newRelayId(); + instance.setVpcEndpointId(newRelayId); + instance.setVpcEndpointSubnetId(RdsEndpointAddresses.subnetFor(instance)); + instance.setVpcEndpointAddress(null); + try { + endpointAddresses.serve(instance, accountId, region, proxyPort); + } catch (RuntimeException e) { + instance.setVpcEndpointId(oldRelayId); + instance.setVpcEndpointSubnetId(oldSubnetId); + instance.setVpcEndpointAddress(oldAddress); + if (endpointAddresses.tracks(newRelayId)) { + instance.getStaleVpcEndpointIds().add(newRelayId); + } + endpointAddresses.remember(instance, accountId, region); + LOG.warnv(e, "DB instance {0} keeps its endpoint in subnet {1}: the new subnet cannot serve it yet", + instance.getDbInstanceIdentifier(), oldSubnetId); + return; + } + stopRelayMovedOff(instance, oldRelayId); + } + + private void stopRelayMovedOff(DbInstance instance, String relayId) { + try { + endpointAddresses.stopRelay(relayId); + } catch (RuntimeException e) { + instance.getStaleVpcEndpointIds().add(relayId); + LOG.warnv(e, "DB instance {0} keeps relay {1} until it can be removed", + instance.getDbInstanceIdentifier(), relayId); + } + } + + /** + * Whether the instance's endpoint is still in a subnet of the DB subnet group it moved off: a move that could not + * be served when it was made, which the next serve makes. + */ + private static boolean endpointMovePending(DbInstance instance) { + Map subnets = instance.getSubnetAvailabilityZones(); + return !subnets.isEmpty() && !subnets.containsKey(instance.getVpcEndpointSubnetId()); + } + private boolean requiresMinorEngineRestart(DbInstance instance, String requestedVersion) { if (config.services().rds().mock() || isBlank(requestedVersion) || requestedVersion.equals(instance.getEngineVersion())) { @@ -4671,6 +4779,13 @@ 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); + } if (instance.getContainerId() != null) { try { containerManager.stop(buildHandle(instance)); @@ -4720,7 +4835,7 @@ public class RdsService implements Resettable, ResourceProvider { if (isDsqlReservedPort(instance.getProxyPort())) { int port = allocateProxyPort(); instance.setProxyPort(port); - instance.setEndpoint(advertised(proxyEndpoint(port), instance.getRequestedPort())); + instance.setEndpoint(instanceEndpoint(instance, port)); } refreshManagedMasterUserSecret(instance, effectiveRegion); instance.setStatus(DbInstanceStatus.STARTING); @@ -4782,6 +4897,22 @@ public class RdsService implements Resettable, ResourceProvider { (user, pw) -> validateDbPasswordForScope(accountId, instanceRegion, id, user, pw), proxyBinding(instance.getEngine(), instance.getEndpoint().address(), instance.getEndpoint().port(), instanceRegion, accountId, instance.getDbiResourceId())); + try { + serveInVpc(instance); + } catch (RuntimeException e) { + // Started without its endpoint, the instance would report an address nothing serves. It goes back to + // stopped, as it was, so a later StartDBInstance tries again. + proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id)); + if (handle != null) { + stopStartedBackend(handle, e); + } + instance.setContainerId(null); + instance.setContainerHost(null); + instance.setContainerPort(0); + instance.setStatus(DbInstanceStatus.STOPPED); + putInstanceForScope(currentAccountId(), effectiveRegion, id, instance); + throw e; + } } } @@ -5276,11 +5407,12 @@ public class RdsService implements Resettable, ResourceProvider { int relayPort = instance.getProxyPort(); DbEndpoint relayEndpoint = instance.getEndpoint(); boolean allocatedRelayPort = false; + boolean proxyStarted = false; try { if (relayEndpoint == null) { relayPort = allocateProxyPort(); allocatedRelayPort = true; - relayEndpoint = advertised(proxyEndpoint(relayPort), instance.getRequestedPort()); + relayEndpoint = instanceEndpoint(instance, relayPort); } proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id), backendIdentity.runtimeId(), @@ -5292,7 +5424,14 @@ public class RdsService implements Resettable, ResourceProvider { proxyBinding(instance.getEngine(), relayEndpoint.address(), relayEndpoint.port(), instanceRegion, accountId, backendIdentity.dbUserResourceId())); + proxyStarted = true; + if (started != null) { + serveInVpc(instance, relayPort); + } } catch (RuntimeException e) { + if (proxyStarted) { + proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id)); + } if (allocatedRelayPort) { releaseProxyPort(relayPort); } @@ -5614,6 +5753,9 @@ public class RdsService implements Resettable, ResourceProvider { if (!mock || instance.isBackendCleanupRequired()) { proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id)); } + // A relay Docker does not confirm removed fails the delete, which keeps the record, its proxy port and the + // relay's address until a retry removes it. + forgetInVpc(instance); if (clusterId == null || clusterId.isBlank()) { // Standalone, so stop its container and clean up its Docker volume. Current mock mode @@ -9298,6 +9440,35 @@ public class RdsService implements Resettable, ResourceProvider { return allocateProxyPort(); } + /** + * 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. + */ + private Integer portFromSource(Integer requested, Integer sourcePort) { + if (requested != null || endpointAddresses == null || !endpointAddresses.enabled()) { + return requested; + } + return sourcePort != null && sourcePort > 0 ? sourcePort : null; + } + + /** The Port a source instance serves, or was created with, for {@link #portFromSource}. */ + private static Integer portOf(DbInstance source) { + if (RdsEndpointAddresses.inVpc(source)) { + return RdsEndpointAddresses.servedPort(source); + } + return source.getRequestedPort(); + } + + /** A free proxy port for an endpoint in its VPC, which serves {@code requestedPort} itself; the Port is checked. */ + private int reserveProxyPortBehindVpcEndpoint(Integer requestedPort) { + if (requestedPort != null && (requestedPort < 1150 || requestedPort > 65535)) { + throw new AwsException("InvalidParameterValue", "Port must be between 1150 and 65535.", 400); + } + return allocateProxyPort(); + } + private int allocateProxyPort() { int base = config.services().rds().proxyBasePort(); int max = config.services().rds().proxyMaxPort(); @@ -9311,9 +9482,25 @@ public class RdsService implements Resettable, ResourceProvider { } private boolean reserveAvailableProxyPort(int port) { + return !isDsqlReservedPort(port) && !relayTargets(port) && usedPorts.add(port); + } + + /** + * Reserves a port a stored resource already owns, as a restart does: a relay that still forwards to it is that + * resource's own, so it does not keep the port from its owner. + */ + private boolean reserveOwnedProxyPort(int port) { return !isDsqlReservedPort(port) && usedPorts.add(port); } + /** + * Whether a relay of an endpoint in a VPC that may still run forwards to {@code port}: one Docker did not confirm + * removed outlives its instance's hold on the port, and a database given the port would get its clients. + */ + private boolean relayTargets(int port) { + return endpointAddresses != null && endpointAddresses.targetsPort(port); + } + private boolean isDsqlReservedPort(int port) { EmulatorConfig.DsqlServiceConfig dsql = config.services().dsql(); return dsql != null && dsql.enabled() && !dsql.mock() && dsql.port() == port; @@ -9323,6 +9510,102 @@ public class RdsService implements Resettable, ResourceProvider { usedPorts.remove(port); } + /** + * The endpoint a standalone instance on {@code proxyPort} reports: its endpoint in its VPC when it has one, + * otherwise the proxy endpoint. + */ + private DbEndpoint instanceEndpoint(DbInstance instance, int proxyPort) { + if (RdsEndpointAddresses.inVpc(instance)) { + return RdsEndpointAddresses.endpoint(instance, accountIdFromArn(instance.getDbInstanceArn()), + regionResolver.regionOf(instance.getDbInstanceArn())); + } + return advertised(proxyEndpoint(proxyPort), instance.getRequestedPort()); + } + + /** 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()); + } + + /** + * Serves the endpoint, first making a move to another DB subnet group that could not be served when it was made: + * a relay that still serves in the old subnet gives way only once one in the new subnet serves + * ({@link #moveServedEndpoint}), and an endpoint no relay serves takes a subnet of the group it is in now. + */ + private void serveInVpc(DbInstance instance, int proxyPort) { + if (endpointAddresses == null || !RdsEndpointAddresses.inVpc(instance) || !endpointAddresses.enabled()) { + return; + } + String accountId = accountIdFromArn(instance.getDbInstanceArn()); + String region = regionResolver.regionOf(instance.getDbInstanceArn()); + if (endpointMovePending(instance)) { + if (endpointAddresses.serving(instance)) { + moveServedEndpoint(instance, accountId, region, proxyPort); + return; + } + instance.setVpcEndpointSubnetId(RdsEndpointAddresses.subnetFor(instance)); + instance.setVpcEndpointAddress(null); + } + endpointAddresses.serve(instance, accountId, region, proxyPort); + } + + /** + * Stops serving an instance's endpoint in its VPC; the record keeps the address for the next start. + * + * @throws IllegalStateException when Docker does not confirm the relay removed + */ + private void stopServingInVpc(DbInstance instance) { + if (endpointAddresses != null && RdsEndpointAddresses.inVpc(instance)) { + endpointAddresses.stop(instance); + } + } + + /** + * 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. + */ + private boolean servedInVpc(DbInstance instance) { + return endpointAddresses != null && RdsEndpointAddresses.inVpc(instance) && endpointAddresses.serving(instance); + } + + /** + * Stops serving an instance's endpoint in its VPC for good, as the instance goes. + * + * @throws IllegalStateException when Docker does not confirm the relay removed: the relay still forwards to the + * instance's proxy port, so the caller keeps the record and the port + */ + private void forgetInVpc(DbInstance instance) { + if (endpointAddresses != null && RdsEndpointAddresses.inVpc(instance)) { + endpointAddresses.forget(instance); + } + } + + /** + * 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. + */ + private void placeRestoredEndpoint(DbInstance instance) { + if (endpointAddresses == null || !isBlank(instance.getDbClusterIdentifier())) { + return; + } + endpointAddresses.removeStaleRelays(instance); + if (RdsEndpointAddresses.inVpc(instance) && !endpointAddresses.enabled()) { + 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)) { + endpointAddresses.assign(instance); + } + if (RdsEndpointAddresses.inVpc(instance)) { + // Its name is known whatever comes of serving it, with no address until it is served. + endpointAddresses.remember(instance, accountIdFromArn(instance.getDbInstanceArn()), + regionResolver.regionOf(instance.getDbInstanceArn())); + } + } + /** * With {@code advertise-requested-port} on, reports the Port the client asked for instead of the * proxy port. The proxy still listens on its own port; real clients connect there. @@ -9337,9 +9620,13 @@ public class RdsService implements Resettable, ResourceProvider { /** * The port a client connects to {@code instance} on, which a connection secret must carry: its endpoint's, unless - * the endpoint advertises the requested Port, which nothing listens on. + * the endpoint advertises the requested Port, which nothing listens on. An endpoint in its VPC serves the port it + * reports. */ public int connectablePort(DbInstance instance) { + if (RdsEndpointAddresses.inVpc(instance) && instance.getEndpoint() != null) { + return instance.getEndpoint().port(); + } return advertises(instance.getRequestedPort()) ? connectablePort(instance.getProxyPort()) : instance.getEndpoint().port(); } @@ -10226,14 +10513,17 @@ public class RdsService implements Resettable, ResourceProvider { if (instance.getStatus() == DbInstanceStatus.DELETING) { continue; } + boolean wasInVpc = RdsEndpointAddresses.inVpc(instance); + placeRestoredEndpoint(instance); + boolean inVpc = RdsEndpointAddresses.inVpc(instance); if (instance.getStatus() == DbInstanceStatus.STOPPED) { try { // Stays stopped across a restart; StartDBInstance brings the container back. int port = claimRestoredProxyPort( persistedPortOwners, instance.getDbInstanceArn(), instance.getProxyPort()); - if (port != instance.getProxyPort()) { + if (port != instance.getProxyPort() || inVpc || wasInVpc) { instance.setProxyPort(port); - instance.setEndpoint(advertised(proxyEndpoint(port), instance.getRequestedPort())); + instance.setEndpoint(instanceEndpoint(instance, port)); putInstanceForScope(accountIdFromArn(instance.getDbInstanceArn()), regionResolver.regionOf(instance.getDbInstanceArn()), instance.getDbInstanceIdentifier(), instance); @@ -10285,7 +10575,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.getDbInstanceIdentifier(), instance); continue; } - instance.setEndpoint(advertised(proxyEndpoint(proxyPort), instance.getRequestedPort())); + instance.setEndpoint(instanceEndpoint(instance, proxyPort)); refreshManagedMasterUserSecret(instance, instanceRegion); String backendHost; int backendPort; @@ -10334,6 +10624,9 @@ public class RdsService implements Resettable, ResourceProvider { proxyBinding(instance.getEngine(), instance.getEndpoint().address(), instance.getEndpoint().port(), instanceRegion, accountId, backendIdentity.dbUserResourceId())); + if (restoredHandle != null) { + serveInVpc(instance); + } } instance.setStatus(DbInstanceStatus.AVAILABLE); putInstanceForScope(accountId, instanceRegion, @@ -10346,6 +10639,11 @@ public class RdsService implements Resettable, ResourceProvider { } catch (RuntimeException stopFailure) { e.addSuppressed(stopFailure); } + try { + stopServingInVpc(instance); + } catch (RuntimeException stopFailure) { + e.addSuppressed(stopFailure); + } } RdsContainerHandle cleanupHandle = restoredHandle != null ? restoredHandle @@ -11456,7 +11754,7 @@ public class RdsService implements Resettable, ResourceProvider { } private void reservePersistedProxyPort(Map owners, String ownerArn, int port) { - if (port > 0 && ownerArn != null && !owners.containsKey(port) && reserveAvailableProxyPort(port)) { + if (port > 0 && ownerArn != null && !owners.containsKey(port) && reserveOwnedProxyPort(port)) { owners.put(port, ownerArn); } } @@ -11469,7 +11767,7 @@ public class RdsService implements Resettable, ResourceProvider { } private int reserveOrAllocateProxyPort(int persistedPort) { - if (persistedPort > 0 && reserveAvailableProxyPort(persistedPort)) { + if (persistedPort > 0 && reserveOwnedProxyPort(persistedPort)) { return persistedPort; } return allocateProxyPort(); @@ -12985,7 +13283,7 @@ public class RdsService implements Resettable, ResourceProvider { blue.getDbSubnetGroupName(), null, blue.getAvailabilityZone(), blue.isMultiAz(), false, null, blue.getTags(), blue.getVpcSecurityGroupIds(), blue.getOptionGroupName(), region, blue.isAutoMinorVersionUpgrade(), settings, blue.isPubliclyAccessible(), - null, false); + portFromSource(null, portOf(blue)), false); linkReadReplica(blue, green); if (!config.services().rds().mock() @@ -13091,6 +13389,8 @@ public class RdsService implements Resettable, ResourceProvider { green.setEndpoint(blueEndpoint); green.setProxyPort(bluePort); green.setRequestedPort(blueRequestedPort); + // An endpoint in the VPC moves too: its relay forwards to the proxy port that moved with it. + swapVpcEndpoints(blue, green); // Blue moves off its ARN first, so it is free when green takes it. deleteInstanceForScope(accountId, effectiveRegion, blueId); @@ -13102,6 +13402,15 @@ public class RdsService implements Resettable, ResourceProvider { green.setDbInstanceIdentifier(blueId); green.setDbInstanceArn(blueArn); green.setTags(new LinkedHashMap<>(blue.getTags())); + // An endpoint in the VPC is named after its instance, so each takes the name of its new identifier. + for (DbInstance member : new DbInstance[] {blue, green}) { + if (RdsEndpointAddresses.inVpc(member)) { + member.setEndpoint(instanceEndpoint(member, member.getProxyPort())); + if (endpointAddresses != null) { + endpointAddresses.remember(member, accountId, effectiveRegion); + } + } + } putInstanceForScope(accountId, effectiveRegion, oldId, blue); putInstanceForScope(accountId, effectiveRegion, blueId, green); @@ -13122,6 +13431,21 @@ public class RdsService implements Resettable, ResourceProvider { return deployment; } + private static void swapVpcEndpoints(DbInstance blue, DbInstance green) { + String blueId = blue.getVpcEndpointId(); + String blueSubnetId = blue.getVpcEndpointSubnetId(); + String blueAddress = blue.getVpcEndpointAddress(); + blue.setVpcEndpointId(green.getVpcEndpointId()); + blue.setVpcEndpointSubnetId(green.getVpcEndpointSubnetId()); + blue.setVpcEndpointAddress(green.getVpcEndpointAddress()); + green.setVpcEndpointId(blueId); + green.setVpcEndpointSubnetId(blueSubnetId); + green.setVpcEndpointAddress(blueAddress); + List blueStale = blue.getStaleVpcEndpointIds(); + blue.setStaleVpcEndpointIds(green.getStaleVpcEndpointIds()); + green.setStaleVpcEndpointIds(blueStale); + } + /** * Deletes the deployment record. With {@code deleteTarget} the green instance is deleted too, * which AWS allows only before a switchover; without it the green instance is kept as a diff --git a/src/main/java/io/floci/aws/services/rds/model/DbInstance.java b/src/main/java/io/floci/aws/services/rds/model/DbInstance.java index e55ab4ef28..5dfa73e3be 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbInstance.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbInstance.java @@ -80,6 +80,15 @@ public class DbInstance { private Instant createdAt; private int proxyPort; private Integer requestedPort; + // With endpoints-in-vpc: the relay that serves this record's endpoint at its own address in + // vpcEndpointSubnetId, and that address once it has one. They move with the endpoint, as the + // proxy port does, when a blue/green switchover swaps endpoints. + private String vpcEndpointId; + private String vpcEndpointSubnetId; + private String vpcEndpointAddress; + // Relays the endpoint moved off whose removal Docker has not confirmed yet: they still forward to the proxy + // port, so the record keeps it until each is gone. + private List staleVpcEndpointIds = new ArrayList<>(); // Read replication links, kept on both ends the way DescribeDBInstances reports them: a // replica names its source, a source lists its replicas, by identifier within a Region and // by ARN across Regions. Null and empty on a standalone. The status is the "read @@ -302,6 +311,20 @@ public class DbInstance { public Integer getRequestedPort() { return requestedPort; } public void setRequestedPort(Integer requestedPort) { this.requestedPort = requestedPort; } + public String getVpcEndpointId() { return vpcEndpointId; } + public void setVpcEndpointId(String vpcEndpointId) { this.vpcEndpointId = vpcEndpointId; } + + public String getVpcEndpointSubnetId() { return vpcEndpointSubnetId; } + public void setVpcEndpointSubnetId(String vpcEndpointSubnetId) { this.vpcEndpointSubnetId = vpcEndpointSubnetId; } + + public String getVpcEndpointAddress() { return vpcEndpointAddress; } + public void setVpcEndpointAddress(String vpcEndpointAddress) { this.vpcEndpointAddress = vpcEndpointAddress; } + + public List getStaleVpcEndpointIds() { return staleVpcEndpointIds; } + public void setStaleVpcEndpointIds(List staleVpcEndpointIds) { + this.staleVpcEndpointIds = staleVpcEndpointIds != null ? new ArrayList<>(staleVpcEndpointIds) : new ArrayList<>(); + } + public String getDockerVolumeName() { return dockerVolumeName; } public void setDockerVolumeName(String dockerVolumeName) { this.dockerVolumeName = dockerVolumeName; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 17653484f8..cde809e2b9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -655,6 +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 # 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. diff --git a/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java b/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java index e9aa068b20..ae8015fee1 100644 --- a/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java +++ b/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java @@ -79,4 +79,32 @@ class AwsEndpointsTest { assertEquals(false, AwsPartitions.byId("aws-eusc").supportsS3DualStack("eusc-de-east-1")); assertEquals(false, AwsPartitions.commercial().supportsS3DualStack(null)); } + + @ParameterizedTest + @MethodSource("io.floci.aws.testing.PartitionMatrix#cases") + void aDbInstanceHostCarriesTheAccountAndRegionIdentifierAndThePartitionSuffix(PartitionCase partitionCase) { + String region = partitionCase.region(); + String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", region); + + assertEquals("db1." + identifier + "." + region + ".rds." + partitionCase.dnsSuffix(), + AwsEndpoints.rdsInstanceHost("DB1", "123456789012", region)); + PartitionMatrix.assertHostIn(partitionCase, AwsEndpoints.rdsInstanceHost("db1", "123456789012", region)); + } + + @Test + void theRdsEndpointIdentifierIsTwelveLettersAndDigitsALetterFirst() { + String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", "us-east-1"); + + assertEquals(12, identifier.length()); + assertEquals(true, identifier.matches("[a-z][a-z0-9]{11}")); + } + + @Test + void theRdsEndpointIdentifierIsTheSameForAnAccountAndRegionAndDiffersAcrossEither() { + String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", "us-east-1"); + + assertEquals(identifier, AwsEndpoints.rdsEndpointIdentifier("123456789012", "us-east-1")); + assertEquals(false, identifier.equals(AwsEndpoints.rdsEndpointIdentifier("210987654321", "us-east-1"))); + assertEquals(false, identifier.equals(AwsEndpoints.rdsEndpointIdentifier("123456789012", "eu-west-1"))); + } } diff --git a/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java b/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java index 6b22b29e25..3035b559a9 100644 --- a/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java @@ -50,6 +50,22 @@ class CurrentContainerNetworkResolverTest { assertEquals(Optional.of("172.24.0.2"), resolver.resolveContainerIp()); } + @Test + void resolveContainerIpOn_givesFlocisAddressOnThatNetworkOnly() { + Map networks = networks( + "floci_default", "172.19.0.2", + "rds-net", "172.30.0.5"); + CurrentContainerNetworkResolver resolver = resolverOn(networks); + + assertEquals(Optional.of("172.30.0.5"), resolver.resolveContainerIpOn("rds-net")); + assertEquals(Optional.empty(), resolver.resolveContainerIpOn("other-net")); + assertEquals(Optional.empty(), resolver.resolveContainerIpOn(null)); + + // Floci joins networks as it runs, so the next call sees one it joined. + networks.put("other-net", network("172.31.0.7")); + assertEquals(Optional.of("172.31.0.7"), resolver.resolveContainerIpOn("other-net")); + } + @Test void resolveNetworkName_skipsANetworkFlociMadeWhichItIsStillOnAfterACrash() { // Docker lists a container's networks by name, so the cluster's comes first. diff --git a/src/test/java/io/floci/aws/core/common/docker/DockerHostResolverTest.java b/src/test/java/io/floci/aws/core/common/docker/DockerHostResolverTest.java index f135fc22d9..cc6d653203 100644 --- a/src/test/java/io/floci/aws/core/common/docker/DockerHostResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/DockerHostResolverTest.java @@ -31,4 +31,45 @@ class DockerHostResolverTest { assertEquals("172.24.0.2", resolver.resolve()); } + + @Test + void resolveOn_usesFlocisAddressOnTheNetworkWhenItIsOnIt() { + ContainerDetector containerDetector = mock(ContainerDetector.class); + CurrentContainerNetworkResolver currentContainerNetworkResolver = + mock(CurrentContainerNetworkResolver.class); + when(containerDetector.isRunningInContainer()).thenReturn(true); + when(currentContainerNetworkResolver.resolveContainerIp()).thenReturn(Optional.of("172.24.0.2")); + when(currentContainerNetworkResolver.resolveContainerIpOn("rds-net")).thenReturn(Optional.of("172.30.0.5")); + + DockerHostResolver resolver = + new DockerHostResolver(config(null), containerDetector, currentContainerNetworkResolver); + + assertEquals("172.30.0.5", resolver.resolveOn("rds-net")); + assertEquals("172.24.0.2", resolver.resolveOn("other-net")); + } + + @Test + void resolveOn_keepsAConfiguredOverrideAndTheHostAlias() { + ContainerDetector inContainer = mock(ContainerDetector.class); + CurrentContainerNetworkResolver currentContainerNetworkResolver = + mock(CurrentContainerNetworkResolver.class); + when(inContainer.isRunningInContainer()).thenReturn(true); + when(currentContainerNetworkResolver.resolveContainerIpOn("rds-net")).thenReturn(Optional.of("172.30.0.5")); + assertEquals("floci.internal", new DockerHostResolver(config("floci.internal"), inContainer, + currentContainerNetworkResolver).resolveOn("rds-net")); + + ContainerDetector onHost = mock(ContainerDetector.class); + assertEquals("host.docker.internal", new DockerHostResolver(config(null), onHost, + currentContainerNetworkResolver).resolveOn("rds-net")); + } + + private static EmulatorConfig config(String dockerHostOverride) { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class); + when(config.services()).thenReturn(services); + when(services.lambda()).thenReturn(lambda); + when(lambda.dockerHostOverride()).thenReturn(Optional.ofNullable(dockerHostOverride)); + return config; + } } diff --git a/src/test/java/io/floci/aws/services/ec2/VpcAddressRelaysTest.java b/src/test/java/io/floci/aws/services/ec2/VpcAddressRelaysTest.java new file mode 100644 index 0000000000..baf1ffcaec --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/VpcAddressRelaysTest.java @@ -0,0 +1,343 @@ +package io.floci.aws.services.ec2; + +import com.github.dockerjava.api.model.Container; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.services.ec2.model.Subnet; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** An endpoint served at its own address in a subnet, by a relay container EC2 leases the address for. */ +class VpcAddressRelaysTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private Ec2Service ec2; + private ContainerLifecycleManager lifecycleManager; + private ContainerBuilder.Builder builder; + private VpcRelayFixture fixture; + private VpcAddressRelays relays; + + @BeforeEach + void setUp() { + ec2 = mock(Ec2Service.class); + Subnet subnet = new Subnet(); + subnet.setSubnetId("subnet-1"); + subnet.setVpcId("vpc-1"); + subnet.setCidrBlock("10.0.1.0/24"); + when(ec2.describeSubnets(REGION, List.of("subnet-1"), Map.of())).thenReturn(List.of(subnet)); + fixture = new VpcRelayFixture(ec2); + lifecycleManager = fixture.lifecycleManager; + builder = fixture.builder; + relays = fixture.relays("test-endpoint", "floci-net"); + } + + @Test + void aRelayListensOnTheEndpointPortAtItsAddressAndForwardsToTheTarget() { + assertEquals("10.0.1.20", relays.serve(relay("ep1", 5432, 7001), null)); + + verify(builder).withEntrypoint(List.of("socat")); + verify(builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:7001,nodelay")); + verify(builder).withDockerNetwork(Optional.of("floci-net")); + verify(builder).withHostDockerInternalOnLinux(); + verify(ec2).attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "relay-1", "10.0.1.20"); + assertEquals(Optional.of("10.0.1.20"), relays.address("ep1")); + assertTrue(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + assertTrue(relays.holdsVpc(ACCOUNT, REGION, "vpc-1")); + } + + @Test + void aSameNamedContainerLeftBehindIsRemovedBeforeTheRelayStarts() { + relays.serve(relay("ep1", 5432, 7001), null); + + InOrder order = inOrder(lifecycleManager); + order.verify(lifecycleManager).removeIfExistsStrict(relays.containerName("ep1")); + order.verify(lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + verify(builder).withName(relays.containerName("ep1")); + } + + @Test + void aRelayServingTheEndpointTheSameWayIsKept() { + relays.serve(relay("ep1", 5432, 7001), null); + + assertEquals("10.0.1.20", relays.serve(relay("ep1", 5432, 7001), null)); + + verify(lifecycleManager, times(1)).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + } + + @Test + void aRelayThatIsGoneIsStartedAgainAtItsAddress() { + relays.serve(relay("ep1", 5432, 7001), null); + fixture.present.remove("relay-1"); + + assertEquals("10.0.1.20", relays.serve(relay("ep1", 5432, 7001), null)); + + verify(lifecycleManager, times(2)).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + verify(ec2).attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "relay-2", "10.0.1.20"); + } + + @Test + void aRelayToAnotherTargetReplacesTheOldOneAtItsAddress() { + relays.serve(relay("ep1", 5432, 7001), null); + + assertEquals("10.0.1.20", relays.serve(relay("ep1", 5432, 7002), null)); + + verify(lifecycleManager).removeIfExistsStrict("relay-1"); + verify(ec2).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + verify(ec2).attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "relay-2", "10.0.1.20"); + verify(builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:7002,nodelay")); + } + + @Test + void anEndpointIsServedAgainAtThePreferredAddressItHeldBefore() { + assertEquals("10.0.1.31", relays.serve(relay("ep1", 5432, 7001), "10.0.1.31")); + + verify(ec2, never()).allocateVpcPrivateIp(any(), any(), any()); + } + + @Test + void aSubnetWithNoAddressToGiveServesNothing() { + doReturn(Optional.empty()).when(ec2).allocateVpcPrivateIp(ACCOUNT, REGION, "subnet-1"); + + assertThrows(IllegalStateException.class, () -> relays.serve(relay("ep1", 5432, 7001), null)); + + assertEquals(Optional.empty(), relays.address("ep1")); + assertFalse(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + } + + @Test + void aRelayThatDoesNotStartGivesItsAddressBack() { + doAnswer(invocation -> { + invocation.>getArgument(1).accept("relay-x"); + throw new IllegalStateException("start refused"); + }).when(lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + + assertThrows(IllegalStateException.class, () -> relays.serve(relay("ep1", 5432, 7001), null)); + + verify(ec2).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + assertFalse(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + assertEquals(Optional.empty(), relays.address("ep1")); + assertEquals(List.of(), fixture.placements.all()); + } + + @Test + void aRelayThatMayHaveStartedAndCouldNotBeRemovedStaysTrackedUntilAStopRemovesIt() { + doAnswer(invocation -> { + invocation.>getArgument(1).accept("relay-x"); + fixture.present.add("relay-x"); + throw new IllegalStateException("start reply lost"); + }).when(lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + doThrow(new IllegalStateException("daemon down")).when(lifecycleManager).removeIfExistsStrict("relay-x"); + + assertThrows(IllegalStateException.class, () -> relays.serve(relay("ep1", 5432, 7001), null)); + + assertEquals(Optional.of("10.0.1.20"), relays.address("ep1")); + assertTrue(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + + doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(lifecycleManager).removeIfExistsStrict("relay-x"); + relays.stop("ep1"); + + assertEquals(Optional.empty(), relays.address("ep1")); + verify(ec2).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + } + + @Test + void aServedRelayIsWrittenDownUntilAStopRemovesIt() { + relays.serve(relay("ep1", 5432, 7001), null); + + assertEquals(1, fixture.placements.all().size()); + assertTrue(relays.targetsPort(7001)); + + relays.stop("ep1"); + + assertEquals(List.of(), fixture.placements.all()); + assertFalse(relays.targetsPort(7001)); + } + + @Test + void aRelayDockerDidNotRemoveStaysWrittenDownAndKeepsItsTargetPortTaken() { + relays.serve(relay("ep1", 5432, 7001), null); + doThrow(new IllegalStateException("daemon down")).when(lifecycleManager).removeIfExistsStrict("relay-1"); + + assertThrows(IllegalStateException.class, () -> relays.stop("ep1")); + + assertTrue(relays.targetsPort(7001)); + } + + @Test + void aRestartRemovesTheRelaysAnEarlierFlociWroteDown() { + relays.serve(relay("ep1", 5432, 7001), null); + VpcAddressRelays restarted = fixture.relays("test-endpoint", "floci-net"); + clearInvocations(lifecycleManager); + + restarted.recoverAll(); + + verify(lifecycleManager).removeIfExistsStrict(restarted.containerName("ep1")); + assertEquals(List.of(), fixture.placements.all()); + assertFalse(restarted.targetsPort(7001)); + } + + @Test + void aRelayARestartCannotRemoveIsHeldWithItsAddressUntilAStopRemovesIt() { + relays.serve(relay("ep1", 5432, 7001), null); + fixture.leased.clear(); + VpcAddressRelays restarted = fixture.relays("test-endpoint", "floci-net"); + String name = restarted.containerName("ep1"); + doThrow(new IllegalStateException("daemon down")).when(lifecycleManager).removeIfExistsStrict(name); + + restarted.recoverAll(); + + assertEquals(Optional.of("10.0.1.20"), restarted.address("ep1")); + assertTrue(fixture.leased.contains("10.0.1.20")); + assertTrue(restarted.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + assertTrue(restarted.targetsPort(7001)); + + doAnswer(invocation -> null).when(lifecycleManager).removeIfExistsStrict(name); + restarted.stop("ep1"); + + assertEquals(Optional.empty(), restarted.address("ep1")); + assertFalse(fixture.leased.contains("10.0.1.20")); + assertFalse(restarted.targetsPort(7001)); + } + + @Test + void aRestartRemovesARelayOfThisFlociThatWasNeverWrittenDown() { + Container survivor = new Container(); + Map labels = Map.of("io.floci.service", "test-endpoint", + "io.floci.resource-id", "ep-lost", "io.floci.owner", "4566"); + setField(survivor, "id", "relay-lost"); + setField(survivor, "labels", labels); + when(fixture.docker.listContainersCmd().withShowAll(true).withLabelFilter(any(Map.class)).exec()) + .thenReturn(List.of(survivor)); + + fixture.relays("test-endpoint", "floci-net").recoverAll(); + + verify(lifecycleManager).removeIfExists("relay-lost"); + } + + @Test + void stoppingAnEndpointNeverServedAndNeverWrittenDownAsksDockerNothing() { + relays.stop("never"); + + verify(lifecycleManager, never()).removeIfExistsStrict(any(String.class)); + } + + @Test + void stoppingAnEndpointRemovesItsRelayAndGivesTheAddressBack() { + relays.serve(relay("ep1", 5432, 7001), null); + + relays.stop("ep1"); + + verify(lifecycleManager).removeIfExistsStrict("relay-1"); + verify(ec2).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + assertEquals(Optional.empty(), relays.address("ep1")); + assertFalse(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + } + + @Test + void aRelayDockerDidNotRemoveStaysTrackedWithItsAddressUntilALaterStopRemovesIt() { + relays.serve(relay("ep1", 5432, 7001), null); + doThrow(new IllegalStateException("daemon down")).when(lifecycleManager).removeIfExistsStrict("relay-1"); + + assertThrows(IllegalStateException.class, () -> relays.stop("ep1")); + + assertEquals(Optional.of("10.0.1.20"), relays.address("ep1")); + assertTrue(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + verify(ec2, never()).releaseVpcPrivateIp(any(), any(), any(), any()); + + doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(lifecycleManager).removeIfExistsStrict("relay-1"); + relays.stop("ep1"); + + assertEquals(Optional.empty(), relays.address("ep1")); + verify(ec2).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + } + + @Test + void anEndpointWhoseOldRelayDockerDidNotRemoveIsNotServedAgain() { + relays.serve(relay("ep1", 5432, 7001), null); + doThrow(new IllegalStateException("daemon down")).when(lifecycleManager).removeIfExistsStrict("relay-1"); + + assertThrows(IllegalStateException.class, () -> relays.serve(relay("ep1", 5432, 7002), null)); + + verify(lifecycleManager, times(1)).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + assertEquals(Optional.of("10.0.1.20"), relays.address("ep1")); + } + + @Test + void stoppingEveryRelayCarriesOnPastOneDockerDidNotRemove() { + relays.serve(relay("ep1", 5432, 7001), null); + relays.serve(relay("ep2", 5432, 7002), null); + doThrow(new IllegalStateException("daemon down")).when(lifecycleManager).removeIfExistsStrict("relay-1"); + + relays.stopAll(); + + verify(lifecycleManager).removeIfExistsStrict("relay-2"); + assertEquals(Optional.empty(), relays.address("ep2")); + assertEquals(Optional.of("10.0.1.20"), relays.address("ep1")); + } + + @Test + void stoppingEveryRelayRemovesEachOne() { + relays.serve(relay("ep1", 5432, 7001), null); + relays.serve(relay("ep2", 5432, 7002), null); + + relays.stopAll(); + + verify(lifecycleManager).removeIfExistsStrict("relay-1"); + verify(lifecycleManager).removeIfExistsStrict("relay-2"); + assertFalse(relays.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + } + + @Test + void stoppingAnEndpointNoRelayServesRemovesNothing() { + relays.stop("unknown"); + relays.stop(null); + + verify(lifecycleManager, never()).removeIfExistsStrict(any(String.class)); + verify(ec2, never()).releaseVpcPrivateIp(any(), any(), any(), any()); + } + + private static VpcAddressRelays.Relay relay(String id, int port, int targetPort) { + return new VpcAddressRelays.Relay(id, ACCOUNT, REGION, "vpc-1", "subnet-1", port, + "host.docker.internal", targetPort, "endpoint " + id); + } + + private static void setField(Container container, String name, Object value) { + try { + Field field = Container.class.getDeclaredField(name); + field.setAccessible(true); + field.set(container, value); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java b/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java index e0cd734f92..9bea9819e8 100644 --- a/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java +++ b/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java @@ -71,6 +71,46 @@ class VpcContainerLeasesTest { assertFalse(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1")); } + @Test + void aRestartTakesBackAnAddressInTheRangeASubstitutedSubnetLeasesFrom() { + Subnet subnet = new Subnet(); + subnet.setSubnetId("subnet-1"); + subnet.setVpcId("vpc-1"); + subnet.setCidrBlock("172.17.0.0/24"); + when(ec2.describeSubnets(REGION, List.of("subnet-1"), Map.of())).thenReturn(List.of(subnet)); + // The declared range is the Docker bridge's, so the VPC's network uses another. + when(ec2.effectiveSubnetCidr(ACCOUNT, REGION, "subnet-1")).thenReturn(Optional.of("10.255.1.0/24")); + when(ec2.reserveVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.255.1.20")).thenReturn(true); + + Optional lease = leases.reclaim(ACCOUNT, REGION, "subnet-1", "container-1", + List.of("172.17.0.4", "10.255.1.20"), "resource-1"); + + assertEquals(Optional.of("10.255.1.20"), lease.map(VpcContainerLeases.Lease::address)); + verify(ec2, never()).reserveVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "172.17.0.4"); + } + + @Test + void aPreferredAddressTheSubnetStillHasIsTakenBack() { + when(ec2.reserveVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.31")).thenReturn(true); + when(ec2.attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "10.0.1.31")) + .thenReturn(Optional.of("vpc-net")); + + assertEquals("10.0.1.31", leases.join(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "r1", "10.0.1.31") + .orElseThrow().address()); + + verify(ec2, never()).allocateVpcPrivateIp(anyString(), anyString(), anyString()); + } + + @Test + void aPreferredAddressSomethingElseHoldsGivesWayToTheNextFreeOne() { + when(ec2.reserveVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.31")).thenReturn(false); + when(ec2.attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "10.0.1.20")) + .thenReturn(Optional.of("vpc-net")); + + assertEquals("10.0.1.20", leases.join(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "r1", "10.0.1.31") + .orElseThrow().address()); + } + @Test void aSubnetOutsideTheVpcTheResourceNamesIsNotJoined() { assertTrue(leases.join(ACCOUNT, REGION, "vpc-other", "subnet-1", "c1", "r1").isEmpty()); diff --git a/src/test/java/io/floci/aws/services/ec2/VpcRelayFixture.java b/src/test/java/io/floci/aws/services/ec2/VpcRelayFixture.java new file mode 100644 index 0000000000..04b83d6971 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/VpcRelayFixture.java @@ -0,0 +1,108 @@ +package io.floci.aws.services.ec2; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerSpec; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * {@link VpcAddressRelays} over a mocked EC2 and Docker: EC2 leases the addresses of a Docker-backed subnet, whose + * range is {@code 10.0.1.0/24}, in order from {@code 10.0.1.20}, takes one back once it is released, and attaches any container; Docker starts a relay as + * {@code relay-1}, {@code relay-2}, ... and reports it running until it is removed. The caller tells the EC2 mock which + * VPC a subnet is in, through {@code describeSubnets}. + */ +public final class VpcRelayFixture { + + public final Ec2Service ec2; + public final DockerClient docker; + public final ContainerLifecycleManager lifecycleManager; + public final ContainerBuilder containerBuilder; + public final ContainerBuilder.Builder builder; + public final EmulatorConfig config; + /** The relays Docker has. */ + public final List present = new ArrayList<>(); + /** The addresses EC2 has leased. */ + public final Set leased = new HashSet<>(); + /** Where the relays write themselves down, shared by every relays this fixture builds, as a restart shares it. */ + public final VpcAddressRelays.Placements placements = VpcAddressRelays.Placements.inMemory(); + private int created; + private int nextHost = 20; + + public VpcRelayFixture(Ec2Service ec2) { + this.ec2 = ec2; + doAnswer(invocation -> { + invocation.getArgument(1).run(); + return null; + }).when(ec2).runWithSubnetReferencesHeld(anyString(), any()); + when(ec2.allocateVpcPrivateIp(anyString(), anyString(), anyString())).thenAnswer(invocation -> { + String address = "10.0.1." + nextHost++; + leased.add(address); + return Optional.of(address); + }); + when(ec2.effectiveSubnetCidr(anyString(), anyString(), anyString())).thenReturn(Optional.of("10.0.1.0/24")); + when(ec2.reserveVpcPrivateIp(anyString(), anyString(), anyString(), anyString())) + .thenAnswer(invocation -> leased.add(invocation.getArgument(3))); + doAnswer(invocation -> leased.remove(invocation.getArgument(3))) + .when(ec2).releaseVpcPrivateIp(anyString(), anyString(), anyString(), anyString()); + when(ec2.attachContainerToVpc(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(Optional.of("vpc-net")); + + docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + when(docker.inspectContainerCmd(any())).thenAnswer(invocation -> { + if (!present.contains(invocation.getArgument(0))) { + throw new NotFoundException("gone"); + } + InspectContainerCmd inspect = mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS); + when(inspect.exec().getState().getRunning()).thenReturn(true); + return inspect; + }); + lifecycleManager = mock(ContainerLifecycleManager.class); + when(lifecycleManager.getDockerClient()).thenReturn(docker); + startsRelaysNormally(); + doAnswer(invocation -> present.remove(invocation.getArgument(0))) + .when(lifecycleManager).removeIfExistsStrict(any(String.class)); + + builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.build()).thenReturn(new ContainerSpec("alpine/socat")); + containerBuilder = mock(ContainerBuilder.class); + when(containerBuilder.newContainer(anyString())).thenReturn(builder); + config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.docker().resourceNamespace()).thenReturn(Optional.empty()); + when(config.port()).thenReturn(4566); + } + + /** Docker starts each relay as {@code relay-1}, {@code relay-2}, ..., as it does until a test says otherwise. */ + public void startsRelaysNormally() { + doAnswer(invocation -> { + String id = "relay-" + ++created; + invocation.>getArgument(1).accept(id); + present.add(id); + return new ContainerLifecycleManager.ContainerInfo(id, Map.of()); + }).when(lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + } + + /** Relays for {@code service}'s endpoints, on {@code network}, or Floci's default network when null. */ + public VpcAddressRelays relays(String service, String network) { + return new VpcAddressRelays(new VpcContainerLeases(ec2, "Test endpoint", () -> docker), + containerBuilder, lifecycleManager, config, service, "alpine/socat", network, placements); + } +} diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java index ce313ea22e..74a30fb2d4 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java @@ -346,10 +346,13 @@ class EcsContainerManagerLifecycleTest { doThrow(new IllegalStateException("busy again")).when(lifecycle).removeVolumeStrict("alpha"); assertFalse(manager.removeLeftoverTaskVolumes("current")); }); + // The removals run on this thread; another ECS test running beside this one logs through the same logger. + long thisThread = Thread.currentThread().threadId(); assertEquals(List.of(Level.WARNING.intValue(), Level.WARNING.intValue(), Level.FINE.intValue(), Level.FINE.intValue(), Level.FINE.intValue(), Level.WARNING.intValue(), Level.FINE.intValue()), - records.stream().map(record -> record.getLevel().intValue()).toList()); + records.stream().filter(record -> record.getLongThreadID() == thisThread) + .map(record -> record.getLevel().intValue()).toList()); verify(lifecycle, times(4)).removeVolumeStrict("alpha"); verify(lifecycle, times(4)).removeVolumeStrict("beta"); verify(lifecycle, never()).removeVolume(anyString()); diff --git a/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java b/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java index 4762053411..b429f392eb 100644 --- a/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java +++ b/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java @@ -147,6 +147,8 @@ class MwaaEnvironmentManagerTest { subnet.setVpcId(vpcId); subnet.setCidrBlock("172.31.0.0/20"); when(ec2Service.describeSubnets("us-east-1", List.of(subnetId), Map.of())).thenReturn(List.of(subnet)); + when(ec2Service.effectiveSubnetCidr(anyString(), eq("us-east-1"), eq(subnetId))) + .thenReturn(Optional.of("172.31.0.0/20")); } private void airflowContainerStarts() { diff --git a/src/test/java/io/floci/aws/services/rds/RdsDnsRecordSourceTest.java b/src/test/java/io/floci/aws/services/rds/RdsDnsRecordSourceTest.java new file mode 100644 index 0000000000..e5b70b4aca --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsDnsRecordSourceTest.java @@ -0,0 +1,83 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.core.common.dns.DnsAnswer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +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. */ +class RdsDnsRecordSourceTest { + + private static final String NAME = "db1.abcdefghijkl.us-east-1.rds.amazonaws.com"; + + private RdsEndpointAddresses endpointAddresses; + private RdsDnsRecordSource source; + + @BeforeEach + void setUp() { + endpointAddresses = mock(RdsEndpointAddresses.class); + when(endpointAddresses.enabled()).thenReturn(true); + when(endpointAddresses.names(NAME)).thenReturn(true); + when(endpointAddresses.addressOf(NAME)).thenReturn(Optional.of("10.0.1.20")); + source = new RdsDnsRecordSource(endpointAddresses); + } + + @Test + void aServedEndpointResolvesToItsAddress() { + DnsAnswer answer = source.resolveAuthoritative(NAME, 1).orElseThrow(); + + assertEquals(List.of("10.0.1.20"), answer.addresses()); + assertEquals(List.of("10.0.1.20"), source.resolveAuthoritative(NAME + ".", 1).orElseThrow().addresses()); + } + + @Test + void anEndpointHasNoIpv6Address() { + DnsAnswer answer = source.resolveAuthoritative(NAME, 28).orElseThrow(); + + assertTrue(answer.isEmpty()); + assertTrue(answer.nameExists()); + } + + @Test + void aStoppedInstancesNameHasNoAddress() { + when(endpointAddresses.addressOf(NAME)).thenReturn(Optional.empty()); + + DnsAnswer answer = source.resolveAuthoritative(NAME, 1).orElseThrow(); + + assertTrue(answer.isEmpty()); + assertTrue(answer.nameExists()); + } + + @Test + void aNameNoInstanceIsServedUnderIsLeftToTheOtherSources() { + assertFalse(source.resolveAuthoritative("other.abcdefghijkl.us-east-1.rds.amazonaws.com", 1).isPresent()); + assertFalse(source.resolveIpv4(NAME).isPresent()); + } + + @Test + void aNameOutsideRdsIsNotLookedUp() { + assertFalse(source.resolveAuthoritative("sqs.us-east-1.amazonaws.com", 1).isPresent()); + + verify(endpointAddresses, never()).names(anyString()); + } + + @Test + void nothingIsLookedUpWithEndpointsInTheirVpcOff() { + when(endpointAddresses.enabled()).thenReturn(false); + + assertFalse(source.resolveAuthoritative(NAME, 1).isPresent()); + + verify(endpointAddresses, never()).names(anyString()); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java new file mode 100644 index 0000000000..3b7a960415 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java @@ -0,0 +1,277 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsEndpoints; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.docker.DockerHostResolver; +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.DbEndpoint; +import io.floci.aws.services.rds.model.DbInstance; +import io.floci.aws.services.rds.model.DbInstanceStatus; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doThrow; +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. */ +class RdsEndpointAddressesTest { + + private static final String ACCOUNT = "123456789012"; + private static final String REGION = "us-east-1"; + + private EmulatorConfig config; + private VpcRelayFixture fixture; + private RdsEndpointAddresses addresses; + private DockerHostResolver hostResolver; + + @BeforeEach + void setUp() { + config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().rds().endpointsInVpc()).thenReturn(true); + when(config.services().rds().mock()).thenReturn(false); + when(config.services().ec2().vpcNetworks().enabled()).thenReturn(true); + when(config.services().ec2().mock()).thenReturn(false); + Ec2Service ec2 = mock(Ec2Service.class); + for (String subnetId : List.of("subnet-a", "subnet-b")) { + Subnet subnet = new Subnet(); + subnet.setSubnetId(subnetId); + subnet.setVpcId("vpc-1"); + when(ec2.describeSubnets(REGION, List.of(subnetId), Map.of())).thenReturn(List.of(subnet)); + } + fixture = new VpcRelayFixture(ec2); + hostResolver = mock(DockerHostResolver.class); + when(hostResolver.resolve()).thenReturn("host.docker.internal"); + when(hostResolver.resolveOn(any())).thenReturn("host.docker.internal"); + addresses = new RdsEndpointAddresses(config, new RegionResolver(REGION, ACCOUNT), hostResolver, + fixture.relays(RdsEndpointAddresses.SERVICE, null)); + } + + @Test + void anInstanceIsServedInTheSubnetOfItsAvailabilityZone() { + DbInstance instance = instance("db1", "us-east-1b", null); + + assertTrue(addresses.assign(instance)); + + assertEquals("subnet-b", instance.getVpcEndpointSubnetId()); + assertTrue(RdsEndpointAddresses.inVpc(instance)); + assertNull(instance.getVpcEndpointAddress()); + } + + @Test + void anInstanceWithNoSubnetInItsZoneIsServedInTheFirstSubnetOfItsGroup() { + DbInstance instance = instance("db1", "us-east-1c", null); + + assertTrue(addresses.assign(instance)); + + assertEquals("subnet-a", instance.getVpcEndpointSubnetId()); + } + + @Test + void endpointsStayOnFloci() { + DbInstance off = instance("off", "us-east-1a", null); + when(config.services().rds().endpointsInVpc()).thenReturn(false); + assertFalse(addresses.assign(off)); + + when(config.services().rds().endpointsInVpc()).thenReturn(true); + when(config.services().rds().mock()).thenReturn(true); + assertFalse(addresses.assign(off)); + + when(config.services().rds().mock()).thenReturn(false); + when(config.services().ec2().vpcNetworks().enabled()).thenReturn(false); + assertFalse(addresses.assign(off)); + + when(config.services().ec2().vpcNetworks().enabled()).thenReturn(true); + when(config.services().ec2().mock()).thenReturn(true); + assertFalse(addresses.assign(off)); + + when(config.services().ec2().mock()).thenReturn(false); + DbInstance noSubnet = instance("nosubnet", "us-east-1a", null); + noSubnet.setSubnetAvailabilityZones(new LinkedHashMap<>()); + assertFalse(addresses.assign(noSubnet)); + + assertFalse(RdsEndpointAddresses.inVpc(off)); + assertFalse(RdsEndpointAddresses.inVpc(noSubnet)); + } + + @Test + void theEndpointIsTheInstanceNameRdsGivesItOnThePortItServes() { + DbInstance postgres = instance("App-DB", "us-east-1a", null); + DbInstance mysql = instance("other", "us-east-1a", null); + mysql.setEngine(DatabaseEngine.MYSQL); + DbInstance requested = instance("custom", "us-east-1a", 6543); + + assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("app-db", ACCOUNT, REGION), 5432), + RdsEndpointAddresses.endpoint(postgres, ACCOUNT, REGION)); + assertEquals(3306, RdsEndpointAddresses.endpoint(mysql, ACCOUNT, REGION).port()); + assertEquals(6543, RdsEndpointAddresses.endpoint(requested, ACCOUNT, REGION).port()); + } + + @Test + void servingRelaysThePortTheInstanceServesToItsProxyAndRecordsTheAddress() { + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + + addresses.serve(instance, ACCOUNT, REGION, 7004); + + assertEquals("10.0.1.20", instance.getVpcEndpointAddress()); + assertTrue(addresses.serving(instance)); + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:7004,nodelay")); + verify(fixture.ec2).attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-a", "relay-1", "10.0.1.20"); + } + + @Test + void aRelayReachesTheProxyAtFlocisAddressOnTheNetworkItJoins() { + when(fixture.containerBuilder.resolveDockerNetwork(Optional.empty())).thenReturn(Optional.of("rds-net")); + when(hostResolver.resolveOn("rds-net")).thenReturn("172.30.0.5"); + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + + addresses.serve(instance, ACCOUNT, REGION, 7004); + + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:172.30.0.5:7004,nodelay")); + } + + @Test + void twoInstancesServeTheSamePortEachAtItsOwnAddress() { + DbInstance first = instance("first", "us-east-1a", 5432); + DbInstance second = instance("second", "us-east-1a", 5432); + addresses.assign(first); + addresses.assign(second); + + addresses.serve(first, ACCOUNT, REGION, 7001); + addresses.serve(second, ACCOUNT, REGION, 7002); + + assertEquals("10.0.1.20", first.getVpcEndpointAddress()); + assertEquals("10.0.1.21", second.getVpcEndpointAddress()); + assertEquals(5432, RdsEndpointAddresses.endpoint(first, ACCOUNT, REGION).port()); + assertEquals(5432, RdsEndpointAddresses.endpoint(second, ACCOUNT, REGION).port()); + } + + @Test + void aStoppedEndpointIsServedAgainAtTheAddressItHeld() { + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + addresses.serve(instance, ACCOUNT, REGION, 7001); + + addresses.stop(instance); + assertFalse(addresses.serving(instance)); + assertEquals("10.0.1.20", instance.getVpcEndpointAddress()); + addresses.serve(instance, ACCOUNT, REGION, 7001); + + assertEquals("10.0.1.20", instance.getVpcEndpointAddress()); + verify(fixture.ec2).attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-a", "relay-2", "10.0.1.20"); + } + + @Test + void anEndpointTakenOutOfItsVpcLosesItsRelayAndAddress() { + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + addresses.serve(instance, ACCOUNT, REGION, 7001); + + addresses.unassign(instance); + + assertFalse(RdsEndpointAddresses.inVpc(instance)); + assertNull(instance.getVpcEndpointSubnetId()); + assertNull(instance.getVpcEndpointAddress()); + assertFalse(fixture.leased.contains("10.0.1.20")); + } + + @Test + void aServedEndpointIsKnownByItsNameWithItsAddressAndAStoppedOneWithNone() { + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + String host = AwsEndpoints.rdsInstanceHost("db1", ACCOUNT, REGION); + assertFalse(addresses.names(host)); + + addresses.serve(instance, ACCOUNT, REGION, 7001); + assertTrue(addresses.names(host.toUpperCase())); + assertEquals(Optional.of("10.0.1.20"), addresses.addressOf(host)); + + addresses.stop(instance); + assertTrue(addresses.names(host)); + assertEquals(Optional.empty(), addresses.addressOf(host)); + + addresses.forget(instance); + assertFalse(addresses.names(host)); + } + + @Test + void anEndpointRememberedUnderANewIdentifierLosesItsOldName() { + DbInstance instance = instance("old-name", "us-east-1a", null); + addresses.assign(instance); + addresses.serve(instance, ACCOUNT, REGION, 7001); + + instance.setDbInstanceIdentifier("new-name"); + addresses.remember(instance, ACCOUNT, REGION); + + assertFalse(addresses.names(AwsEndpoints.rdsInstanceHost("old-name", ACCOUNT, REGION))); + assertEquals(Optional.of("10.0.1.20"), + addresses.addressOf(AwsEndpoints.rdsInstanceHost("new-name", ACCOUNT, REGION))); + } + + @Test + void anEndpointWhoseRelayDockerDidNotRemoveKeepsItsName() { + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + addresses.serve(instance, ACCOUNT, REGION, 7001); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + + assertThrows(IllegalStateException.class, () -> addresses.unassign(instance)); + + assertTrue(RdsEndpointAddresses.inVpc(instance)); + assertTrue(addresses.names(AwsEndpoints.rdsInstanceHost("db1", ACCOUNT, REGION))); + assertTrue(addresses.serving(instance)); + } + + @Test + void aServedEndpointKeepsItsSubnetAndVpcInUseForTheAccountThatOwnsIt() { + DbInstance instance = instance("db1", "us-east-1a", null); + addresses.assign(instance); + addresses.serve(instance, ACCOUNT, REGION, 7001); + + assertTrue(addresses.hasSubnetDependency(REGION, "subnet-a")); + assertTrue(addresses.hasVpcDependency(REGION, "vpc-1")); + assertFalse(addresses.hasSubnetDependency(REGION, "subnet-b")); + + addresses.stopManagedContainers(); + + assertFalse(addresses.hasSubnetDependency(REGION, "subnet-a")); + assertFalse(addresses.serving(instance)); + } + + 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); + instance.setDbInstanceArn("arn:aws:rds:" + REGION + ":" + ACCOUNT + ":db:" + id); + instance.setVpcId("vpc-1"); + instance.setAvailabilityZone(availabilityZone); + Map subnets = new LinkedHashMap<>(); + subnets.put("subnet-a", "us-east-1a"); + subnets.put("subnet-b", "us-east-1b"); + instance.setSubnetAvailabilityZones(subnets); + instance.setRequestedPort(requestedPort); + return instance; + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..eb99ae515e --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java @@ -0,0 +1,169 @@ +package io.floci.aws.services.rds; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.HostConfig; +import io.floci.aws.core.common.AwsEndpoints; +import io.floci.aws.core.common.dns.DnsAnswer; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.services.ec2.net.VpcNetworkManager; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.DockerAvailability; +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.BeforeEach; +import org.junit.jupiter.api.Test; +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.DBInstance; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * #6273: with {@code endpoints-in-vpc} on, two real PostgreSQL instances both serve 5432, each at its own address in + * 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. + * + *

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. + */ +@QuarkusTest +@TestProfile(RdsEndpointsInVpcDockerNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class RdsEndpointsInVpcDockerNightlyIntegrationTest { + + /** Endpoints in the VPC, real databases, and Docker-backed VPC networks under a namespace of their own. */ + public static final class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.rds.endpoints-in-vpc", "true", + "floci.services.rds.mock", "false", + "floci.services.ec2.mock", "false", + "floci.services.ec2.vpc-networks.enabled", "true", + "floci.network.security-group-enforcement.enabled", "false", + "floci.docker.resource-namespace", "rds-endpoints-in-vpc-it"); + } + } + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String PASSWORD = "password123"; + + @Inject + DockerClient dockerClient; + + @Inject + RdsService rdsService; + + @Inject + RdsDnsRecordSource dnsRecordSource; + + @Inject + VpcNetworkManager vpcNetworkManager; + + @BeforeEach + void requireDocker() { + assumeTrue(DockerAvailability.answers(dockerClient), "Docker must be available for the endpoints-in-VPC check"); + } + + @Test + void twoInstancesServe5432AtTheirOwnAddressesUnderTheirRdsNames() throws Exception { + 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)); + } + String firstName = AwsEndpoints.rdsInstanceHost(first, ACCOUNT, REGION); + String secondName = AwsEndpoints.rdsInstanceHost(second, ACCOUNT, REGION); + for (String id : List.of(first, second)) { + DBInstance described = rds.describeDBInstances(r -> r.dbInstanceIdentifier(id)) + .dbInstances().getFirst(); + assertEquals(AwsEndpoints.rdsInstanceHost(id, ACCOUNT, REGION), described.endpoint().address()); + assertEquals(5432, described.endpoint().port()); + } + String firstAddress = address(firstName); + String secondAddress = address(secondName); + assertNotEquals(firstAddress, secondAddress); + + vpcId = rdsService.getDbInstance(first).getVpcId(); + String network = vpcNetworkManager.networkNameFor(ACCOUNT, REGION, vpcId).orElseThrow(); + String image = dockerClient.inspectContainerCmd(rdsService.getDbInstance(first).getContainerId()) + .exec().getConfig().getImage(); + client = dockerClient.createContainerCmd(image) + .withEntrypoint("sleep") + .withCmd("600") + .withHostConfig(HostConfig.newHostConfig().withNetworkMode(network)) + .exec().getId(); + dockerClient.startContainerCmd(client).exec(); + + assertEquals("first", psql(client, firstAddress, + "CREATE TABLE IF NOT EXISTS marker(v text PRIMARY KEY); " + + "INSERT INTO marker VALUES ('first') ON CONFLICT DO NOTHING; SELECT v FROM marker;")); + assertEquals("0", psql(client, secondAddress, + "SELECT count(*) FROM pg_tables WHERE tablename = 'marker';")); + + rds.stopDBInstance(r -> r.dbInstanceIdentifier(first)); + assertTrue(dnsRecordSource.resolveAuthoritative(firstName, 1).orElseThrow().isEmpty(), + "a stopped instance's name has no address"); + rds.startDBInstance(r -> r.dbInstanceIdentifier(first)); + assertEquals(firstAddress, address(firstName)); + assertEquals("first", psql(client, firstAddress, "SELECT v FROM marker;")); + } finally { + for (String id : List.of(first, second)) { + try { + rds.deleteDBInstance(r -> r.dbInstanceIdentifier(id).skipFinalSnapshot(true)); + } catch (RuntimeException ignored) { + // Not created, or already gone: nothing of it is left to remove. + } + } + } + } finally { + if (client != null) { + dockerClient.removeContainerCmd(client).withForce(true).exec(); + } + if (vpcId != null) { + vpcNetworkManager.deleteVpcNetwork(ACCOUNT, REGION, vpcId); + } + } + } + + private String address(String name) { + DnsAnswer answer = dnsRecordSource.resolveAuthoritative(name, 1).orElseThrow(); + assertEquals(1, answer.addresses().size(), name + " must resolve to one address"); + return answer.addresses().getFirst(); + } + + /** Runs {@code sql} as the master user through {@code address}:5432 from the client, once the endpoint answers. */ + private String psql(String client, String address, String sql) { + String[] command = {"env", "PGPASSWORD=" + PASSWORD, "PGCONNECT_TIMEOUT=3", + "PGOPTIONS=-c client_min_messages=warning", "psql", "-h", address, "-p", "5432", + "-U", "admin", "-d", "appdb", "-tAq", "-c", sql}; + return await("psql through " + address).atMost(Duration.ofMinutes(2)).pollInterval(Duration.ofSeconds(2)) + .until(() -> { + ContainerExec.Result result = ContainerExec.runMerged(dockerClient, client, command, 30); + return result.exitCode() == 0 ? result.stdout().strip() : null; + }, output -> output != null); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java new file mode 100644 index 0000000000..64a1c54fba --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java @@ -0,0 +1,943 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsEndpoints; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.core.common.docker.DockerHostResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.StorageBackend; +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.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.DbEndpoint; +import io.floci.aws.services.rds.model.DbInstance; +import io.floci.aws.services.rds.model.DbInstanceSettings; +import io.floci.aws.services.rds.model.DbInstanceStatus; +import io.floci.aws.services.rds.model.ReadReplicaRequest; +import io.floci.aws.services.rds.proxy.RdsProxyBinding; +import io.floci.aws.services.rds.proxy.RdsProxyManager; +import io.floci.aws.testing.ParallelLocks; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.mockito.ArgumentCaptor; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +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 + * {@link io.floci.aws.services.ec2.VpcAddressRelays} over a mocked EC2 and Docker. + */ +@ResourceLock(ParallelLocks.PORTS) +class RdsEndpointsInVpcTest { + + private static final String ACCOUNT = "123456789012"; + private static final String REGION = "us-east-1"; + private static final String SUBNET_A = Ec2Service.defaultSubnetId(REGION, "a", "000000000000"); + private static final String SUBNET_B = Ec2Service.defaultSubnetId(REGION, "b", "000000000000"); + private static final String SUBNET_C = "subnet-0c0c0c0c0c0c0c0c0"; + private static final String SUBNET_D = "subnet-0d0d0d0d0d0d0d0d0"; + private static final String SUBNET_E = "subnet-0e0e0e0e0e0e0e0e0"; + private static final String SUBNET_F = "subnet-0f0f0f0f0f0f0f0f0"; + + private EmulatorConfig config; + private RdsContainerManager containerManager; + private RdsProxyManager proxyManager; + private Ec2Service ec2Service; + private VpcRelayFixture fixture; + private DockerHostResolver hostResolver; + private RdsEndpointAddresses endpointAddresses; + private StorageBackend instances; + private RdsService rdsService; + + @BeforeEach + void setUp() { + config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.defaultAccountId()).thenReturn(ACCOUNT); + EmulatorConfig.RdsServiceConfig rds = config.services().rds(); + when(rds.proxyBasePort()).thenReturn(7000); + when(rds.proxyMaxPort()).thenReturn(7099); + when(rds.iamTokenEndpointBinding()).thenReturn(true); + when(rds.mock()).thenReturn(false); + when(rds.endpointsInVpc()).thenReturn(true); + when(rds.defaultSqlServerImage()).thenReturn("mcr.microsoft.com/mssql/server:2022-latest"); + when(config.services().ec2().vpcNetworks().enabled()).thenReturn(true); + when(config.services().ec2().mock()).thenReturn(false); + + containerManager = mock(RdsContainerManager.class); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "10.9.0.5", 5432)); + proxyManager = mock(RdsProxyManager.class); + ec2Service = mock(Ec2Service.class); + when(ec2Service.resolveDefaultVpcId(any())).thenReturn("vpc-default"); + when(ec2Service.describeSubnets(any(), anyList(), any())).thenAnswer(invocation -> { + List ids = invocation.getArgument(1); + // The default VPC's subnets are a and b; c and d are only reached by naming them. + List defaults = List.of(subnet(SUBNET_A, "us-east-1a"), subnet(SUBNET_B, "us-east-1b")); + List all = List.of(defaults.get(0), defaults.get(1), subnet(SUBNET_C, "us-east-1c"), + subnet(SUBNET_D, "us-east-1d"), subnet(SUBNET_E, "us-east-1a", "vpc-other"), + subnet(SUBNET_F, "us-east-1b", "vpc-other")); + return ids == null || ids.isEmpty() ? defaults + : all.stream().filter(subnet -> ids.contains(subnet.getSubnetId())).toList(); + }); + fixture = new VpcRelayFixture(ec2Service); + hostResolver = mock(DockerHostResolver.class); + when(hostResolver.resolve()).thenReturn("host.docker.internal"); + when(hostResolver.resolveOn(any())).thenReturn("host.docker.internal"); + endpointAddresses = newEndpointAddresses(); + instances = new FailingStore(); + rdsService = newService(instances); + } + + @Test + void anInstanceReportsItsRdsNameAndPortAndServesThemAtItsOwnAddress() { + DbInstance instance = create("app", "postgres", 5432); + + String name = AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION); + assertEquals(new DbEndpoint(name, 5432), instance.getEndpoint()); + assertEquals("10.0.1.20", instance.getVpcEndpointAddress()); + assertEquals(instance.getAvailabilityZone(), + instance.getSubnetAvailabilityZones().get(instance.getVpcEndpointSubnetId())); + assertEquals(5432, rdsService.connectablePort(instance)); + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:" + instance.getProxyPort() + ",nodelay")); + ArgumentCaptor binding = ArgumentCaptor.forClass(RdsProxyBinding.class); + verify(proxyManager).startProxy(any(), any(), any(), anyBoolean(), eq(instance.getProxyPort()), any(), + anyInt(), eq(name), any(), any(), any(), any(), binding.capture()); + assertEquals(name, binding.getValue().advertisedHost()); + assertEquals(5432, binding.getValue().publishedPort()); + assertEquals(Optional.of("10.0.1.20"), endpointAddresses.addressOf(name.toUpperCase())); + } + + @Test + void anEndpointInItsVpcIsConnectableOnThePortItReportsWhateverAdvertiseRequestedPortSays() { + when(config.services().rds().advertiseRequestedPort()).thenReturn(true); + + DbInstance instance = create("app", "postgres", 5432); + + assertEquals(5432, rdsService.connectablePort(instance)); + assertEquals(AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION), instance.getEndpoint().address()); + } + + @Test + void twoInstancesBothServe5432EachAtItsOwnAddress() { + DbInstance first = create("first", "postgres", 5432); + DbInstance second = create("second", "postgres", 5432); + + assertEquals(5432, first.getEndpoint().port()); + assertEquals(5432, second.getEndpoint().port()); + assertNotEquals(first.getEndpoint().address(), second.getEndpoint().address()); + assertNotEquals(first.getVpcEndpointAddress(), second.getVpcEndpointAddress()); + assertNotEquals(first.getProxyPort(), second.getProxyPort()); + } + + @Test + void anInstanceCreatedWithoutAPortServesItsEnginesDefault() { + assertEquals(3306, create("mysql-db", "mysql", null).getEndpoint().port()); + assertEquals(5432, create("pg-db", "postgres", null).getEndpoint().port()); + } + + @Test + void aCreateTheSubnetHasNoAddressForFailsAndLeavesNothingBehind() { + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), anyString()); + + assertThrows(IllegalStateException.class, () -> create("app", "postgres", 5432)); + + assertThrows(AwsException.class, () -> rdsService.getDbInstance("app")); + verify(proxyManager).stopProxy(any()); + assertTrue(fixture.present.isEmpty()); + } + + @Test + void aStoppedInstanceKeepsItsNameAndIsServedAgainAtItsAddressWhenStarted() { + DbInstance instance = create("app", "postgres", 5432); + DbEndpoint endpoint = instance.getEndpoint(); + + rdsService.stopDbInstance("app", null, REGION); + DbInstance stopped = rdsService.getDbInstance("app"); + assertEquals(endpoint, stopped.getEndpoint()); + assertFalse(endpointAddresses.serving(stopped)); + assertTrue(fixture.present.isEmpty()); + assertTrue(endpointAddresses.names(endpoint.address())); + assertEquals(Optional.empty(), endpointAddresses.addressOf(endpoint.address())); + + rdsService.startDbInstance("app", REGION); + DbInstance started = rdsService.getDbInstance("app"); + assertEquals(endpoint, started.getEndpoint()); + assertEquals("10.0.1.20", started.getVpcEndpointAddress()); + assertTrue(endpointAddresses.serving(started)); + } + + @Test + void aDeletedInstanceGivesItsAddressBack() { + String subnetId = create("app", "postgres", 5432).getVpcEndpointSubnetId(); + assertTrue(endpointAddresses.hasSubnetDependency(REGION, subnetId)); + + rdsService.deleteDbInstance("app", REGION); + + assertTrue(fixture.present.isEmpty()); + assertFalse(fixture.leased.contains("10.0.1.20")); + assertFalse(endpointAddresses.hasSubnetDependency(REGION, subnetId)); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION))); + } + + @Test + void aDeleteWhoseRelayDockerDoesNotRemoveKeepsTheRecordAndItsPortUntilARetryRemovesIt() { + DbInstance instance = create("app", "postgres", 5432); + int proxyPort = instance.getProxyPort(); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + + assertThrows(IllegalStateException.class, () -> rdsService.deleteDbInstance("app", REGION)); + + assertEquals(DbInstanceStatus.DELETING, rdsService.getDbInstance("app").getStatus()); + assertTrue(endpointAddresses.serving(instance)); + assertNotEquals(proxyPort, create("other", "postgres", 5432).getProxyPort()); + + doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(fixture.lifecycleManager).removeIfExistsStrict("relay-1"); + rdsService.deleteDbInstance("app", REGION); + + assertThrows(AwsException.class, () -> rdsService.getDbInstance("app")); + assertFalse(endpointAddresses.serving(instance)); + assertFalse(fixture.leased.contains("10.0.1.20")); + } + + @Test + void aStopWhoseRelayDockerDoesNotRemoveStillStopsAndTheNextStartServesAgain() { + DbInstance instance = create("app", "postgres", 5432); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + + rdsService.stopDbInstance("app", null, REGION); + + assertEquals(DbInstanceStatus.STOPPED, rdsService.getDbInstance("app").getStatus()); + rdsService.startDbInstance("app", REGION); + assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbInstance("app").getStatus()); + assertTrue(endpointAddresses.serving(instance)); + } + + @Test + void aMoveWhoseOldRelayCannotBeRemovedKeepsItWithTheInstanceUntilADeleteRemovesIt() { + DbInstance instance = create("app", "postgres", 5432); + String oldRelayId = instance.getVpcEndpointId(); + int proxyPort = instance.getProxyPort(); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + + DbInstance moved = rdsService.getDbInstance("app"); + assertEquals(List.of(oldRelayId), moved.getStaleVpcEndpointIds()); + assertTrue(List.of(SUBNET_C, SUBNET_D).contains(moved.getVpcEndpointSubnetId())); + assertThrows(IllegalStateException.class, () -> rdsService.deleteDbInstance("app", REGION)); + assertEquals(DbInstanceStatus.DELETING, rdsService.getDbInstance("app").getStatus()); + assertNotEquals(proxyPort, create("other", "postgres", 5432).getProxyPort()); + + doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(fixture.lifecycleManager).removeIfExistsStrict("relay-1"); + rdsService.deleteDbInstance("app", REGION); + + assertThrows(AwsException.class, () -> rdsService.getDbInstance("app")); + assertFalse(fixture.present.contains("relay-1")); + } + + @Test + void aFailedMoveWhoseNewRelayMayHaveStartedKeepsItWithTheInstance() { + DbInstance instance = create("app", "postgres", 5432); + String oldAddress = instance.getVpcEndpointAddress(); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + doAnswer(invocation -> { + invocation.>getArgument(1).accept("relay-x"); + fixture.present.add("relay-x"); + throw new IllegalStateException("start reply lost"); + }).when(fixture.lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-x"); + + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + + DbInstance kept = rdsService.getDbInstance("app"); + assertEquals(oldAddress, kept.getVpcEndpointAddress()); + assertEquals(1, kept.getStaleVpcEndpointIds().size()); + assertTrue(endpointAddresses.serving(kept)); + } + + @Test + void aRestartRemovesTheRelaysAnInstanceMovedOff() { + create("app", "postgres", 5432); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + assertEquals(1, rdsService.getDbInstance("app").getStaleVpcEndpointIds().size()); + // Stopped, it is not served at the restart: the restart itself removes the relay. + rdsService.stopDbInstance("app", null, REGION); + doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(fixture.lifecycleManager).removeIfExistsStrict("relay-1"); + + newService(instances, newEndpointAddresses()).restorePersistedRuntime(); + + assertEquals(List.of(), newServiceView().getDbInstance("app").getStaleVpcEndpointIds()); + } + + @Test + void aRelayAMoveLeftThatARestartCannotRemoveKeepsItsOldSubnetInUse() { + DbInstance instance = create("app", "postgres", 5432); + String oldSubnet = instance.getVpcEndpointSubnetId(); + String oldRelayName = ContainerStorageHelper.dockerName(fixture.config, + RdsEndpointAddresses.SERVICE + "-" + instance.getVpcEndpointId()); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + rdsService.stopDbInstance("app", null, REGION); + // The process ends: its leases go with it, and the relay Docker would not remove is left running. + fixture.leased.clear(); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict(oldRelayName); + RdsEndpointAddresses restarted = newEndpointAddresses(); + + newService(instances, restarted).restorePersistedRuntime(); + + assertTrue(restarted.hasSubnetDependency(REGION, oldSubnet)); + assertTrue(fixture.leased.contains("10.0.1.20")); + assertEquals(1, newServiceView().getDbInstance("app").getStaleVpcEndpointIds().size()); + } + + @Test + void theNextStartRemovesTheRelaysAnInstanceMovedOff() { + create("app", "postgres", 5432); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + rdsService.stopDbInstance("app", null, REGION); + doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(fixture.lifecycleManager).removeIfExistsStrict("relay-1"); + + rdsService.startDbInstance("app", REGION); + + assertEquals(List.of(), rdsService.getDbInstance("app").getStaleVpcEndpointIds()); + assertFalse(fixture.present.contains("relay-1")); + } + + @Test + void aFailedCreateWhoseRelayDockerDoesNotRemoveKeepsTheRecordAndItsPort() { + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + ((FailingStore) instances).failNextAvailableWrite = true; + + assertThrows(IllegalStateException.class, () -> create("app", "postgres", 5432)); + + DbInstance kept = rdsService.getDbInstance("app"); + assertTrue(endpointAddresses.serving(kept)); + assertNotEquals(0, kept.getProxyPort(), "the record keeps the port its relay forwards to"); + assertNotEquals(kept.getProxyPort(), create("other", "postgres", 5432).getProxyPort()); + } + + @Test + void anInstanceWhoseRelayCannotBeRemovedAfterTheSettingIsTurnedOffIsNotServed() { + DbInstance instance = create("app", "postgres", 5432); + // Floci ends without removing the relay, which stays written down. + when(config.services().rds().endpointsInVpc()).thenReturn(false); + String relayName = ContainerStorageHelper.dockerName(fixture.config, + RdsEndpointAddresses.SERVICE + "-" + instance.getVpcEndpointId()); + // Taking the relay up and taking it out of the VPC fail; a relay started after them would start. + doThrow(new IllegalStateException("daemon down")).doThrow(new IllegalStateException("daemon down")) + .doNothing().when(fixture.lifecycleManager).removeIfExistsStrict(relayName); + RdsEndpointAddresses restarted = newEndpointAddresses(); + clearInvocations(fixture.lifecycleManager); + + newService(instances, restarted).restorePersistedRuntime(); + + DbInstance restored = newServiceView().getDbInstance("app"); + assertTrue(RdsEndpointAddresses.inVpc(restored)); + // The relay left behind is held with its address, and no new one starts while the setting is off. + verify(fixture.lifecycleManager, never()).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + } + + @Test + void aRestartRemovesTheRelayAnEarlierFlociLeftRunning() { + DbInstance instance = create("app", "postgres", 5432); + String relayName = ContainerStorageHelper.dockerName(fixture.config, + RdsEndpointAddresses.SERVICE + "-" + instance.getVpcEndpointId()); + clearInvocations(fixture.lifecycleManager); + + newService(instances, newEndpointAddresses()).restorePersistedRuntime(); + + verify(fixture.lifecycleManager, atLeastOnce()).removeIfExistsStrict(relayName); + } + + @Test + void aRelayARestartCannotRemoveKeepsItsAddressAndSubnetUntilTheNextStartRemovesIt() { + DbInstance instance = create("app", "postgres", 5432); + String subnetId = instance.getVpcEndpointSubnetId(); + String relayName = ContainerStorageHelper.dockerName(fixture.config, + RdsEndpointAddresses.SERVICE + "-" + instance.getVpcEndpointId()); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + rdsService.stopDbInstance("app", null, REGION); + // The process ends: its leases go with it, and the relay Docker would not remove is left running. + fixture.leased.clear(); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict(relayName); + RdsEndpointAddresses restarted = newEndpointAddresses(); + RdsService restartedService = newService(instances, restarted); + + restartedService.restorePersistedRuntime(); + + assertTrue(restarted.hasSubnetDependency(REGION, subnetId)); + assertTrue(fixture.leased.contains("10.0.1.20")); + + doNothing().when(fixture.lifecycleManager).removeIfExistsStrict(relayName); + restartedService.startDbInstance("app", REGION); + + DbInstance started = restartedService.getDbInstance("app"); + assertEquals("10.0.1.20", started.getVpcEndpointAddress()); + assertTrue(restarted.serving(started)); + } + + @Test + void aPortARelayMayStillForwardToIsNotGivenToAnotherInstance() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + DbInstance instance = create("app", "postgres", 5432); + instance.setEndpoint(null); + instances.put("us-east-1::app", instance); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "10.9.0.5", 5432)); + doAnswer(invocation -> { + invocation.>getArgument(1).accept("relay-x"); + fixture.present.add("relay-x"); + throw new IllegalStateException("start reply lost"); + }).when(fixture.lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-x"); + + assertThrows(IllegalStateException.class, () -> rdsService.ensureInstanceBackend("app", REGION)); + fixture.startsRelaysNormally(); + + int relayTarget = fixture.placements.all().getFirst().relay().targetPort(); + for (int i = 0; i < 3; i++) { + assertNotEquals(relayTarget, create("other-" + i, "postgres", 5432).getProxyPort()); + } + } + + @Test + void aRestartKnowsAStoppedInstancesNameWithNoAddress() { + create("app", "postgres", 5432); + rdsService.stopDbInstance("app", null, REGION); + RdsEndpointAddresses restarted = newEndpointAddresses(); + + newService(instances, restarted).restorePersistedRuntime(); + + String name = AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION); + assertTrue(restarted.names(name)); + assertEquals(Optional.empty(), restarted.addressOf(name)); + } + + @Test + void aRestartServesTheInstanceAgainAtTheAddressItHeld() { + DbInstance instance = create("app", "postgres", 5432); + endpointAddresses.stopManagedContainers(); + assertFalse(fixture.leased.contains("10.0.1.20")); + + newService(instances).restorePersistedRuntime(); + + DbInstance restored = newServiceView().getDbInstance("app"); + assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION), 5432), + restored.getEndpoint()); + assertEquals("10.0.1.20", restored.getVpcEndpointAddress()); + assertTrue(endpointAddresses.serving(restored)); + } + + @Test + void turningTheSettingOffAcrossARestartPutsTheEndpointBackOnFloci() { + create("app", "postgres", 5432); + endpointAddresses.stopManagedContainers(); + when(config.services().rds().endpointsInVpc()).thenReturn(false); + + newService(instances).restorePersistedRuntime(); + + DbInstance restored = newServiceView().getDbInstance("app"); + assertFalse(RdsEndpointAddresses.inVpc(restored)); + assertNull(restored.getVpcEndpointAddress()); + assertEquals(restored.getProxyPort(), restored.getEndpoint().port()); + assertFalse(restored.getEndpoint().address().endsWith(".rds.amazonaws.com")); + } + + @Test + void turningTheSettingOnAcrossARestartPutsAnExistingInstanceInItsVpc() { + when(config.services().rds().endpointsInVpc()).thenReturn(false); + DbInstance before = create("app", "postgres", 5432); + assertFalse(RdsEndpointAddresses.inVpc(before)); + when(config.services().rds().endpointsInVpc()).thenReturn(true); + + newService(instances).restorePersistedRuntime(); + + DbInstance restored = newServiceView().getDbInstance("app"); + assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION), 5432), + restored.getEndpoint()); + assertTrue(endpointAddresses.serving(restored)); + } + + @Test + void anInstanceCreatedWithoutDockerIsServedOnceItsBackendStarts() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + DbInstance instance = create("app", "postgres", 5432); + assertFalse(endpointAddresses.serving(instance)); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "10.9.0.5", 5432)); + + rdsService.ensureInstanceBackend("app", REGION); + + assertTrue(endpointAddresses.serving(rdsService.getDbInstance("app"))); + } + + @Test + void anInstanceMovedToAnotherSubnetGroupIsServedInOneOfItsSubnets() { + DbInstance instance = create("app", "postgres", 5432); + String before = instance.getVpcEndpointAddress(); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + + DbInstance moved = rdsService.getDbInstance("app"); + assertTrue(List.of(SUBNET_C, SUBNET_D).contains(moved.getVpcEndpointSubnetId())); + assertNotEquals(before, moved.getVpcEndpointAddress()); + assertFalse(fixture.leased.contains(before)); + assertFalse(fixture.present.contains("relay-1"), "the relay in the old subnet goes once the new one serves"); + assertTrue(endpointAddresses.serving(moved)); + assertTrue(endpointAddresses.hasSubnetDependency(REGION, moved.getVpcEndpointSubnetId())); + assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION), 5432), + moved.getEndpoint()); + } + + @Test + void aCreateWhoseRecordCannotBeWrittenTakesItsRelayAway() { + ((FailingStore) instances).failNextAvailableWrite = true; + + assertThrows(IllegalStateException.class, () -> create("app", "postgres", 5432)); + + assertTrue(fixture.present.isEmpty()); + assertTrue(fixture.leased.isEmpty()); + } + + @Test + void aRestoreThatFailsAfterServingTakesTheRelayAway() { + create("app", "postgres", 5432); + endpointAddresses.stopManagedContainers(); + ((FailingStore) instances).failNextAvailableWrite = true; + + newService(instances).restorePersistedRuntime(); + + assertTrue(fixture.present.isEmpty()); + assertTrue(fixture.leased.isEmpty()); + } + + @Test + void aBackendStartedOnRetryForARecordWithoutAnEndpointReportsItsName() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + DbInstance instance = create("app", "postgres", 5432); + instance.setEndpoint(null); + instances.put("us-east-1::app", instance); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "10.9.0.5", 5432)); + + rdsService.ensureInstanceBackend("app", REGION); + + assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("app", ACCOUNT, REGION), 5432), + rdsService.getDbInstance("app").getEndpoint()); + } + + @Test + void aStoppedInstanceTakenOutOfItsVpcAcrossARestartReportsTheProxyEndpoint() { + create("app", "postgres", 5432); + rdsService.stopDbInstance("app", null, REGION); + when(config.services().rds().endpointsInVpc()).thenReturn(false); + + newService(instances).restorePersistedRuntime(); + + DbInstance restored = newServiceView().getDbInstance("app"); + assertFalse(RdsEndpointAddresses.inVpc(restored)); + assertEquals(restored.getProxyPort(), restored.getEndpoint().port()); + assertFalse(restored.getEndpoint().address().endsWith(".rds.amazonaws.com")); + } + + @Test + void aStartThatLeavesAPortDsqlNowHoldsKeepsTheNameAndRelaysToTheNewProxyPort() { + DbInstance instance = create("app", "postgres", 5432); + int oldPort = instance.getProxyPort(); + DbEndpoint endpoint = instance.getEndpoint(); + rdsService.stopDbInstance("app", null, REGION); + EmulatorConfig.DsqlServiceConfig dsql = config.services().dsql(); + when(dsql.enabled()).thenReturn(true); + when(dsql.mock()).thenReturn(false); + when(dsql.port()).thenReturn(oldPort); + + rdsService.startDbInstance("app", REGION); + + DbInstance started = rdsService.getDbInstance("app"); + assertNotEquals(oldPort, started.getProxyPort()); + assertEquals(endpoint, started.getEndpoint()); + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:" + started.getProxyPort() + ",nodelay")); + } + + @Test + void aMoveToASubnetWithNoFreeAddressKeepsTheOldEndpointUntilARestartMovesIt() { + DbInstance instance = create("app", "postgres", 5432); + String oldSubnet = instance.getVpcEndpointSubnetId(); + String name = instance.getEndpoint().address(); + rdsService.createDbSubnetGroup("moved", "moved", List.of(SUBNET_C, SUBNET_D)); + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), eq(SUBNET_C)); + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), eq(SUBNET_D)); + + rdsService.modifyDbInstance("app", null, null, "moved", null, REGION); + + DbInstance kept = rdsService.getDbInstance("app"); + assertEquals(oldSubnet, kept.getVpcEndpointSubnetId()); + assertEquals(Optional.of("10.0.1.20"), endpointAddresses.addressOf(name)); + assertTrue(fixture.present.contains("relay-1")); + + endpointAddresses.stopManagedContainers(); + doReturn(Optional.of("10.0.1.40")).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), + eq(SUBNET_C)); + doReturn(Optional.of("10.0.1.41")).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), + eq(SUBNET_D)); + RdsEndpointAddresses restarted = newEndpointAddresses(); + newService(instances, restarted).restorePersistedRuntime(); + + DbInstance moved = newServiceView().getDbInstance("app"); + assertTrue(List.of(SUBNET_C, SUBNET_D).contains(moved.getVpcEndpointSubnetId())); + assertTrue(restarted.serving(moved)); + } + + @Test + void aMoveToAnotherVpcThatCouldNotBeServedIsMadeByTheNextStart() { + DbInstance instance = create("app", "postgres", 5432); + String oldSubnet = instance.getVpcEndpointSubnetId(); + rdsService.createDbSubnetGroup("other", "other", List.of(SUBNET_E, SUBNET_F)); + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), eq(SUBNET_E)); + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), eq(SUBNET_F)); + + rdsService.modifyDbInstance("app", null, null, "other", null, REGION); + + DbInstance kept = rdsService.getDbInstance("app"); + assertEquals("vpc-other", kept.getVpcId()); + assertEquals(oldSubnet, kept.getVpcEndpointSubnetId()); + assertTrue(endpointAddresses.serving(kept)); + + rdsService.stopDbInstance("app", null, REGION); + doReturn(Optional.of("10.0.2.40")).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), + eq(SUBNET_E)); + doReturn(Optional.of("10.0.2.41")).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), + eq(SUBNET_F)); + rdsService.startDbInstance("app", REGION); + + DbInstance started = rdsService.getDbInstance("app"); + assertEquals(DbInstanceStatus.AVAILABLE, started.getStatus()); + assertTrue(List.of(SUBNET_E, SUBNET_F).contains(started.getVpcEndpointSubnetId())); + assertTrue(endpointAddresses.serving(started)); + } + + @Test + void aFailedCreateWhoseRelayMayHaveStartedAndCouldNotBeRemovedKeepsTheRecordAndItsPort() { + doAnswer(invocation -> { + invocation.>getArgument(1).accept("relay-x"); + fixture.present.add("relay-x"); + throw new IllegalStateException("start reply lost"); + }).when(fixture.lifecycleManager).createAndStart(any(ContainerSpec.class), any(Consumer.class)); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-x"); + + assertThrows(IllegalStateException.class, () -> create("app", "postgres", 5432)); + + DbInstance kept = rdsService.getDbInstance("app"); + assertTrue(endpointAddresses.serving(kept)); + assertNotEquals(0, kept.getProxyPort(), "the record keeps the port the relay may forward to"); + } + + @Test + void twoInstancesAskingForTheSamePortInsideTheProxyRangeBothGetIt() { + DbInstance first = create("first", "postgres", 7010); + DbInstance second = create("second", "postgres", 7010); + + assertEquals(7010, first.getEndpoint().port()); + assertEquals(7010, second.getEndpoint().port()); + assertNotEquals(first.getProxyPort(), second.getProxyPort()); + } + + @Test + void aPortOutsideRdsRangeIsStillRefused() { + AwsException refused = assertThrows(AwsException.class, () -> create("app", "postgres", 80)); + + assertEquals("InvalidParameterValue", refused.getErrorCode()); + } + + @Test + void aReadReplicaServesItsSourcesPort() { + create("source", "postgres", 6543); + + DbInstance replica = rdsService.createDbInstanceReadReplica(new ReadReplicaRequest("replica", "source", + null, null, null, null, null, null, null, null, null, null, null, null, null, Map.of()), null); + + assertEquals(6543, replica.getEndpoint().port()); + } + + @Test + void aRestoreFromASnapshotServesTheOriginalInstancesPort() { + when(containerManager.createPostgresSnapshot(any(), any())).thenReturn("-- dump"); + create("source", "postgres", 6543); + rdsService.createDbSnapshot("snap", "source"); + + DbInstance restored = rdsService.restoreDbInstanceFromDbSnapshot("restored", "snap", + null, null, false, null, List.of(), Map.of(), REGION); + + assertEquals(6543, restored.getEndpoint().port()); + } + + @Test + void aGreenInstanceServesItsBluesPort() { + DbInstance blue = rdsService.createDbInstance("bg-blue", "postgres", "16.3", "admin", "password", + "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, + new DbInstanceSettings(null, null, 1, null, null, null), null, 6543); + + BlueGreenDeployment deployment = rdsService.createBlueGreenDeployment( + new RdsService.BlueGreenDeploymentRequest("bg", blue.getDbInstanceArn(), "17.4", null, null, null, + null, null, Map.of()), REGION); + + String greenArn = deployment.getTarget(); + DbInstance green = rdsService.getDbInstance(greenArn.substring(greenArn.lastIndexOf(':') + 1)); + assertEquals(6543, green.getEndpoint().port()); + } + + @Test + void aCreateWhoseContainerFailsWithDockerDownLeavesNoRecordBehind() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException("daemon down")); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict(anyString()); + + assertThrows(IllegalStateException.class, () -> create("app", "postgres", 5432)); + + assertThrows(AwsException.class, () -> rdsService.getDbInstance("app")); + } + + @Test + void aStopOfAnInstanceNeverServedAsksDockerNothingAboutRelays() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + create("app", "postgres", 5432); + clearInvocations(fixture.lifecycleManager); + + rdsService.stopDbInstance("app", null, REGION); + + verify(fixture.lifecycleManager, never()).removeIfExistsStrict(anyString()); + } + + @Test + void anInstanceNotServedYetIsKnownByNameWithNoAddress() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + + DbInstance instance = create("app", "postgres", 5432); + + assertTrue(endpointAddresses.names(instance.getEndpoint().address())); + assertEquals(Optional.empty(), endpointAddresses.addressOf(instance.getEndpoint().address())); + } + + @Test + void aRestartKnowsTheNameOfAnInstanceItCouldNotServe() { + DbInstance instance = create("app", "postgres", 5432); + endpointAddresses.stopManagedContainers(); + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), anyString()); + doReturn(false).when(ec2Service).reserveVpcPrivateIp(anyString(), anyString(), anyString(), anyString()); + RdsEndpointAddresses restarted = newEndpointAddresses(); + + newService(instances, restarted).restorePersistedRuntime(); + + assertTrue(restarted.names(instance.getEndpoint().address())); + assertFalse(restarted.serving(newServiceView().getDbInstance("app"))); + } + + @Test + void aStartWhoseRelayCannotBeServedLeavesTheInstanceStoppedForARetry() { + create("app", "postgres", 5432); + rdsService.stopDbInstance("app", null, REGION); + doReturn(Optional.empty()).when(ec2Service).allocateVpcPrivateIp(anyString(), anyString(), anyString()); + doReturn(false).when(ec2Service).reserveVpcPrivateIp(anyString(), anyString(), anyString(), anyString()); + + assertThrows(IllegalStateException.class, () -> rdsService.startDbInstance("app", REGION)); + + assertEquals(DbInstanceStatus.STOPPED, rdsService.getDbInstance("app").getStatus()); + } + + @Test + void aRestartKeepsTheProxyPortOfAnInstanceWhoseRelayItCouldNotRemove() { + DbInstance instance = create("app", "postgres", 5432); + int proxyPort = instance.getProxyPort(); + String relayName = ContainerStorageHelper.dockerName(fixture.config, + RdsEndpointAddresses.SERVICE + "-" + instance.getVpcEndpointId()); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict(relayName); + + newService(instances, newEndpointAddresses()).restorePersistedRuntime(); + + assertEquals(proxyPort, newServiceView().getDbInstance("app").getProxyPort()); + } + + @Test + void aResetWritesDownTheRelaysItCouldNotRemoveAndForgetsTheNames() { + DbInstance instance = create("app", "postgres", 5432); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + endpointAddresses.stopManagedContainers(); + fixture.placements.all().forEach(fixture.placements::remove); + endpointAddresses.clear(); + + endpointAddresses.afterReset(); + + assertEquals(1, fixture.placements.all().size()); + assertTrue(endpointAddresses.targetsPort(instance.getProxyPort())); + assertFalse(endpointAddresses.names(instance.getEndpoint().address())); + } + + @Test + void mockModeKeepsTheProxyEndpoint() { + when(config.services().rds().mock()).thenReturn(true); + + DbInstance instance = create("app", "postgres", 5432); + + assertFalse(RdsEndpointAddresses.inVpc(instance)); + assertTrue(fixture.present.isEmpty()); + } + + @Test + void aSwitchoverHandsTheBlueNameAndAddressToGreen() { + DbInstance blue = rdsService.createDbInstance("bg-blue", "postgres", "16.3", "admin", "password", + "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, + new DbInstanceSettings(null, null, 1, null, null, null), null, 5432); + String blueAddress = blue.getVpcEndpointAddress(); + BlueGreenDeployment deployment = rdsService.createBlueGreenDeployment( + new RdsService.BlueGreenDeploymentRequest("bg", blue.getDbInstanceArn(), "17.4", null, null, null, + null, null, Map.of()), REGION); + + String greenArn = deployment.getTarget(); + String greenId = greenArn.substring(greenArn.lastIndexOf(':') + 1); + assertTrue(endpointAddresses.names(AwsEndpoints.rdsInstanceHost(greenId, ACCOUNT, REGION))); + + rdsService.switchoverBlueGreenDeployment(deployment.getBlueGreenDeploymentIdentifier(), null, REGION); + + DbInstance production = rdsService.getDbInstance("bg-blue"); + DbInstance retired = rdsService.getDbInstance("bg-blue-old1"); + assertEquals("17.4", production.getEngineVersion()); + assertEquals(new DbEndpoint(AwsEndpoints.rdsInstanceHost("bg-blue", ACCOUNT, REGION), 5432), + production.getEndpoint()); + assertEquals(blueAddress, production.getVpcEndpointAddress()); + assertEquals(AwsEndpoints.rdsInstanceHost("bg-blue-old1", ACCOUNT, REGION), retired.getEndpoint().address()); + assertNotEquals(blueAddress, retired.getVpcEndpointAddress()); + assertEquals(Optional.of(blueAddress), + endpointAddresses.addressOf(AwsEndpoints.rdsInstanceHost("bg-blue", ACCOUNT, REGION))); + assertEquals(Optional.of(retired.getVpcEndpointAddress()), + endpointAddresses.addressOf(AwsEndpoints.rdsInstanceHost("bg-blue-old1", ACCOUNT, REGION))); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsInstanceHost(greenId, ACCOUNT, REGION))); + verify(proxyManager, atLeastOnce()).startProxy(any(), any(), any(), anyBoolean(), + eq(production.getProxyPort()), any(), anyInt(), eq(production.getEndpoint().address()), any(), any(), + any(), any(), any()); + } + + 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, + DbInstanceSettings.defaults(), null, port); + } + + private RdsService newService(StorageBackend store) { + return newService(store, endpointAddresses); + } + + private RdsService newService(StorageBackend store, RdsEndpointAddresses addresses) { + return new RdsService(containerManager, proxyManager, ec2Service, new RegionResolver(REGION, ACCOUNT), + config, store, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), null, null, null, addresses); + } + + /** What a Floci process starts with: no relay served and no name known. */ + private RdsEndpointAddresses newEndpointAddresses() { + return new RdsEndpointAddresses(config, new RegionResolver(REGION, ACCOUNT), hostResolver, + fixture.relays(RdsEndpointAddresses.SERVICE, null)); + } + + private RdsService newServiceView() { + return newService(instances); + } + + /** A store whose next write of an available instance fails, as a full disk would make it. */ + private static final class FailingStore extends InMemoryStorage { + boolean failNextAvailableWrite; + + @Override + public synchronized void put(String key, DbInstance value) { + if (failNextAvailableWrite && value.getStatus() == DbInstanceStatus.AVAILABLE) { + failNextAvailableWrite = false; + throw new IllegalStateException("store refused the write"); + } + super.put(key, value); + } + } + + private static Subnet subnet(String id, String availabilityZone) { + return subnet(id, availabilityZone, "vpc-default"); + } + + private static Subnet subnet(String id, String availabilityZone, String vpcId) { + Subnet subnet = new Subnet(); + subnet.setSubnetId(id); + subnet.setVpcId(vpcId); + subnet.setAvailabilityZone(availabilityZone); + subnet.setCidrBlock("10.0.1.0/24"); + return subnet; + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java index a2db52376f..ee5eb4afad 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java @@ -12321,7 +12321,7 @@ class RdsServiceTest { return new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config, instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups, null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), null, kmsService, eventPublisher); + new InMemoryStorage<>(), null, kmsService, eventPublisher, null); } private RdsService newService(RdsContainerManager containerManager, @@ -12334,7 +12334,7 @@ class RdsServiceTest { return new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config, instances, clusters, parameterGroups, clusterParameterGroups, new InMemoryStorage<>(), secretsManager, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), null, kmsService, eventPublisher); + new InMemoryStorage<>(), null, kmsService, eventPublisher, null); } private RdsService proxyStoreService(