feat(rds): model DB proxies and their target groups (#1813)

* feat(rds): model DB proxies and their target groups

Add DB proxies as first-class RDS resources for both the RDS Query API
and CloudFormation:

- RdsService: two persisted stores plus the proxy lifecycle
  (create/register-targets/describe/delete). A proxy exposes a bare-host
  endpoint on the engine family's default port; in non-mock mode
  registering a target starts an auth relay (via RdsProxyManager) that
  forwards 1:1 to the target cluster/instance, re-armed on restart.
- RdsQueryHandler: CreateDBProxy, DeleteDBProxy, RegisterDBProxyTargets,
  DescribeDBProxyTargetGroups, DescribeDBProxyTargets, and a real
  DescribeDBProxies listing (2014-10-31 XML shapes).
- AwsQueryController: route the six DBProxy actions to RDS.
- CloudFormation: provision/delete AWS::RDS::DBProxy and
  AWS::RDS::DBProxyTargetGroup.

This models DB proxies for provisioning and discovery; it does not add
real connection pooling (the relay forwards 1:1), so it does not close
#1679.

* fix(rds): reserve DB proxy port so same-engine proxies get distinct ports

createDbProxy used the engine family's default port (5432/3306/1433)
directly without reserving it, so two proxies for the same engine got
the identical port and the second relay failed to bind in non-mock
mode. Reserve the default port via reserveOrAllocateProxyPort, falling
back to an allocated pool port when it is already taken — the first
proxy keeps the clean bare-host default port, later ones get a distinct
port, and the persisted port stays canonical across restarts.

* fix(rds): harden DB proxy lifecycle compatibility

* fix(rds): complete DB proxy compatibility hardening

* fix(rds): make DB proxy lifecycle rollback-safe

* fix(rds): default omitted proxy target group

* test(dynamodb): retain Quarkus port for cleanup

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
Alex BannaandAlexander Banna authored and GitHub committed 2026-08-14 23:34:56 -05:00
1 parent 42a79a7fd7
commit e4010ec12f
38 files changed
+9734 -546

No files matched your search

@@ -368,7 +368,10 @@ public class AwsQueryController {
"AddTagsToResource", "ListTagsForResource", "RemoveTagsFromResource",
"CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster",
"CreateDBParameterGroup", "DescribeDBParameterGroups",
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters"
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters",
"DescribeDBProxies", "CreateDBProxy", "ModifyDBProxy", "DeleteDBProxy",
"RegisterDBProxyTargets", "DeregisterDBProxyTargets",
"DescribeDBProxyTargetGroups", "ModifyDBProxyTargetGroup", "DescribeDBProxyTargets"
);
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
@@ -221,6 +221,50 @@ public class ContainerLifecycleManager {
}
}
/**
* Stops and removes a container, failing when Docker cannot confirm removal.
*
* <p>Most emulator shutdown paths intentionally use best-effort cleanup through
* {@link #stopAndRemove(String, Closeable)}. Resource-deletion paths that must retain their
* persisted record for a retry use this stricter variant instead.
*/
public void stopAndRemoveStrict(String containerId, Closeable logStream) {
LOG.infov("Stopping container {0}", containerId);
if (logStream != null) {
try {
logStream.close();
} catch (Exception e) {
LOG.debugv("Error closing log stream: {0}", e.getMessage());
}
}
Exception stopFailure = null;
try {
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
} catch (NotFoundException e) {
LOG.debugv("Container {0} not found (already removed)", containerId);
return;
} catch (Exception e) {
stopFailure = e;
LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage());
}
try {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
LOG.debugv("Removed container {0}", containerId);
} catch (NotFoundException e) {
// Already gone, so cleanup succeeded.
} catch (Exception e) {
IllegalStateException cleanupFailure = new IllegalStateException(
"Failed to remove container " + containerId, e);
if (stopFailure != null) {
cleanupFailure.addSuppressed(stopFailure);
}
throw cleanupFailure;
}
}
/**
* Creates a named volume if it does not already exist. Idempotent — safe to call on every
* container start. Labels the volume {@code floci=true} so
@@ -359,6 +403,18 @@ public class ContainerLifecycleManager {
}
}
/** Removes a named Docker volume and propagates failures so callers can retry safely. */
public void removeVolumeStrict(String volumeName) {
try {
dockerClient.removeVolumeCmd(volumeName).exec();
LOG.debugv("Removed volume {0}", volumeName);
} catch (NotFoundException e) {
// Already gone — nothing to do.
} catch (Exception e) {
throw new IllegalStateException("Failed to remove volume " + volumeName, e);
}
}
/**
* Finds an existing container by name.
*
@@ -459,6 +515,25 @@ public class ContainerLifecycleManager {
}
}
/**
* Removes a container by name, failing when Docker cannot confirm removal.
*
* <p>Callers that are about to reuse a fixed container name must use this variant so a
* daemon failure cannot be mistaken for successful stale-container cleanup.
*
* @param name the container name to remove
*/
public void removeIfExistsStrict(String name) {
try {
dockerClient.removeContainerCmd(name).withForce(true).exec();
LOG.infov("Removed stale container {0}", name);
} catch (NotFoundException e) {
// Not found means the fixed name is available.
} catch (Exception e) {
throw new IllegalStateException("Failed to remove stale container " + name, e);
}
}
/**
* Returns whether the container is currently running. A missing container is treated as
* not-running; any other Docker error (e.g. an inspect timeout under daemon overload) is also
@@ -65,7 +65,14 @@ public class ContainerLogStreamer {
*/
public Closeable attach(String containerId, String logGroup, String logStream,
String region, String logPrefix) {
ensureLogGroupAndStream(logGroup, logStream, region);
return attachForAccount(
null, containerId, logGroup, logStream, region, logPrefix);
}
public Closeable attachForAccount(
String accountId, String containerId, String logGroup, String logStream,
String region, String logPrefix) {
ensureLogGroupAndStreamForAccount(accountId, logGroup, logStream, region);
// Trim trailing whitespace and drop blank lines, then fan each reassembled line out to the
// console logger and CloudWatch Logs.
@@ -73,7 +80,7 @@ public class ContainerLogStreamer {
String trimmed = line.stripTrailing();
if (!trimmed.isEmpty()) {
LOG.infov("[{0}] {1}", logPrefix, trimmed);
forwardToCloudWatchLogs(logGroup, logStream, region, trimmed);
forwardToCloudWatchLogs(accountId, logGroup, logStream, region, trimmed);
}
};
@@ -111,12 +118,17 @@ public class ContainerLogStreamer {
*/
public ResultCallback.Adapter<Frame> execLogCallback(String logGroup, String logStream,
String region, String logPrefix) {
return frameCallback(logGroup, logStream, region, logPrefix);
return frameCallback(null, logGroup, logStream, region, logPrefix);
}
/** Shared frame handling for both the container log stream and exec streams. */
private ResultCallback.Adapter<Frame> frameCallback(String logGroup, String logStream,
String region, String logPrefix) {
/**
* Shared frame handling for both the container log stream and exec streams.
*
* @param accountId account that owns the destination log stream, or {@code null} for the
* default account
*/
private ResultCallback.Adapter<Frame> frameCallback(String accountId, String logGroup, String logStream,
String region, String logPrefix) {
return new ResultCallback.Adapter<>() {
@Override
public void onNext(Frame frame) {
@@ -126,7 +138,7 @@ public class ContainerLogStreamer {
String line = new String(frame.getPayload(), StandardCharsets.UTF_8).stripTrailing();
if (!line.isEmpty()) {
LOG.infov("[{0}] {1}", logPrefix, line);
forwardToCloudWatchLogs(logGroup, logStream, region, line);
forwardToCloudWatchLogs(accountId, logGroup, logStream, region, line);
}
}
};
@@ -136,8 +148,14 @@ public class ContainerLogStreamer {
* Creates a CloudWatch log group and stream if they don't already exist.
*/
public void ensureLogGroupAndStream(String logGroup, String logStream, String region) {
ensureLogGroupAndStreamForAccount(null, logGroup, logStream, region);
}
public void ensureLogGroupAndStreamForAccount(
String accountId, String logGroup, String logStream, String region) {
try {
cloudWatchLogsService.createLogGroup(logGroup, null, null, region);
cloudWatchLogsService.createLogGroupForAccount(
accountId, logGroup, null, null, region);
} catch (AwsException ignored) {
// Already exists
} catch (Exception e) {
@@ -145,7 +163,8 @@ public class ContainerLogStreamer {
}
try {
cloudWatchLogsService.createLogStream(logGroup, logStream, region);
cloudWatchLogsService.createLogStreamForAccount(
accountId, logGroup, logStream, region);
} catch (AwsException ignored) {
// Already exists
} catch (Exception e) {
@@ -164,15 +183,17 @@ public class ContainerLogStreamer {
}
public void streamToCloudWatchLogs(String logGroup, String logStream, String region, String line) {
forwardToCloudWatchLogs(logGroup, logStream, region, line);
forwardToCloudWatchLogs(null, logGroup, logStream, region, line);
}
private void forwardToCloudWatchLogs(String logGroup, String logStream, String region, String line) {
private void forwardToCloudWatchLogs(
String accountId, String logGroup, String logStream, String region, String line) {
try {
Map<String, Object> event = new HashMap<>();
event.put("timestamp", System.currentTimeMillis());
event.put("message", line);
cloudWatchLogsService.putLogEvents(logGroup, logStream, List.of(event), region);
cloudWatchLogsService.putLogEventsForAccount(
accountId, logGroup, logStream, List.of(event), region);
} catch (Exception e) {
LOG.debugv("Could not forward log line to CloudWatch Logs: {0}", e.getMessage());
}
@@ -102,6 +102,15 @@ public final class ContainerStorageHelper {
String fallbackId,
String internalMount) {
String volumeName = resourceName(config, service, volumeId, fallbackId);
applyNamedVolume(builder, lifecycleManager, volumeName, internalMount);
}
/** Mounts a persisted, exact Docker volume name without applying namespace rules again. */
public static void applyNamedVolume(
ContainerBuilder.Builder builder,
ContainerLifecycleManager lifecycleManager,
String volumeName,
String internalMount) {
lifecycleManager.ensureVolume(volumeName);
builder.withNamedVolume(volumeName, internalMount);
}
@@ -121,6 +130,14 @@ public final class ContainerStorageHelper {
String volumeId,
String fallbackId) {
String volumeName = resourceName(config, service, volumeId, fallbackId);
removeNamedVolume(config, lifecycleManager, volumeName);
}
/** Removes or retains a persisted, exact Docker volume name according to storage policy. */
public static void removeNamedVolume(
EmulatorConfig config,
ContainerLifecycleManager lifecycleManager,
String volumeName) {
boolean isMemory = "memory".equals(config.storage().mode());
if (isMemory || config.storage().pruneVolumesOnDelete()) {
lifecycleManager.removeVolume(volumeName);
@@ -129,6 +146,22 @@ public final class ContainerStorageHelper {
}
}
/**
* Removes an exact named volume according to storage policy and propagates Docker failures.
*/
public static void removeNamedVolumeStrict(
EmulatorConfig config,
ContainerLifecycleManager lifecycleManager,
String volumeName) {
boolean isMemory = "memory".equals(config.storage().mode());
if (isMemory || config.storage().pruneVolumesOnDelete()) {
lifecycleManager.removeVolumeStrict(volumeName);
} else {
LOG.infov("Retained Docker volume {0}. Remove manually: docker volume rm {0}",
volumeName);
}
}
/**
* Ensures the host data directory exists for host-path mode (absolute paths only).
* Called by managers in their legacy host-path code paths.
@@ -6,6 +6,7 @@ import jakarta.enterprise.inject.Instance;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -113,6 +114,21 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.scan(k -> true);
}
/**
* Returns every stored entry with its raw delegate key intact.
*
* <p>Startup migrations use this form when the key itself is part of a resource's identity.
* Keeping the account prefix prevents a value stored under a corrupt or foreign key from
* being re-keyed solely from mutable fields in the value.
*/
public Map<String, V> scanAllAccountsWithRawKeys() {
Map<String, V> result = new LinkedHashMap<>();
for (String rawKey : delegate.keys()) {
delegate.get(rawKey).ifPresent(value -> result.put(rawKey, value));
}
return result;
}
/**
* Returns all entries across every account as a map of logical-key (account prefix stripped)
* to value. Entries without a slash-prefixed account segment are skipped.
@@ -171,6 +187,97 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.get(accountId + "/" + key);
}
/**
* Returns an explicitly scoped entry, or safely migrates a matching legacy unscoped entry.
*
* <p>The caller-supplied predicate must establish that the legacy value belongs to the
* destination account. This opt-in path avoids {@link #get(String)}'s request-context fallback,
* which cannot validate ownership before migrating old data.
*/
public synchronized Optional<V> getForAccountMigratingLegacy(
String accountId, String key, Predicate<V> legacyOwner) {
Optional<V> scoped = getForAccount(accountId, key);
if (scoped.isPresent()) {
return scoped;
}
Optional<V> legacy = delegate.get(key).filter(legacyOwner);
if (legacy.isEmpty()) {
return Optional.empty();
}
delegate.put(accountId + "/" + key, legacy.get());
delegate.delete(key);
return legacy;
}
/**
* Returns an explicitly scoped entry, or safely migrates one of several older key shapes.
*
* <p>This is intended for resources whose logical key gained another scope component after
* account isolation was already deployed. Both account-prefixed legacy keys and older
* unprefixed keys are considered, but only when {@code legacyOwner} proves that the stored
* value belongs to the requested destination scope. The destination is written before the
* source is removed so a failed write cannot orphan the legacy value.
*/
public synchronized Optional<V> getForAccountMigratingLegacyKeys(
String accountId, String key, List<String> legacyKeys,
Predicate<V> legacyOwner) {
return getForAccountMigratingLegacyKeys(
accountId, key, legacyKeys, legacyOwner, true);
}
/**
* Variant of {@link #getForAccountMigratingLegacyKeys(String, String, List, Predicate)} that
* can exclude unprefixed legacy keys when the value cannot prove account ownership.
*/
public synchronized Optional<V> getForAccountMigratingLegacyKeys(
String accountId, String key, List<String> legacyKeys,
Predicate<V> legacyOwner, boolean includeUnscopedLegacyKeys) {
String destinationKey = accountId + "/" + key;
Set<String> candidates = new LinkedHashSet<>();
if (includeUnscopedLegacyKeys) {
candidates.add(key);
}
if (legacyKeys != null) {
for (String legacyKey : legacyKeys) {
if (legacyKey == null || legacyKey.isBlank()) {
continue;
}
candidates.add(accountId + "/" + legacyKey);
if (includeUnscopedLegacyKeys) {
candidates.add(legacyKey);
}
}
}
candidates.remove(destinationKey);
Optional<V> scoped = delegate.get(destinationKey);
if (scoped.isPresent()) {
if (scoped.filter(legacyOwner).isEmpty()) {
// A value under the destination key that does not belong to the requested
// scope is corrupt. Preserve both it and every legacy candidate so the
// caller fails closed without deleting the recoverable owned value.
return Optional.empty();
}
for (String candidateKey : candidates) {
if (delegate.get(candidateKey).filter(legacyOwner).isPresent()) {
delegate.delete(candidateKey);
}
}
return scoped;
}
for (String candidateKey : candidates) {
Optional<V> legacy = delegate.get(candidateKey).filter(legacyOwner);
if (legacy.isEmpty()) {
continue;
}
delegate.put(destinationKey, legacy.get());
delegate.delete(candidateKey);
return legacy;
}
return Optional.empty();
}
public void putForAccount(String accountId, String key, V value) {
delegate.put(accountId + "/" + key, value);
}
@@ -184,6 +291,13 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length())));
}
/** Returns unprefixed pre-account values that satisfy an ownership predicate. */
public List<V> scanUnscopedLegacy(Predicate<V> legacyOwner) {
return delegate.scan(k -> !k.contains("/")).stream()
.filter(legacyOwner)
.toList();
}
public Set<String> keysForAccount(String accountId) {
String prefix = accountId + "/";
return delegate.keys().stream()
@@ -43,6 +43,7 @@ import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
@@ -400,11 +401,16 @@ public class CloudFormationResourceProvisioner {
case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region);
// RDS. DBInstance/DBCluster start real RDS containers (same as the direct API).
case "AWS::RDS::DBSubnetGroup" -> provisionDbSubnetGroup(resource, properties, engine, stackName, region);
case "AWS::RDS::DBParameterGroup" -> provisionDbParameterGroup(resource, properties, engine, stackName);
case "AWS::RDS::DBParameterGroup" ->
provisionDbParameterGroup(resource, properties, engine, stackName, region);
case "AWS::RDS::DBClusterParameterGroup" ->
provisionDbClusterParameterGroup(resource, properties, engine, stackName);
provisionDbClusterParameterGroup(
resource, properties, engine, stackName, region);
case "AWS::RDS::DBInstance" -> provisionDbInstance(resource, properties, engine, stackName, region);
case "AWS::RDS::DBCluster" -> provisionDbCluster(resource, properties, engine, stackName, region);
case "AWS::RDS::DBProxy" -> provisionDbProxy(resource, properties, engine, region);
case "AWS::RDS::DBProxyTargetGroup" ->
provisionDbProxyTargetGroup(resource, properties, engine, region);
case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName);
case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName);
case "AWS::Logs::LogGroup" -> provisionLogGroup(resource, properties, engine, region, accountId, stackName);
@@ -614,11 +620,16 @@ public class CloudFormationResourceProvisioner {
case "AWS::KinesisFirehose::DeliveryStream" -> firehoseService.deleteDeliveryStream(physicalId);
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId);
case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId);
case "AWS::RDS::DBSubnetGroup" -> rdsService.deleteDbSubnetGroup(physicalId);
case "AWS::RDS::DBParameterGroup" -> rdsService.deleteDbParameterGroup(physicalId);
case "AWS::RDS::DBClusterParameterGroup" -> rdsService.deleteDbClusterParameterGroup(physicalId);
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region);
case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId, region);
case "AWS::RDS::DBProxy" -> deleteDbProxySafe(physicalId, region);
case "AWS::RDS::DBProxyTargetGroup" -> clearDbProxyTargetGroupSafe(physicalId, region);
case "AWS::RDS::DBSubnetGroup" ->
rdsService.deleteDbSubnetGroup(physicalId, region);
case "AWS::RDS::DBParameterGroup" ->
rdsService.deleteDbParameterGroup(physicalId, region);
case "AWS::RDS::DBClusterParameterGroup" ->
rdsService.deleteDbClusterParameterGroup(physicalId, region);
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
case "AWS::Logs::LogGroup" -> logsService.deleteLogGroup(physicalId, region);
case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region);
@@ -1339,7 +1350,7 @@ public class CloudFormationResourceProvisioner {
}
private void provisionDbParameterGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String stackName) {
String stackName, String region) {
String name = resolveOptional(props, "DBParameterGroupName", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 60, true);
@@ -1347,13 +1358,15 @@ public class CloudFormationResourceProvisioner {
String family = resolveOptional(props, "Family", engine);
String description = firstNonBlank(resolveOptional(props, "Description", engine),
"Managed by CloudFormation");
var group = rdsService.createDbParameterGroup(name, family, description);
var group = rdsService.createDbParameterGroup(
name, family, description, region);
r.setPhysicalId(group.getDbParameterGroupName());
r.getAttributes().put("DBParameterGroupName", group.getDbParameterGroupName());
}
private void provisionDbClusterParameterGroup(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine, String stackName) {
CloudFormationTemplateEngine engine,
String stackName, String region) {
String name = resolveOptional(props, "DBClusterParameterGroupName", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 60, true);
@@ -1361,7 +1374,8 @@ public class CloudFormationResourceProvisioner {
String family = resolveOptional(props, "Family", engine);
String description = firstNonBlank(resolveOptional(props, "Description", engine),
"Managed by CloudFormation");
var group = rdsService.createDbClusterParameterGroup(name, family, description);
var group = rdsService.createDbClusterParameterGroup(
name, family, description, region);
r.setPhysicalId(group.getDbClusterParameterGroupName());
r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName());
}
@@ -1427,6 +1441,184 @@ public class CloudFormationResourceProvisioner {
}
}
private void provisionDbProxy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region) {
String name = resolveOptional(props, "DBProxyName", engine);
String engineFamily = resolveOptional(props, "EngineFamily", engine);
String defaultAuthScheme = resolveOptional(props, "DefaultAuthScheme", engine);
if (defaultAuthScheme == null) {
defaultAuthScheme = "NONE";
} else if (defaultAuthScheme.isBlank()) {
throw new AwsException("InvalidParameterValue",
"DefaultAuthScheme must be NONE or IAM_AUTH.", 400);
}
String endpointNetworkType = resolveOptional(props, "EndpointNetworkType", engine);
String targetConnectionNetworkType = resolveOptional(
props, "TargetConnectionNetworkType", engine);
validateIpv4DbProxyNetworkType(endpointNetworkType,
"EndpointNetworkType", true, "IPV4, IPV6, or DUAL");
validateIpv4DbProxyNetworkType(targetConnectionNetworkType,
"TargetConnectionNetworkType", false, "IPV4 or IPV6");
boolean requireTls = parseBoolProp(props, "RequireTLS", engine);
boolean debugLogging = parseBoolProp(props, "DebugLogging", engine);
Integer configuredIdleClientTimeout = parseOptionalIntProp(props, "IdleClientTimeout", engine);
int idleClientTimeout = configuredIdleClientTimeout != null ? configuredIdleClientTimeout : 1800;
String roleArn = resolveOptional(props, "RoleArn", engine);
List<String> subnetIds = resolveStringList(props, "VpcSubnetIds", engine);
if (subnetIds.stream().distinct().count() < 2) {
throw new AwsException("InvalidParameterValue",
"AWS::RDS::DBProxy VpcSubnetIds must contain at least two distinct subnet IDs.", 400);
}
List<String> sgIds = resolveStringList(props, "VpcSecurityGroupIds", engine);
List<DbProxyAuth> auth = parseProxyAuth(props, engine);
boolean iamAuth = "IAM_AUTH".equalsIgnoreCase(defaultAuthScheme)
|| auth.stream().anyMatch(a ->
"REQUIRED".equalsIgnoreCase(a.getIamAuth())
|| "ENABLED".equalsIgnoreCase(a.getIamAuth()));
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
var proxy = r.getPhysicalId() == null
? rdsService.createDbProxy(name, engineFamily, requireTls, iamAuth,
defaultAuthScheme, roleArn, subnetIds, sgIds, auth, idleClientTimeout,
debugLogging, tags, region)
: updateDbProxy(r, name, engineFamily, defaultAuthScheme, requireTls,
idleClientTimeout, debugLogging, roleArn, subnetIds, sgIds, auth, tags, region);
r.setPhysicalId(proxy.getDbProxyName()); // Ref -> DBProxyName
r.getAttributes().put("Endpoint", proxy.getEndpoint()); // GetAtt "Endpoint" (bare host)
r.getAttributes().put("DBProxyArn", proxy.getDbProxyArn());
if (proxy.getVpcId() != null) {
r.getAttributes().put("VpcId", proxy.getVpcId());
}
}
private io.github.hectorvent.floci.services.rds.model.DbProxy updateDbProxy(
StackResource resource, String name, String engineFamily, String defaultAuthScheme,
boolean requireTls, int idleClientTimeout, boolean debugLogging, String roleArn,
List<String> subnetIds, List<String> securityGroupIds, List<DbProxyAuth> auth,
Map<String, String> tags, String region) {
var existing = rdsService.getDbProxy(resource.getPhysicalId(), region);
if (!Objects.equals(existing.getDbProxyName(), name)
|| engineFamily == null
|| !existing.getEngineFamily().equalsIgnoreCase(engineFamily)
|| !Set.copyOf(existing.getVpcSubnetIds()).equals(Set.copyOf(subnetIds))) {
throw new AwsException("UnsupportedOperation",
"Changing DBProxyName, EngineFamily, or VpcSubnetIds requires CloudFormation "
+ "replacement, which is not yet supported by Floci.", 400);
}
return rdsService.modifyDbProxy(existing.getDbProxyName(), defaultAuthScheme, auth,
requireTls, idleClientTimeout, debugLogging, roleArn,
securityGroupIds, tags, region);
}
private void provisionDbProxyTargetGroup(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine, String region) {
String dbProxyName = resolveOptional(props, "DBProxyName", engine);
String targetGroupName = resolveOptional(props, "TargetGroupName", engine);
if (!"default".equals(targetGroupName)) {
throw new AwsException("InvalidParameterValue",
"AWS::RDS::DBProxyTargetGroup TargetGroupName must be default.", 400);
}
List<String> clusterIds = resolveStringList(props, "DBClusterIdentifiers", engine);
List<String> instanceIds = resolveStringList(props, "DBInstanceIdentifiers", engine);
Integer maxConn = null;
Integer maxIdle = null;
Integer connectionBorrowTimeout = null;
String initQuery = null;
List<String> sessionPinningFilters = List.of();
if (props != null && props.has("ConnectionPoolConfigurationInfo")) {
JsonNode cpc = props.get("ConnectionPoolConfigurationInfo");
maxConn = parseOptionalIntProp(cpc, "MaxConnectionsPercent", engine);
maxIdle = parseOptionalIntProp(cpc, "MaxIdleConnectionsPercent", engine);
connectionBorrowTimeout = parseOptionalIntProp(cpc, "ConnectionBorrowTimeout", engine);
initQuery = resolveOptional(cpc, "InitQuery", engine);
sessionPinningFilters = resolveStringList(cpc, "SessionPinningFilters", engine);
}
if (maxIdle != null && maxConn == null) {
throw new AwsException("InvalidParameterValue",
"MaxConnectionsPercent is required when MaxIdleConnectionsPercent is specified.",
400);
}
if (r.getPhysicalId() != null) {
var existing = rdsService.getDbProxyTargetGroupByArn(r.getPhysicalId(), region);
if (!Objects.equals(existing.getDbProxyName(), dbProxyName)
|| !Objects.equals(existing.getTargetGroupName(), targetGroupName)) {
throw new AwsException("UnsupportedOperation",
"Changing DBProxyName or TargetGroupName requires CloudFormation replacement.",
400);
}
}
var proxy = rdsService.getDbProxy(dbProxyName, region);
int effectiveMaxConnections = maxConn != null ? maxConn
: ("SQLSERVER".equals(proxy.getEngineFamily()) ? 10 : 100);
int effectiveMaxIdle = maxIdle != null ? maxIdle : effectiveMaxConnections / 2;
int effectiveBorrowTimeout = connectionBorrowTimeout != null ? connectionBorrowTimeout : 120;
var tg = rdsService.reconcileDbProxyTargetGroup(
dbProxyName, targetGroupName, clusterIds, instanceIds,
effectiveMaxConnections, effectiveMaxIdle, effectiveBorrowTimeout,
initQuery, sessionPinningFilters, region);
r.setPhysicalId(tg.getTargetGroupArn()); // Ref -> TargetGroupArn
r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
r.getAttributes().put("DBProxyName", tg.getDbProxyName());
}
private List<DbProxyAuth> parseProxyAuth(JsonNode props, CloudFormationTemplateEngine engine) {
List<DbProxyAuth> auth = new ArrayList<>();
if (props != null && props.has("Auth") && props.get("Auth").isArray()) {
for (JsonNode a : props.get("Auth")) {
DbProxyAuth entry = new DbProxyAuth();
entry.setAuthScheme(resolveOptional(a, "AuthScheme", engine));
entry.setSecretArn(resolveOptional(a, "SecretArn", engine));
entry.setIamAuth(resolveOptional(a, "IAMAuth", engine));
entry.setClientPasswordAuthType(resolveOptional(a, "ClientPasswordAuthType", engine));
entry.setDescription(resolveOptional(a, "Description", engine));
entry.setUserName(resolveOptional(a, "UserName", engine));
auth.add(entry);
}
}
return auth;
}
private void validateIpv4DbProxyNetworkType(
String value, String propertyName, boolean dualAllowed, String validValues) {
if (value == null) {
return;
}
if ("IPV4".equalsIgnoreCase(value)) {
return;
}
boolean supportedAwsValue = "IPV6".equalsIgnoreCase(value)
|| (dualAllowed && "DUAL".equalsIgnoreCase(value));
if (value.isBlank() || !supportedAwsValue) {
throw new AwsException("InvalidParameterValue",
propertyName + " must be " + validValues + ".", 400);
}
throw new AwsException("UnsupportedOperation",
propertyName + " " + value.toUpperCase()
+ " is not supported because Floci currently exposes IPv4 proxy networking only.",
400);
}
private void deleteDbProxySafe(String name, String region) {
try {
rdsService.deleteDbProxy(name, region);
} catch (AwsException e) {
if (!"DBProxyNotFoundFault".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("DB proxy already gone, treating as deleted: {0}", name);
}
}
private void clearDbProxyTargetGroupSafe(String targetGroupArn, String region) {
try {
rdsService.clearDbProxyTargetGroupByArn(targetGroupArn, region);
} catch (AwsException e) {
if (!"DBProxyTargetGroupNotFoundFault".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("DB proxy target group already gone, treating as deleted: {0}", targetGroupArn);
}
}
private static String firstNonBlank(String value, String fallback) {
return (value == null || value.isBlank()) ? fallback : value;
}
@@ -1443,6 +1635,18 @@ public class CloudFormationResourceProvisioner {
}
}
private Integer parseOptionalIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
String value = resolveOptional(props, name, engine);
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.valueOf(value.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", name + " must be an integer.", 400);
}
}
private boolean parseBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
return Boolean.parseBoolean(resolveOptional(props, name, engine));
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
@@ -21,6 +22,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
@@ -131,11 +133,23 @@ public class CloudWatchLogsService {
public void createLogGroup(String name, Integer retentionInDays, Map<String, String> tags,
boolean deletionProtectionEnabled, String region) {
createLogGroupForAccount(null, name, retentionInDays, tags, deletionProtectionEnabled, region);
}
public void createLogGroupForAccount(
String accountId, String name, Integer retentionInDays,
Map<String, String> tags, String region) {
createLogGroupForAccount(accountId, name, retentionInDays, tags, false, region);
}
public void createLogGroupForAccount(
String accountId, String name, Integer retentionInDays,
Map<String, String> tags, boolean deletionProtectionEnabled, String region) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);
}
String key = groupKey(region, name);
if (groupStore.get(key).isPresent()) {
if (getForAccount(groupStore, accountId, key).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException",
"The specified log group already exists: " + name, 400);
}
@@ -147,7 +161,7 @@ public class CloudWatchLogsService {
if (tags != null) {
group.setTags(new HashMap<>(tags));
}
groupStore.put(key, group);
putForAccount(groupStore, accountId, key, group);
LOG.infov("Created log group: {0} in region {1}", name, region);
}
@@ -255,13 +269,18 @@ public class CloudWatchLogsService {
// ──────────────────────────── Log Streams ────────────────────────────
public void createLogStream(String groupName, String streamName, String region) {
createLogStreamForAccount(null, groupName, streamName, region);
}
public void createLogStreamForAccount(
String accountId, String groupName, String streamName, String region) {
String groupKey = groupKey(region, groupName);
groupStore.get(groupKey)
getForAccount(groupStore, accountId, groupKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log group does not exist: " + groupName, 400));
String streamKey = streamKey(region, groupName, streamName);
if (streamStore.get(streamKey).isPresent()) {
if (getForAccount(streamStore, accountId, streamKey).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException",
"The specified log stream already exists: " + streamName, 400);
}
@@ -271,7 +290,7 @@ public class CloudWatchLogsService {
stream.setLogStreamName(streamName);
stream.setCreatedTime(System.currentTimeMillis());
stream.setUploadSequenceToken(UUID.randomUUID().toString());
streamStore.put(streamKey, stream);
putForAccount(streamStore, accountId, streamKey, stream);
LOG.infov("Created log stream: {0}/{1}", groupName, streamName);
}
@@ -311,8 +330,14 @@ public class CloudWatchLogsService {
public String putLogEvents(String groupName, String streamName,
List<Map<String, Object>> events, String region) {
return putLogEventsForAccount(null, groupName, streamName, events, region);
}
public String putLogEventsForAccount(
String accountId, String groupName, String streamName,
List<Map<String, Object>> events, String region) {
String streamKey = streamKey(region, groupName, streamName);
LogStream stream = streamStore.get(streamKey)
LogStream stream = getForAccount(streamStore, accountId, streamKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log stream does not exist: " + streamName, 400));
@@ -333,7 +358,7 @@ public class CloudWatchLogsService {
logEvent.setSequence(ingestionSequence.incrementAndGet());
String eventKey = eventKey(region, groupName, streamName, ts, logEvent.getEventId());
eventStore.put(eventKey, logEvent);
putForAccount(eventStore, accountId, eventKey, logEvent);
totalBytes += msg.getBytes().length + 26; // approx overhead
if (minTs == null || ts < minTs) { minTs = ts; }
@@ -353,11 +378,32 @@ public class CloudWatchLogsService {
stream.setStoredBytes(stream.getStoredBytes() + totalBytes);
String nextToken = UUID.randomUUID().toString();
stream.setUploadSequenceToken(nextToken);
streamStore.put(streamKey, stream);
putForAccount(streamStore, accountId, streamKey, stream);
return nextToken;
}
private <V> Optional<V> getForAccount(
StorageBackend<String, V> store, String accountId, String key) {
if (accountId != null && store instanceof AccountAwareStorageBackend<?> rawAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<V> aware = (AccountAwareStorageBackend<V>) rawAware;
return aware.getForAccount(accountId, key);
}
return store.get(key);
}
private <V> void putForAccount(
StorageBackend<String, V> store, String accountId, String key, V value) {
if (accountId != null && store instanceof AccountAwareStorageBackend<?> rawAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<V> aware = (AccountAwareStorageBackend<V>) rawAware;
aware.putForAccount(accountId, key, value);
return;
}
store.put(key, value);
}
public record LogEventsResult(List<LogEvent> events, String nextForwardToken, String nextBackwardToken) {}
public LogEventsResult getLogEvents(String groupName, String streamName,
@@ -11,6 +11,10 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbProxy;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -50,35 +54,43 @@ public class RdsQueryHandler {
try {
return switch (action) {
case "CreateDBInstance" -> handleCreateDbInstance(params, region);
case "DescribeDBInstances" -> handleDescribeDbInstances(params);
case "DeleteDBInstance" -> handleDeleteDbInstance(params);
case "ModifyDBInstance" -> handleModifyDbInstance(params);
case "RebootDBInstance" -> handleRebootDbInstance(params);
case "DescribeDBInstances" -> handleDescribeDbInstances(params, region);
case "DeleteDBInstance" -> handleDeleteDbInstance(params, region);
case "ModifyDBInstance" -> handleModifyDbInstance(params, region);
case "RebootDBInstance" -> handleRebootDbInstance(params, region);
case "DescribeOrderableDBInstanceOptions" -> handleDescribeOrderableDbInstanceOptions(params);
case "CreateDBSubnetGroup" -> handleCreateDbSubnetGroup(params, region);
case "DescribeDBSubnetGroups" -> handleDescribeDbSubnetGroups(params, region);
case "ModifyDBSubnetGroup" -> handleModifyDbSubnetGroup(params, region);
case "DeleteDBSubnetGroup" -> handleDeleteDbSubnetGroup(params);
case "DeleteDBSubnetGroup" -> handleDeleteDbSubnetGroup(params, region);
case "CreateDBCluster" -> handleCreateDbCluster(params, region);
case "DescribeDBClusters" -> handleDescribeDbClusters(params);
case "DeleteDBCluster" -> handleDeleteDbCluster(params);
case "ModifyDBCluster" -> handleModifyDbCluster(params);
case "CreateDBParameterGroup" -> handleCreateDbParameterGroup(params);
case "DescribeDBParameterGroups" -> handleDescribeDbParameterGroups(params);
case "DeleteDBParameterGroup" -> handleDeleteDbParameterGroup(params);
case "ModifyDBParameterGroup" -> handleModifyDbParameterGroup(params);
case "DescribeDBParameters" -> handleDescribeDbParameters(params);
case "CreateDBClusterParameterGroup" -> handleCreateDbClusterParameterGroup(params);
case "DescribeDBClusterParameterGroups" -> handleDescribeDbClusterParameterGroups(params);
case "DeleteDBClusterParameterGroup" -> handleDeleteDbClusterParameterGroup(params);
case "ModifyDBClusterParameterGroup" -> handleModifyDbClusterParameterGroup(params);
case "DescribeDBClusterParameters" -> handleDescribeDbClusterParameters(params);
case "DescribeDBClusters" -> handleDescribeDbClusters(params, region);
case "DeleteDBCluster" -> handleDeleteDbCluster(params, region);
case "ModifyDBCluster" -> handleModifyDbCluster(params, region);
case "CreateDBParameterGroup" -> handleCreateDbParameterGroup(params, region);
case "DescribeDBParameterGroups" -> handleDescribeDbParameterGroups(params, region);
case "DeleteDBParameterGroup" -> handleDeleteDbParameterGroup(params, region);
case "ModifyDBParameterGroup" -> handleModifyDbParameterGroup(params, region);
case "DescribeDBParameters" -> handleDescribeDbParameters(params, region);
case "CreateDBClusterParameterGroup" -> handleCreateDbClusterParameterGroup(params, region);
case "DescribeDBClusterParameterGroups" -> handleDescribeDbClusterParameterGroups(params, region);
case "DeleteDBClusterParameterGroup" -> handleDeleteDbClusterParameterGroup(params, region);
case "ModifyDBClusterParameterGroup" -> handleModifyDbClusterParameterGroup(params, region);
case "DescribeDBClusterParameters" -> handleDescribeDbClusterParameters(params, region);
case "DescribeDBSnapshots" -> handleDescribeDbSnapshots(params);
case "DescribeDBProxies" -> handleDescribeDbProxies(params);
case "DescribeDBProxies" -> handleDescribeDbProxies(params, region);
case "CreateDBProxy" -> handleCreateDbProxy(params, region);
case "ModifyDBProxy" -> handleModifyDbProxy(params, region);
case "DeleteDBProxy" -> handleDeleteDbProxy(params, region);
case "RegisterDBProxyTargets" -> handleRegisterDbProxyTargets(params, region);
case "DeregisterDBProxyTargets" -> handleDeregisterDbProxyTargets(params, region);
case "DescribeDBProxyTargetGroups" -> handleDescribeDbProxyTargetGroups(params, region);
case "ModifyDBProxyTargetGroup" -> handleModifyDbProxyTargetGroup(params, region);
case "DescribeDBProxyTargets" -> handleDescribeDbProxyTargets(params, region);
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params);
case "AddTagsToResource" -> handleAddTagsToResource(params);
case "ListTagsForResource" -> handleListTagsForResource(params);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params);
case "AddTagsToResource" -> handleAddTagsToResource(params, region);
case "ListTagsForResource" -> handleListTagsForResource(params, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params, region);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.RDS, 400);
};
@@ -137,7 +149,8 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbInstances(MultivaluedMap<String, String> params) {
private Response handleDescribeDbInstances(
MultivaluedMap<String, String> params, String region) {
String identifier = params.getFirst("DBInstanceIdentifier");
String filterId = identifier;
if (filterId == null || filterId.isBlank()) {
@@ -146,12 +159,12 @@ public class RdsQueryHandler {
try {
Collection<DbInstance> result;
if (filterId != null && !filterId.isBlank()) {
result = service.listDbInstances(filterId);
result = service.listDbInstances(filterId, region);
} else {
List<String> resourceIds = extractRdsFilterValues(params, "dbi-resource-id");
result = resourceIds.isEmpty()
? service.listDbInstances(null)
: service.listDbInstancesByDbiResourceIds(resourceIds);
? service.listDbInstances(null, region)
: service.listDbInstancesByDbiResourceIds(resourceIds, region);
}
// AWS parity: the DBInstanceIdentifier PARAMETER faults with
// DBInstanceNotFound when no instance matches, while the
@@ -171,14 +184,15 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbInstance(MultivaluedMap<String, String> params) {
private Response handleDeleteDbInstance(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBInstanceIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
}
try {
DbInstance instance = service.getDbInstance(id);
service.deleteDbInstance(id);
DbInstance instance = service.getDbInstance(id, region);
service.deleteDbInstance(id, region);
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("DeleteDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -186,7 +200,8 @@ public class RdsQueryHandler {
}
}
private Response handleModifyDbInstance(MultivaluedMap<String, String> params) {
private Response handleModifyDbInstance(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBInstanceIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
@@ -198,7 +213,8 @@ public class RdsQueryHandler {
try {
List<String> vpcSecurityGroupIds = vpcSecurityGroupIds(params);
DbInstance instance = service.modifyDbInstance(
id, newPassword, iamEnabled, dbSubnetGroupName, vpcSecurityGroupIds);
id, newPassword, iamEnabled, dbSubnetGroupName,
vpcSecurityGroupIds, region);
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -230,21 +246,21 @@ public class RdsQueryHandler {
AwsNamespaces.RDS, xml.build())).build();
}
private Response handleAddTagsToResource(MultivaluedMap<String, String> params) {
private Response handleAddTagsToResource(MultivaluedMap<String, String> params, String region) {
String resourceName = params.getFirst("ResourceName");
try {
service.addTagsToResource(resourceName, parseTags(params));
service.addTagsToResource(resourceName, parseTags(params), region);
return Response.ok(AwsQueryResponse.envelope("AddTagsToResource", AwsNamespaces.RDS, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleListTagsForResource(MultivaluedMap<String, String> params) {
private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {
String resourceName = params.getFirst("ResourceName");
try {
XmlBuilder xml = new XmlBuilder().start("TagList");
writeTags(xml, service.listTagsForResource(resourceName));
writeTags(xml, service.listTagsForResource(resourceName, region));
xml.end("TagList");
return Response.ok(AwsQueryResponse.envelope("ListTagsForResource", AwsNamespaces.RDS, xml.build())).build();
} catch (AwsException e) {
@@ -252,10 +268,10 @@ public class RdsQueryHandler {
}
}
private Response handleRemoveTagsFromResource(MultivaluedMap<String, String> params) {
private Response handleRemoveTagsFromResource(MultivaluedMap<String, String> params, String region) {
String resourceName = params.getFirst("ResourceName");
try {
service.removeTagsFromResource(resourceName, memberList(params, "TagKeys"));
service.removeTagsFromResource(resourceName, memberList(params, "TagKeys"), region);
return Response.ok(AwsQueryResponse.envelope("RemoveTagsFromResource", AwsNamespaces.RDS, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
@@ -310,27 +326,29 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbSubnetGroup(MultivaluedMap<String, String> params) {
private Response handleDeleteDbSubnetGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBSubnetGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue",
"DBSubnetGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
service.deleteDbSubnetGroup(name);
service.deleteDbSubnetGroup(name, region);
return Response.ok(AwsQueryResponse.envelope("DeleteDBSubnetGroup", AwsNamespaces.RDS, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleRebootDbInstance(MultivaluedMap<String, String> params) {
private Response handleRebootDbInstance(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBInstanceIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
}
try {
DbInstance instance = service.rebootDbInstance(id);
DbInstance instance = service.rebootDbInstance(id, region);
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("RebootDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -372,14 +390,15 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbClusters(MultivaluedMap<String, String> params) {
private Response handleDescribeDbClusters(
MultivaluedMap<String, String> params, String region) {
String identifier = params.getFirst("DBClusterIdentifier");
String filterId = identifier;
if (filterId == null || filterId.isBlank()) {
filterId = extractRdsFilterValue(params, "db-cluster-id");
}
try {
Collection<DbCluster> result = service.listDbClusters(filterId);
Collection<DbCluster> result = service.listDbClusters(filterId, region);
// AWS parity: the DBClusterIdentifier PARAMETER faults with
// DBClusterNotFoundFault when no cluster matches, while the
// db-cluster-id Filters form returns an empty list.
@@ -398,14 +417,15 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbCluster(MultivaluedMap<String, String> params) {
private Response handleDeleteDbCluster(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBClusterIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400);
}
try {
DbCluster cluster = service.getDbCluster(id);
service.deleteDbCluster(id);
DbCluster cluster = service.getDbCluster(id, region);
service.deleteDbCluster(id, region);
String result = dbClusterXml(cluster);
return Response.ok(AwsQueryResponse.envelope("DeleteDBCluster", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -413,7 +433,8 @@ public class RdsQueryHandler {
}
}
private Response handleModifyDbCluster(MultivaluedMap<String, String> params) {
private Response handleModifyDbCluster(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBClusterIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400);
@@ -422,7 +443,7 @@ public class RdsQueryHandler {
String iamStr = params.getFirst("EnableIAMDatabaseAuthentication");
Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null;
try {
DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled);
DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled, region);
String result = dbClusterXml(cluster);
return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -432,7 +453,8 @@ public class RdsQueryHandler {
// ── Parameter Groups ──────────────────────────────────────────────────────
private Response handleCreateDbParameterGroup(MultivaluedMap<String, String> params) {
private Response handleCreateDbParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
String family = params.getFirst("DBParameterGroupFamily");
String description = params.getFirst("Description");
@@ -440,7 +462,8 @@ public class RdsQueryHandler {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbParameterGroup group = service.createDbParameterGroup(name, family, description);
DbParameterGroup group = service.createDbParameterGroup(
name, family, description, region);
String result = paramGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("CreateDBParameterGroup", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -448,10 +471,11 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbParameterGroups(MultivaluedMap<String, String> params) {
private Response handleDescribeDbParameterGroups(
MultivaluedMap<String, String> params, String region) {
String filterName = params.getFirst("DBParameterGroupName");
try {
Collection<DbParameterGroup> result = service.listDbParameterGroups(filterName);
Collection<DbParameterGroup> result = service.listDbParameterGroups(filterName, region);
XmlBuilder xml = new XmlBuilder().start("DBParameterGroups");
for (DbParameterGroup g : result) {
xml.start("DBParameterGroup").raw(paramGroupInnerXml(g)).end("DBParameterGroup");
@@ -463,20 +487,22 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbParameterGroup(MultivaluedMap<String, String> params) {
private Response handleDeleteDbParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
service.deleteDbParameterGroup(name);
service.deleteDbParameterGroup(name, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteDBParameterGroup", AwsNamespaces.RDS)).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleModifyDbParameterGroup(MultivaluedMap<String, String> params) {
private Response handleModifyDbParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
@@ -493,7 +519,7 @@ public class RdsQueryHandler {
}
}
try {
DbParameterGroup group = service.modifyDbParameterGroup(name, parameters);
DbParameterGroup group = service.modifyDbParameterGroup(name, parameters, region);
String result = new XmlBuilder()
.elem("DBParameterGroupName", group.getDbParameterGroupName())
.build();
@@ -503,13 +529,14 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbParameters(MultivaluedMap<String, String> params) {
private Response handleDescribeDbParameters(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbParameterGroup group = service.getDbParameterGroup(name);
DbParameterGroup group = service.getDbParameterGroup(name, region);
XmlBuilder xml = new XmlBuilder().start("Parameters");
for (Map.Entry<String, String> entry : group.getParameters().entrySet()) {
xml.start("member")
@@ -527,7 +554,8 @@ public class RdsQueryHandler {
// ── Cluster Parameter Groups ──────────────────────────────────────────────
private Response handleCreateDbClusterParameterGroup(MultivaluedMap<String, String> params) {
private Response handleCreateDbClusterParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
String family = params.getFirst("DBParameterGroupFamily");
String description = params.getFirst("Description");
@@ -535,7 +563,8 @@ public class RdsQueryHandler {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbClusterParameterGroup group = service.createDbClusterParameterGroup(name, family, description);
DbClusterParameterGroup group = service.createDbClusterParameterGroup(
name, family, description, region);
String result = clusterParamGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("CreateDBClusterParameterGroup", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -543,10 +572,12 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbClusterParameterGroups(MultivaluedMap<String, String> params) {
private Response handleDescribeDbClusterParameterGroups(
MultivaluedMap<String, String> params, String region) {
String filterName = params.getFirst("DBClusterParameterGroupName");
try {
Collection<DbClusterParameterGroup> result = service.listDbClusterParameterGroups(filterName);
Collection<DbClusterParameterGroup> result =
service.listDbClusterParameterGroups(filterName, region);
XmlBuilder xml = new XmlBuilder().start("DBClusterParameterGroups");
for (DbClusterParameterGroup g : result) {
xml.start("DBClusterParameterGroup").raw(clusterParamGroupInnerXml(g)).end("DBClusterParameterGroup");
@@ -558,20 +589,22 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbClusterParameterGroup(MultivaluedMap<String, String> params) {
private Response handleDeleteDbClusterParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
service.deleteDbClusterParameterGroup(name);
service.deleteDbClusterParameterGroup(name, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteDBClusterParameterGroup", AwsNamespaces.RDS)).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleModifyDbClusterParameterGroup(MultivaluedMap<String, String> params) {
private Response handleModifyDbClusterParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
@@ -588,7 +621,8 @@ public class RdsQueryHandler {
}
}
try {
DbClusterParameterGroup group = service.modifyDbClusterParameterGroup(name, parameters);
DbClusterParameterGroup group = service.modifyDbClusterParameterGroup(
name, parameters, region);
String result = new XmlBuilder()
.elem("DBClusterParameterGroupName", group.getDbClusterParameterGroupName())
.build();
@@ -598,13 +632,14 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbClusterParameters(MultivaluedMap<String, String> params) {
private Response handleDescribeDbClusterParameters(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbClusterParameterGroup group = service.getDbClusterParameterGroup(name);
DbClusterParameterGroup group = service.getDbClusterParameterGroup(name, region);
XmlBuilder xml = new XmlBuilder().start("Parameters");
for (Map.Entry<String, String> entry : group.getParameters().entrySet()) {
xml.start("member")
@@ -630,12 +665,292 @@ public class RdsQueryHandler {
return Response.ok(AwsQueryResponse.envelope("DescribeDBSnapshots", AwsNamespaces.RDS, result)).build();
}
private Response handleDescribeDbProxies(MultivaluedMap<String, String> params) {
// DB proxies are not modeled; return the RDS Query API's wire-accurate empty
// result (empty <DBProxies> wrapper, no <Marker>) so SDK clients complete the
// read instead of failing with UnsupportedOperation.
String result = new XmlBuilder().start("DBProxies").end("DBProxies").build();
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxies", AwsNamespaces.RDS, result)).build();
private Response handleDescribeDbProxies(MultivaluedMap<String, String> params, String region) {
XmlBuilder xml = new XmlBuilder().start("DBProxies");
for (DbProxy p : service.listDbProxies(params.getFirst("DBProxyName"), region)) {
xml.start("member").raw(dbProxyInnerXml(p)).end("member");
}
xml.end("DBProxies");
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxies", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleCreateDbProxy(MultivaluedMap<String, String> params, String region) {
validateIpv4NetworkType(params.getFirst("EndpointNetworkType"),
"EndpointNetworkType", true, "IPV4, IPV6, or DUAL");
validateIpv4NetworkType(params.getFirst("TargetConnectionNetworkType"),
"TargetConnectionNetworkType", false, "IPV4 or IPV6");
String name = params.getFirst("DBProxyName");
String engineFamily = params.getFirst("EngineFamily");
boolean requireTls = "true".equalsIgnoreCase(params.getFirst("RequireTLS"));
boolean debugLogging = "true".equalsIgnoreCase(params.getFirst("DebugLogging"));
int idleClientTimeout = 1800;
String idleClientTimeoutValue = params.getFirst("IdleClientTimeout");
if (idleClientTimeoutValue != null) {
try {
idleClientTimeout = Integer.parseInt(idleClientTimeoutValue);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", "IdleClientTimeout must be an integer.", 400);
}
}
String roleArn = params.getFirst("RoleArn");
List<String> subnetIds = memberList(params, "VpcSubnetIds");
List<String> sgIds = memberList(params, "VpcSecurityGroupIds");
List<DbProxyAuth> auth = parseProxyAuth(params);
String defaultAuthScheme = params.getFirst("DefaultAuthScheme");
boolean iamEnabled = auth.stream().anyMatch(a ->
"REQUIRED".equalsIgnoreCase(a.getIamAuth())
|| "ENABLED".equalsIgnoreCase(a.getIamAuth()));
iamEnabled = iamEnabled || "IAM_AUTH".equalsIgnoreCase(defaultAuthScheme);
DbProxy proxy = service.createDbProxy(
name, engineFamily, requireTls, iamEnabled, defaultAuthScheme, roleArn,
subnetIds, sgIds, auth, idleClientTimeout, debugLogging, parseTags(params), region);
String result = new XmlBuilder().start("DBProxy").raw(dbProxyInnerXml(proxy)).end("DBProxy").build();
return Response.ok(AwsQueryResponse.envelope("CreateDBProxy", AwsNamespaces.RDS, result)).build();
}
private Response handleModifyDbProxy(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
String newName = params.getFirst("NewDBProxyName");
if (newName != null && !newName.isBlank()) {
throw new AwsException("UnsupportedOperation",
"NewDBProxyName is not supported; renaming a persisted proxy requires "
+ "an atomic storage-key migration.", 400);
}
List<DbProxyAuth> auth = hasProxyAuthKeys(params) ? parseProxyAuth(params) : null;
List<String> securityGroups = hasMemberKeys(params, "SecurityGroups")
? memberList(params, "SecurityGroups")
: (hasMemberKeys(params, "VpcSecurityGroupIds")
? vpcSecurityGroupIds(params) : null);
DbProxy proxy = service.modifyDbProxy(
name,
params.getFirst("DefaultAuthScheme"),
auth,
parseOptionalBoolean(params, "RequireTLS"),
parseOptionalInteger(params, "IdleClientTimeout"),
parseOptionalBoolean(params, "DebugLogging"),
params.getFirst("RoleArn"),
securityGroups,
null,
region);
String result = new XmlBuilder().start("DBProxy")
.raw(dbProxyInnerXml(proxy)).end("DBProxy").build();
return Response.ok(AwsQueryResponse.envelope(
"ModifyDBProxy", AwsNamespaces.RDS, result)).build();
}
private Response handleDeleteDbProxy(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
DbProxy proxy = service.getDbProxy(name, region);
String result = new XmlBuilder().start("DBProxy").raw(dbProxyInnerXml(proxy)).end("DBProxy").build();
service.deleteDbProxy(name, region);
return Response.ok(AwsQueryResponse.envelope("DeleteDBProxy", AwsNamespaces.RDS, result)).build();
}
private Response handleRegisterDbProxyTargets(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
String tgName = params.getFirst("TargetGroupName");
validateOptionalTargetGroupName(tgName);
List<String> clusterIds = memberList(params, "DBClusterIdentifiers");
List<String> instanceIds = memberList(params, "DBInstanceIdentifiers");
DbProxyTargetGroup tg = service.registerDbProxyTargets(
name, tgName, clusterIds, instanceIds, 0, 0, region);
XmlBuilder xml = new XmlBuilder().start("DBProxyTargets");
for (DbProxyTarget t : tg.getTargets()) {
xml.start("member").raw(dbProxyTargetInnerXml(t)).end("member");
}
xml.end("DBProxyTargets");
return Response.ok(AwsQueryResponse.envelope("RegisterDBProxyTargets", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleDeregisterDbProxyTargets(MultivaluedMap<String, String> params, String region) {
String targetGroupName = params.getFirst("TargetGroupName");
validateOptionalTargetGroupName(targetGroupName);
service.deregisterDbProxyTargets(params.getFirst("DBProxyName"), targetGroupName,
memberList(params, "DBClusterIdentifiers"), memberList(params, "DBInstanceIdentifiers"), region);
return Response.ok(AwsQueryResponse.envelope("DeregisterDBProxyTargets", AwsNamespaces.RDS, "")).build();
}
private Response handleDescribeDbProxyTargetGroups(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
XmlBuilder xml = new XmlBuilder().start("TargetGroups");
for (DbProxyTargetGroup tg : service.describeDbProxyTargetGroups(
name, params.getFirst("TargetGroupName"), region)) {
xml.start("member").raw(dbProxyTargetGroupInnerXml(tg)).end("member");
}
xml.end("TargetGroups");
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxyTargetGroups", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleModifyDbProxyTargetGroup(
MultivaluedMap<String, String> params, String region) {
String targetGroupName = params.getFirst("TargetGroupName");
if (targetGroupName == null || targetGroupName.isBlank()) {
throw new AwsException("InvalidParameterValue",
"TargetGroupName is required.", 400);
}
String newName = params.getFirst("NewName");
if (newName != null && !newName.isBlank()) {
throw new AwsException("UnsupportedOperation",
"The default DB proxy target group cannot be renamed.", 400);
}
String poolPrefix = "ConnectionPoolConfig.";
List<String> pinningFilters = hasMemberKeys(
params, poolPrefix + "SessionPinningFilters")
? memberList(params, poolPrefix + "SessionPinningFilters") : null;
DbProxyTargetGroup targetGroup = service.configureDbProxyTargetGroup(
params.getFirst("DBProxyName"),
targetGroupName,
parseOptionalInteger(params, poolPrefix + "MaxConnectionsPercent"),
parseOptionalInteger(params, poolPrefix + "MaxIdleConnectionsPercent"),
parseOptionalInteger(params, poolPrefix + "ConnectionBorrowTimeout"),
params.containsKey(poolPrefix + "InitQuery")
? params.getFirst(poolPrefix + "InitQuery") : null,
pinningFilters,
region);
String result = new XmlBuilder().start("DBProxyTargetGroup")
.raw(dbProxyTargetGroupInnerXml(targetGroup)).end("DBProxyTargetGroup").build();
return Response.ok(AwsQueryResponse.envelope(
"ModifyDBProxyTargetGroup", AwsNamespaces.RDS, result)).build();
}
private Response handleDescribeDbProxyTargets(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
String tgName = params.getFirst("TargetGroupName");
validateOptionalTargetGroupName(tgName);
XmlBuilder xml = new XmlBuilder().start("Targets");
for (DbProxyTarget t : service.describeDbProxyTargets(name, tgName, region)) {
xml.start("member").raw(dbProxyTargetInnerXml(t)).end("member");
}
xml.end("Targets");
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxyTargets", AwsNamespaces.RDS, xml.build())).build();
}
private void validateOptionalTargetGroupName(String targetGroupName) {
if (targetGroupName != null && targetGroupName.isBlank()) {
throw new AwsException("InvalidParameterValue",
"TargetGroupName must be at least 1 character.", 400);
}
}
private String dbProxyInnerXml(DbProxy p) {
XmlBuilder xml = new XmlBuilder()
.elem("DBProxyName", p.getDbProxyName())
.elem("DBProxyArn", p.getDbProxyArn())
.elem("Status", p.getStatus())
.elem("EngineFamily", p.getEngineFamily())
.elem("Endpoint", p.getEndpoint())
.elem("RequireTLS", String.valueOf(p.isRequireTls()))
.elem("DefaultAuthScheme", p.getDefaultAuthScheme())
.elem("EndpointNetworkType", p.getEndpointNetworkType() != null
? p.getEndpointNetworkType() : "IPV4")
.elem("TargetConnectionNetworkType", p.getTargetConnectionNetworkType() != null
? p.getTargetConnectionNetworkType() : "IPV4")
.elem("IdleClientTimeout", p.getIdleClientTimeout())
.elem("DebugLogging", String.valueOf(p.isDebugLogging()));
if (p.getVpcId() != null) {
xml.elem("VpcId", p.getVpcId());
}
if (p.getRoleArn() != null) {
xml.elem("RoleArn", p.getRoleArn());
}
xml.start("Auth");
for (DbProxyAuth a : p.getAuth()) {
xml.start("member")
.elem("AuthScheme", a.getAuthScheme())
.elem("SecretArn", a.getSecretArn())
.elem("IAMAuth", a.getIamAuth());
if (a.getClientPasswordAuthType() != null) {
xml.elem("ClientPasswordAuthType", a.getClientPasswordAuthType());
}
if (a.getDescription() != null) {
xml.elem("Description", a.getDescription());
}
if (a.getUserName() != null) {
xml.elem("UserName", a.getUserName());
}
xml.end("member");
}
xml.end("Auth");
xml.start("VpcSubnetIds");
for (String s : p.getVpcSubnetIds()) {
xml.elem("member", s);
}
xml.end("VpcSubnetIds");
xml.start("VpcSecurityGroupIds");
for (String securityGroupId : p.getVpcSecurityGroupIds()) {
xml.elem("member", securityGroupId);
}
xml.end("VpcSecurityGroupIds");
if (p.getCreatedAt() != null) {
xml.elem("CreatedDate", p.getCreatedAt().toString());
}
if (p.getUpdatedAt() != null) {
xml.elem("UpdatedDate", p.getUpdatedAt().toString());
}
return xml.build();
}
private static void validateIpv4NetworkType(
String value, String parameterName, boolean dualAllowed, String validValues) {
if (value == null) {
return;
}
if ("IPV4".equalsIgnoreCase(value)) {
return;
}
boolean supportedAwsValue = "IPV6".equalsIgnoreCase(value)
|| (dualAllowed && "DUAL".equalsIgnoreCase(value));
if (value.isBlank() || !supportedAwsValue) {
throw new AwsException("InvalidParameterValue",
parameterName + " must be " + validValues + ".", 400);
}
throw new AwsException("UnsupportedOperation",
parameterName + " " + value.toUpperCase()
+ " is not supported because Floci currently exposes IPv4 proxy networking only.",
400);
}
private String dbProxyTargetGroupInnerXml(DbProxyTargetGroup tg) {
XmlBuilder xml = new XmlBuilder()
.elem("DBProxyName", tg.getDbProxyName())
.elem("TargetGroupName", tg.getTargetGroupName())
.elem("TargetGroupArn", tg.getTargetGroupArn())
.elem("Status", tg.getStatus())
.elem("IsDefault", String.valueOf(tg.isDefaultTargetGroup()))
.start("ConnectionPoolConfig")
.elem("MaxConnectionsPercent", tg.getMaxConnectionsPercent())
.elem("MaxIdleConnectionsPercent", tg.getMaxIdleConnectionsPercent())
.elem("ConnectionBorrowTimeout", tg.getConnectionBorrowTimeout());
if (tg.getInitQuery() != null) {
xml.elem("InitQuery", tg.getInitQuery());
}
xml.start("SessionPinningFilters");
for (String filter : tg.getSessionPinningFilters()) {
xml.elem("member", filter);
}
xml.end("SessionPinningFilters")
.end("ConnectionPoolConfig");
if (tg.getCreatedAt() != null) {
xml.elem("CreatedDate", tg.getCreatedAt().toString());
}
if (tg.getUpdatedAt() != null) {
xml.elem("UpdatedDate", tg.getUpdatedAt().toString());
}
return xml.build();
}
private String dbProxyTargetInnerXml(DbProxyTarget t) {
XmlBuilder xml = new XmlBuilder()
.elem("Type", t.getType())
.elem("RdsResourceId", t.getRdsResourceId())
.elem("Endpoint", t.getEndpoint())
.elem("Port", t.getPort())
.start("TargetHealth").elem("State", t.getTargetHealth()).end("TargetHealth");
if (t.getTargetArn() != null) {
xml.elem("TargetArn", t.getTargetArn());
}
return xml.build();
}
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params) {
@@ -864,7 +1179,17 @@ public class RdsQueryHandler {
if (groupName == null || groupName.isBlank() || "default".equalsIgnoreCase(groupName)) {
return fallbackSubnetGroup(instance, "default", "default subnet group");
}
return service.getDbSubnetGroup(groupName);
return service.getDbSubnetGroup(
groupName, regionFromRdsArn(instance.getDbInstanceArn()));
}
private String regionFromRdsArn(String arn) {
if (arn == null || arn.isBlank()) {
return config.defaultRegion();
}
String[] parts = arn.split(":", 6);
return parts.length == 6 && !parts[3].isBlank()
? parts[3] : config.defaultRegion();
}
private DbSubnetGroup fallbackSubnetGroup(DbInstance instance, String name, String description) {
@@ -924,6 +1249,7 @@ public class RdsQueryHandler {
case DELETING -> "deleting";
case REBOOTING -> "rebooting";
case MODIFYING -> "modifying";
case FAILED -> "failed";
};
}
@@ -998,6 +1324,62 @@ public class RdsQueryHandler {
}
}
private static List<DbProxyAuth> parseProxyAuth(MultivaluedMap<String, String> params) {
List<DbProxyAuth> auth = new java.util.ArrayList<>();
for (int index = 1; ; index++) {
String prefix = "Auth.member." + index + ".";
String authScheme = params.getFirst(prefix + "AuthScheme");
String secretArn = params.getFirst(prefix + "SecretArn");
String iamAuth = params.getFirst(prefix + "IAMAuth");
String passwordType = params.getFirst(prefix + "ClientPasswordAuthType");
String description = params.getFirst(prefix + "Description");
String userName = params.getFirst(prefix + "UserName");
if (authScheme == null && secretArn == null && iamAuth == null
&& passwordType == null && description == null && userName == null) {
break;
}
DbProxyAuth entry = new DbProxyAuth(
authScheme, secretArn, iamAuth, passwordType, description);
entry.setUserName(userName);
auth.add(entry);
}
return auth;
}
private static boolean hasProxyAuthKeys(MultivaluedMap<String, String> params) {
return params.keySet().stream().anyMatch(key -> key.startsWith("Auth.member."));
}
private static Boolean parseOptionalBoolean(
MultivaluedMap<String, String> params, String parameterName) {
String value = params.getFirst(parameterName);
if (value == null) {
return null;
}
if ("true".equalsIgnoreCase(value)) {
return true;
}
if ("false".equalsIgnoreCase(value)) {
return false;
}
throw new AwsException("InvalidParameterValue",
parameterName + " must be true or false.", 400);
}
private static Integer parseOptionalInteger(
MultivaluedMap<String, String> params, String parameterName) {
String value = params.getFirst(parameterName);
if (value == null) {
return null;
}
try {
return Integer.valueOf(value);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue",
parameterName + " must be an integer.", 400);
}
}
private static Map<String, String> parseTags(MultivaluedMap<String, String> params) {
Map<String, String> tags = new LinkedHashMap<>();
readTags(params, "Tags.member", tags);
File diff suppressed because it is too large. Load diff
@@ -8,22 +8,48 @@ import java.io.Closeable;
public class RdsContainerHandle {
private final String containerId;
private final String runtimeId;
private final String instanceId;
private final String host;
private final int port;
private final String storageKey;
private final String containerKey;
private Closeable logStream;
public RdsContainerHandle(String containerId, String instanceId, String host, int port) {
this(containerId, instanceId, instanceId, host, port, null);
}
public RdsContainerHandle(
String containerId, String runtimeId, String instanceId, String host, int port) {
this(containerId, runtimeId, instanceId, host, port, null);
}
public RdsContainerHandle(
String containerId, String runtimeId, String instanceId,
String host, int port, String storageKey) {
this(containerId, runtimeId, instanceId, host, port, storageKey, null);
}
public RdsContainerHandle(
String containerId, String runtimeId, String instanceId,
String host, int port, String storageKey, String containerKey) {
this.containerId = containerId;
this.runtimeId = runtimeId == null || runtimeId.isBlank() ? instanceId : runtimeId;
this.instanceId = instanceId;
this.host = host;
this.port = port;
this.storageKey = storageKey;
this.containerKey = containerKey;
}
public String getContainerId() { return containerId; }
public String getRuntimeId() { return runtimeId; }
public String getInstanceId() { return instanceId; }
public String getHost() { return host; }
public int getPort() { return port; }
public String getStorageKey() { return storageKey; }
public String getContainerKey() { return containerKey; }
public Closeable getLogStream() { return logStream; }
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.rds.container;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -26,9 +27,11 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Manages backend Docker container lifecycle for RDS DB instances and clusters.
@@ -38,6 +41,7 @@ import java.util.concurrent.TimeUnit;
public class RdsContainerManager {
private static final Logger LOG = Logger.getLogger(RdsContainerManager.class);
private static final Pattern SAFE_STORAGE_COMPONENT = Pattern.compile("[A-Za-z0-9._-]+");
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -47,6 +51,8 @@ public class RdsContainerManager {
private final RegionResolver regionResolver;
private final ServiceConfigAccess serviceConfigAccess;
private final Map<String, RdsContainerHandle> activeContainers = new ConcurrentHashMap<>();
private final Map<String, String> activeStorageOwners = new ConcurrentHashMap<>();
private final Set<String> claimedRuntimes = ConcurrentHashMap.newKeySet();
@Inject
public RdsContainerManager(ContainerBuilder containerBuilder,
@@ -68,75 +74,212 @@ public class RdsContainerManager {
public RdsContainerHandle start(String instanceId, String volumeId, DatabaseEngine engine,
String image, String masterUsername,
String masterPassword, String dbName) {
return start(instanceId, instanceId, volumeId, engine, image,
masterUsername, masterPassword, dbName);
}
public RdsContainerHandle start(
String runtimeId, String instanceId, String volumeId, DatabaseEngine engine,
String image, String masterUsername, String masterPassword, String dbName) {
String exactVolumeName = ContainerStorageHelper.resourceName(
config, "rds", volumeId, instanceId);
return start(runtimeId, instanceId, instanceId, exactVolumeName,
engine, image, masterUsername, masterPassword, dbName);
}
public RdsContainerHandle start(
String runtimeId, String instanceId, String containerStorageResourceId,
String dockerVolumeName, DatabaseEngine engine, String image,
String masterUsername, String masterPassword, String dbName) {
LOG.infov("Starting RDS backend container for instance: {0} engine={1}", instanceId, engine);
String effectiveRuntimeId = runtimeId == null || runtimeId.isBlank()
? instanceId : runtimeId;
String storageResourceId = requireSafeStorageComponent(
containerStorageResourceId, "container storage resource ID");
String exactVolumeName = requireSafeStorageComponent(
dockerVolumeName, "Docker volume name");
int enginePort = engine.defaultPort();
String containerName = ContainerStorageHelper.resourceName(config, "rds", volumeId, instanceId);
String containerName = exactVolumeName;
String storageKey = storageKey(storageResourceId, exactVolumeName);
String containerKey = "container:" + containerName;
if (!claimedRuntimes.add(effectiveRuntimeId)) {
throw new IllegalStateException(
"RDS runtime " + effectiveRuntimeId + " already has an active container");
}
try {
claimStorage(storageKey, effectiveRuntimeId);
} catch (RuntimeException | Error e) {
claimedRuntimes.remove(effectiveRuntimeId);
throw e;
}
try {
claimStorage(containerKey, effectiveRuntimeId);
} catch (RuntimeException | Error e) {
releaseOwnership(storageKey, null, effectiveRuntimeId);
throw e;
}
// Remove any stale container with the same name
lifecycleManager.removeIfExists(containerName);
String cleanupContainerId = containerName;
RdsContainerHandle handle = null;
try {
// Remove any stale container with the same name only after storage ownership is secured.
lifecycleManager.removeIfExistsStrict(containerName);
cleanupContainerId = null;
// Build environment variables
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
// Build environment variables
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
// Build container spec with bind mounts for persistence. Publish the
// engine port to the host only in native mode; in Docker mode the auth
// proxy reaches the DB via the container network.
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv(envVars)
.withDockerNetwork(config.services().rds().dockerNetwork())
.withLogRotation();
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv(envVars)
.withDockerNetwork(config.services().rds().dockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(enginePort);
} else {
specBuilder.withExposedPort(enginePort);
}
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(enginePort);
} else {
specBuilder.withExposedPort(enginePort);
}
// Handle persistence mounting
addPersistenceMounts(specBuilder, instanceId, volumeId, engine, image);
addPersistenceMounts(
specBuilder, storageResourceId, exactVolumeName, engine, image);
// Add engine-specific command
List<String> cmd = buildContainerCmd(engine);
if (!cmd.isEmpty()) {
specBuilder.withCmd(cmd);
}
List<String> cmd = buildContainerCmd(engine);
if (!cmd.isEmpty()) {
specBuilder.withCmd(cmd);
}
ContainerSpec spec = specBuilder.build();
ContainerSpec spec = specBuilder.build();
// Create and start container
ContainerInfo info = lifecycleManager.createAndStart(spec);
EndpointInfo endpoint = info.getEndpoint(enginePort);
// Create and start container separately so a failed start retains the cleanup identity.
// The fixed name remains a valid cleanup identity if create succeeds but its response
// is lost before Docker returns the generated ID.
cleanupContainerId = containerName;
String createdContainerId = lifecycleManager.create(spec);
cleanupContainerId = createdContainerId;
ContainerInfo info = lifecycleManager.startCreated(createdContainerId, spec);
EndpointInfo endpoint = info.getEndpoint(enginePort);
LOG.infov("RDS backend for instance {0}: {1}", instanceId, endpoint);
initializeEngine(containerName, info.containerId(), engine, masterUsername);
LOG.infov("RDS backend for instance {0}: {1}", instanceId, endpoint);
initializeEngine(containerName, info.containerId(), engine, masterUsername);
RdsContainerHandle handle = new RdsContainerHandle(
info.containerId(), instanceId, endpoint.host(), endpoint.port());
activeContainers.put(instanceId, handle);
handle = new RdsContainerHandle(
info.containerId(), effectiveRuntimeId, instanceId,
endpoint.host(), endpoint.port(), storageKey, containerKey);
// Attach log streaming
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/rds/instance/" + instanceId + "/error";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/rds/instance/" + instanceId + "/error";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
String accountId = null;
try {
AwsArnUtils.Arn runtimeArn = AwsArnUtils.parse(effectiveRuntimeId);
if ("rds".equals(runtimeArn.service())) {
if (!runtimeArn.region().isBlank()) {
region = runtimeArn.region();
}
if (!runtimeArn.accountId().isBlank()) {
accountId = runtimeArn.accountId();
}
}
} catch (IllegalArgumentException ignored) {
LOG.debugv("Using legacy RDS runtime identity for log routing: {0}",
effectiveRuntimeId);
}
Closeable logHandle = logStreamer.attach(
info.containerId(), logGroup, logStream, region, "rds:" + instanceId);
handle.setLogStream(logHandle);
Closeable logHandle = accountId != null
? logStreamer.attachForAccount(
accountId, info.containerId(), logGroup, logStream, region,
"rds:" + effectiveRuntimeId)
: logStreamer.attach(
info.containerId(), logGroup, logStream, region,
"rds:" + effectiveRuntimeId);
handle.setLogStream(logHandle);
activeContainers.put(effectiveRuntimeId, handle);
return handle;
return handle;
} catch (RuntimeException | Error e) {
if (handle != null) {
activeContainers.remove(effectiveRuntimeId, handle);
}
boolean cleaned = cleanupContainerId == null;
if (cleanupContainerId != null) {
try {
lifecycleManager.stopAndRemoveStrict(
cleanupContainerId,
handle != null ? handle.getLogStream() : null);
cleaned = true;
} catch (RuntimeException | Error cleanupFailure) {
e.addSuppressed(cleanupFailure);
RdsContainerHandle retained = handle != null ? handle
: new RdsContainerHandle(
cleanupContainerId, effectiveRuntimeId, instanceId,
null, 0, storageKey, containerKey);
activeContainers.put(effectiveRuntimeId, retained);
LOG.errorv(cleanupFailure,
"Failed to clean up RDS container {0}; retaining storage ownership for {1}",
cleanupContainerId, effectiveRuntimeId);
}
}
if (cleaned) {
releaseOwnership(storageKey, containerKey, effectiveRuntimeId);
}
throw e;
}
}
public void stop(RdsContainerHandle handle) {
if (handle == null) {
return;
}
activeContainers.remove(handle.getInstanceId());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
RdsContainerHandle active = activeContainers.get(handle.getRuntimeId());
RdsContainerHandle effectiveHandle = active != null ? active : handle;
try {
lifecycleManager.stopAndRemoveStrict(
effectiveHandle.getContainerId(), effectiveHandle.getLogStream());
} catch (RuntimeException | Error e) {
activeContainers.putIfAbsent(effectiveHandle.getRuntimeId(), effectiveHandle);
claimedRuntimes.add(effectiveHandle.getRuntimeId());
throw e;
}
activeContainers.remove(effectiveHandle.getRuntimeId(), effectiveHandle);
releaseOwnership(
effectiveHandle.getStorageKey(), effectiveHandle.getContainerKey(),
effectiveHandle.getRuntimeId());
}
/**
* Retries cleanup for a runtime retained after an earlier stop failure.
*
* <p>The persisted RDS model intentionally clears stale Docker endpoint fields after a failed
* restore. The runtime ARN remains stable and is therefore the safe lookup key for a later
* delete retry.
*/
public void stopByRuntimeId(String runtimeId) {
if (runtimeId == null || runtimeId.isBlank()) {
return;
}
RdsContainerHandle active = activeContainers.get(runtimeId);
if (active != null) {
stop(active);
}
}
/** Returns the retained runtime handle used to persist cleanup identity after a failed start. */
public RdsContainerHandle getActiveHandle(String runtimeId) {
if (runtimeId == null || runtimeId.isBlank()) {
return null;
}
return activeContainers.get(runtimeId);
}
public void stopAll() {
@@ -145,21 +288,28 @@ public class RdsContainerManager {
LOG.infov("Stopping {0} RDS container(s) on shutdown", handles.size());
}
for (RdsContainerHandle handle : handles) {
stop(handle);
try {
stop(handle);
} catch (RuntimeException | Error e) {
LOG.warnv(e, "Failed to stop RDS container {0} during shutdown; continuing",
handle.getContainerId());
}
}
}
private void addPersistenceMounts(ContainerBuilder.Builder specBuilder, String instanceId,
String volumeId, DatabaseEngine engine, String image) {
private void addPersistenceMounts(
ContainerBuilder.Builder specBuilder, String storageResourceId,
String exactVolumeName, DatabaseEngine engine, String image) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.applyStorage(
specBuilder, lifecycleManager, config, "rds", volumeId, instanceId,
ContainerStorageHelper.applyNamedVolume(
specBuilder, lifecycleManager, exactVolumeName,
engineDefaultDataPath(engine, image));
return;
}
// Legacy host-path mode: host-persistent-path is an absolute path
String hostDataPath = ContainerStorageHelper.hostResourcePath(config, "rds", instanceId).toString();
String hostDataPath = ContainerStorageHelper.hostResourcePath(
config, "rds", storageResourceId).toString();
if (!containerDetector.isRunningInContainer()) {
ContainerStorageHelper.ensureHostDir(hostDataPath);
}
@@ -303,12 +453,66 @@ public class RdsContainerManager {
record ContainerExecResult(long exitCode, String output) {}
public void removeVolume(String instanceId, String volumeId) {
removeVolume(instanceId, instanceId,
ContainerStorageHelper.resourceName(config, "rds", volumeId, instanceId));
}
public void removeVolume(
String runtimeId, String containerStorageResourceId, String dockerVolumeName) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.removeStorage(config, lifecycleManager, "rds", volumeId, instanceId);
requireSafeStorageComponent(
containerStorageResourceId, "container storage resource ID");
String exactVolumeName = requireSafeStorageComponent(
dockerVolumeName, "Docker volume name");
String key = "volume:" + exactVolumeName;
String owner = activeStorageOwners.get(key);
if (owner != null) {
throw new IllegalStateException(
"Refusing to remove active RDS storage " + exactVolumeName
+ ", owned by " + owner);
}
ContainerStorageHelper.removeNamedVolumeStrict(
config, lifecycleManager, exactVolumeName);
}
// host-path mode: host directories are not removed automatically
}
private String storageKey(String storageResourceId, String exactVolumeName) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
return "volume:" + exactVolumeName;
}
Path hostPath = ContainerStorageHelper.hostResourcePath(
config, "rds", storageResourceId).toAbsolutePath().normalize();
return "path:" + hostPath;
}
private void claimStorage(String storageKey, String runtimeId) {
String existingOwner = activeStorageOwners.putIfAbsent(storageKey, runtimeId);
if (existingOwner != null && !existingOwner.equals(runtimeId)) {
throw new IllegalStateException(
"RDS storage " + storageKey + " is already owned by " + existingOwner);
}
}
private void releaseOwnership(String storageKey, String containerKey, String runtimeId) {
if (storageKey != null) {
activeStorageOwners.remove(storageKey, runtimeId);
}
if (containerKey != null) {
activeStorageOwners.remove(containerKey, runtimeId);
}
claimedRuntimes.remove(runtimeId);
}
private static String requireSafeStorageComponent(String value, String label) {
if (value == null || value.isBlank()
|| ".".equals(value) || "..".equals(value)
|| !SAFE_STORAGE_COMPONENT.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid " + label + ": " + value);
}
return value;
}
private List<String> buildEnvVars(DatabaseEngine engine, String masterUsername,
String masterPassword, String dbName) {
String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres";
@@ -36,6 +36,7 @@ public class DbCluster {
private String dockerVolumeName;
private String volumeId;
private String containerStorageResourceId;
// Transient — not persisted
private transient String containerId;
@@ -143,6 +144,11 @@ public class DbCluster {
public String getVolumeId() { return volumeId; }
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
public String getContainerStorageResourceId() { return containerStorageResourceId; }
public void setContainerStorageResourceId(String containerStorageResourceId) {
this.containerStorageResourceId = containerStorageResourceId;
}
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
@@ -11,6 +11,7 @@ public class DbClusterParameterGroup {
private String dbClusterParameterGroupName;
private String dbParameterGroupFamily;
private String description;
private String region;
private Map<String, String> parameters = new HashMap<>();
public DbClusterParameterGroup() {}
@@ -31,6 +32,9 @@ public class DbClusterParameterGroup {
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
}
@@ -41,6 +41,7 @@ public class DbInstance {
private String dockerVolumeName;
private String volumeId;
private String containerStorageResourceId;
private transient String containerId;
private transient String containerHost;
@@ -166,6 +167,11 @@ public class DbInstance {
public String getVolumeId() { return volumeId; }
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
public String getContainerStorageResourceId() { return containerStorageResourceId; }
public void setContainerStorageResourceId(String containerStorageResourceId) {
this.containerStorageResourceId = containerStorageResourceId;
}
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
@@ -4,5 +4,5 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum DbInstanceStatus {
CREATING, AVAILABLE, DELETING, REBOOTING, MODIFYING
CREATING, AVAILABLE, DELETING, REBOOTING, MODIFYING, FAILED
}
@@ -11,6 +11,7 @@ public class DbParameterGroup {
private String dbParameterGroupName;
private String dbParameterGroupFamily;
private String description;
private String region;
private Map<String, String> parameters = new HashMap<>();
public DbParameterGroup() {}
@@ -31,6 +32,9 @@ public class DbParameterGroup {
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
}
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* An {@code AWS::RDS::DBProxy}. In real AWS a DB Proxy fronts a target DB cluster/instance behind a
* pooled endpoint. Floci models the control-plane resource and can attach a second auth relay (see
* {@code RdsProxyManager}) that forwards to the registered target's backend container. Distinct
* externally reachable same-engine proxy endpoints require endpoint routing beyond this model.
*/
@RegisterForReflection
public class DbProxy {
private String dbProxyName; // physical id + Ref return value
private String dbProxyArn; // GetAtt "DBProxyArn"
private String dbProxyResourceId; // "prx-XXXX..."
private String endpointHost; // proxy endpoint hostname
private int proxyPort; // relay port (engine family default, or a pool port if taken)
private String engineFamily; // POSTGRESQL | MYSQL | SQLSERVER (as sent by the client)
private boolean requireTls = true;
private boolean iamAuth; // effective relay auth from DefaultAuthScheme/Auth[]
private String defaultAuthScheme = "NONE"; // NONE | IAM_AUTH
private String roleArn;
private int idleClientTimeout = 1800;
private boolean debugLogging;
private String status = "available";
private Instant createdAt;
private Instant updatedAt;
private String vpcId;
private String endpointNetworkType = "IPV4";
private String targetConnectionNetworkType = "IPV4";
private List<String> vpcSubnetIds = new ArrayList<>();
private List<String> vpcSecurityGroupIds = new ArrayList<>();
private List<DbProxyAuth> auth = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
public DbProxy() {}
/** AWS RDS Proxy exposes a bare hostname and clients connect on the engine's default port. */
public String getEndpoint() {
return endpointHost;
}
public String getDbProxyName() { return dbProxyName; }
public void setDbProxyName(String dbProxyName) { this.dbProxyName = dbProxyName; }
public String getDbProxyArn() { return dbProxyArn; }
public void setDbProxyArn(String dbProxyArn) { this.dbProxyArn = dbProxyArn; }
public String getDbProxyResourceId() { return dbProxyResourceId; }
public void setDbProxyResourceId(String dbProxyResourceId) { this.dbProxyResourceId = dbProxyResourceId; }
public String getEndpointHost() { return endpointHost; }
public void setEndpointHost(String endpointHost) { this.endpointHost = endpointHost; }
public int getProxyPort() { return proxyPort; }
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
public String getEngineFamily() { return engineFamily; }
public void setEngineFamily(String engineFamily) { this.engineFamily = engineFamily; }
public boolean isRequireTls() { return requireTls; }
public void setRequireTls(boolean requireTls) { this.requireTls = requireTls; }
public boolean isIamAuth() { return iamAuth; }
public void setIamAuth(boolean iamAuth) { this.iamAuth = iamAuth; }
public String getDefaultAuthScheme() { return defaultAuthScheme; }
public void setDefaultAuthScheme(String defaultAuthScheme) {
this.defaultAuthScheme = defaultAuthScheme;
}
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
public int getIdleClientTimeout() { return idleClientTimeout; }
public void setIdleClientTimeout(int idleClientTimeout) { this.idleClientTimeout = idleClientTimeout; }
public boolean isDebugLogging() { return debugLogging; }
public void setDebugLogging(boolean debugLogging) { this.debugLogging = debugLogging; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public String getEndpointNetworkType() { return endpointNetworkType; }
public void setEndpointNetworkType(String endpointNetworkType) {
this.endpointNetworkType = endpointNetworkType;
}
public String getTargetConnectionNetworkType() { return targetConnectionNetworkType; }
public void setTargetConnectionNetworkType(String targetConnectionNetworkType) {
this.targetConnectionNetworkType = targetConnectionNetworkType;
}
public List<String> getVpcSubnetIds() { return vpcSubnetIds; }
public void setVpcSubnetIds(List<String> vpcSubnetIds) {
this.vpcSubnetIds = vpcSubnetIds != null ? new ArrayList<>(vpcSubnetIds) : new ArrayList<>();
}
public List<String> getVpcSecurityGroupIds() { return vpcSecurityGroupIds; }
public void setVpcSecurityGroupIds(List<String> vpcSecurityGroupIds) {
this.vpcSecurityGroupIds = vpcSecurityGroupIds != null ? new ArrayList<>(vpcSecurityGroupIds) : new ArrayList<>();
}
public List<DbProxyAuth> getAuth() { return auth; }
public void setAuth(List<DbProxyAuth> auth) {
this.auth = auth != null ? new ArrayList<>(auth) : new ArrayList<>();
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); }
}
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** One entry of an {@code AWS::RDS::DBProxy} {@code Auth} array (a secret-based auth descriptor). */
@RegisterForReflection
public class DbProxyAuth {
private String authScheme; // "SECRETS"
private String secretArn;
private String iamAuth; // "REQUIRED" | "DISABLED"
private String clientPasswordAuthType; // nullable
private String description; // nullable
private String userName; // nullable; used by end-to-end IAM authentication
public DbProxyAuth() {}
public DbProxyAuth(String authScheme, String secretArn, String iamAuth,
String clientPasswordAuthType, String description) {
this.authScheme = authScheme;
this.secretArn = secretArn;
this.iamAuth = iamAuth;
this.clientPasswordAuthType = clientPasswordAuthType;
this.description = description;
}
public String getAuthScheme() { return authScheme; }
public void setAuthScheme(String authScheme) { this.authScheme = authScheme; }
public String getSecretArn() { return secretArn; }
public void setSecretArn(String secretArn) { this.secretArn = secretArn; }
public String getIamAuth() { return iamAuth; }
public void setIamAuth(String iamAuth) { this.iamAuth = iamAuth; }
public String getClientPasswordAuthType() { return clientPasswordAuthType; }
public void setClientPasswordAuthType(String clientPasswordAuthType) { this.clientPasswordAuthType = clientPasswordAuthType; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** A registered target of an {@code AWS::RDS::DBProxyTargetGroup} (a DB cluster or instance). */
@RegisterForReflection
public class DbProxyTarget {
private String type; // "TRACKED_CLUSTER" | "RDS_INSTANCE"
private String rdsResourceId; // the cluster/instance identifier
private String targetArn;
private String endpoint; // target backend host
private int port;
private String targetHealth = "AVAILABLE";
public DbProxyTarget() {}
public DbProxyTarget(String type, String rdsResourceId, String targetArn, String endpoint, int port) {
this.type = type;
this.rdsResourceId = rdsResourceId;
this.targetArn = targetArn;
this.endpoint = endpoint;
this.port = port;
}
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getRdsResourceId() { return rdsResourceId; }
public void setRdsResourceId(String rdsResourceId) { this.rdsResourceId = rdsResourceId; }
public String getTargetArn() { return targetArn; }
public void setTargetArn(String targetArn) { this.targetArn = targetArn; }
public String getEndpoint() { return endpoint; }
public void setEndpoint(String endpoint) { this.endpoint = endpoint; }
public int getPort() { return port; }
public void setPort(int port) { this.port = port; }
public String getTargetHealth() { return targetHealth; }
public void setTargetHealth(String targetHealth) { this.targetHealth = targetHealth; }
}
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* The (single, always named {@code "default"}) target group of an {@code AWS::RDS::DBProxy}. Holds
* the registered targets and the connection-pool configuration.
*/
@RegisterForReflection
public class DbProxyTargetGroup {
private String dbProxyName; // owner + physical id
private String targetGroupName = "default";
private String targetGroupArn;
private String status = "available";
private boolean defaultTargetGroup = true;
private Instant createdAt;
private Instant updatedAt;
private int maxConnectionsPercent = 100;
private int maxIdleConnectionsPercent = 50;
private int connectionBorrowTimeout = 120;
private String initQuery;
private List<String> sessionPinningFilters = new ArrayList<>();
private List<DbProxyTarget> targets = new ArrayList<>();
public DbProxyTargetGroup() {}
public String getDbProxyName() { return dbProxyName; }
public void setDbProxyName(String dbProxyName) { this.dbProxyName = dbProxyName; }
public String getTargetGroupName() { return targetGroupName; }
public void setTargetGroupName(String targetGroupName) { this.targetGroupName = targetGroupName; }
public String getTargetGroupArn() { return targetGroupArn; }
public void setTargetGroupArn(String targetGroupArn) { this.targetGroupArn = targetGroupArn; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public boolean isDefaultTargetGroup() { return defaultTargetGroup; }
public void setDefaultTargetGroup(boolean defaultTargetGroup) { this.defaultTargetGroup = defaultTargetGroup; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
public int getMaxConnectionsPercent() { return maxConnectionsPercent; }
public void setMaxConnectionsPercent(int maxConnectionsPercent) { this.maxConnectionsPercent = maxConnectionsPercent; }
public int getMaxIdleConnectionsPercent() { return maxIdleConnectionsPercent; }
public void setMaxIdleConnectionsPercent(int maxIdleConnectionsPercent) { this.maxIdleConnectionsPercent = maxIdleConnectionsPercent; }
public int getConnectionBorrowTimeout() { return connectionBorrowTimeout; }
public void setConnectionBorrowTimeout(int connectionBorrowTimeout) {
this.connectionBorrowTimeout = connectionBorrowTimeout;
}
public String getInitQuery() { return initQuery; }
public void setInitQuery(String initQuery) { this.initQuery = initQuery; }
public List<String> getSessionPinningFilters() { return sessionPinningFilters; }
public void setSessionPinningFilters(List<String> sessionPinningFilters) {
this.sessionPinningFilters = sessionPinningFilters != null
? new ArrayList<>(sessionPinningFilters) : new ArrayList<>();
}
public List<DbProxyTarget> getTargets() { return targets; }
public void setTargets(List<DbProxyTarget> targets) {
this.targets = targets != null ? new ArrayList<>(targets) : new ArrayList<>();
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
@@ -47,7 +48,9 @@ public class RdsAuthProxy {
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(proxyPort));
running = true;
Thread.ofVirtual().name("rds-proxy-accept-" + instanceId).start(this::acceptLoop);
LOG.infov("RDS proxy started for instance {0} on port {1} → {2}:{3}",
@@ -61,8 +64,9 @@ public class RdsAuthProxy {
serverSocket.close();
}
} catch (IOException e) {
LOG.warnv("Error closing RDS proxy server socket for instance {0}: {1}",
instanceId, e.getMessage());
LOG.warnv(e, "Error closing RDS proxy server socket for instance {0}", instanceId);
throw new RuntimeException(
"Failed to stop RDS proxy for instance " + instanceId, e);
}
}
@@ -101,7 +105,11 @@ public class RdsAuthProxy {
}
private static void closeQuietly(Socket s) {
try { s.close(); } catch (IOException ignored) {}
try {
s.close();
} catch (IOException e) {
LOG.debugv(e, "Error closing RDS proxy client socket");
}
}
/**
@@ -24,33 +24,78 @@ public class RdsProxyManager {
this.sigV4Validator = sigV4Validator;
}
public void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
RdsAuthProxy proxy = new RdsAuthProxy(
instanceId, backendHost, backendPort, engine, iamEnabled,
masterUsername, masterPassword, dbName, sigV4Validator, passwordValidator);
try {
proxy.start(proxyPort);
proxies.put(instanceId, proxy);
} catch (IOException e) {
throw new RuntimeException("Failed to start RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
RuntimeException failure = new RuntimeException(
"Failed to start RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
cleanupFailedStart(proxy, failure);
throw failure;
} catch (RuntimeException e) {
RuntimeException failure = new RuntimeException(
"Failed to register RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
cleanupFailedStart(proxy, failure);
throw failure;
}
RdsAuthProxy previous;
try {
previous = proxies.put(instanceId, proxy);
} catch (RuntimeException e) {
RuntimeException failure = new RuntimeException(
"Failed to register RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
cleanupFailedStart(proxy, failure);
throw failure;
}
if (previous != null) {
try {
previous.stop();
} catch (RuntimeException e) {
proxies.put(instanceId, previous);
RuntimeException failure = new RuntimeException(
"Failed to replace RDS proxy for instance " + instanceId, e);
cleanupFailedStart(proxy, failure);
throw failure;
}
}
}
public void stopProxy(String instanceId) {
RdsAuthProxy proxy = proxies.remove(instanceId);
public synchronized void stopProxy(String instanceId) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {
proxy.stop();
proxies.remove(instanceId, proxy);
LOG.infov("Stopped RDS proxy for instance {0}", instanceId);
}
}
public void stopAll() {
proxies.values().forEach(RdsAuthProxy::stop);
proxies.clear();
public synchronized void stopAll() {
proxies.forEach((instanceId, proxy) -> {
try {
proxy.stop();
proxies.remove(instanceId, proxy);
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to stop RDS proxy for instance {0} during shutdown",
instanceId);
}
});
LOG.info("Stopped all RDS proxies");
}
private void cleanupFailedStart(RdsAuthProxy proxy, RuntimeException failure) {
try {
proxy.stop();
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
}
}
@@ -64,13 +64,15 @@ public class RdsDataController {
@POST
@Path("/CommitTransaction")
public Response commitTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.commitTransaction(request)).build());
return handle(headers, body, (request, region) ->
Response.ok(service.commitTransaction(request, region)).build());
}
@POST
@Path("/RollbackTransaction")
public Response rollbackTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.rollbackTransaction(request)).build());
return handle(headers, body, (request, region) ->
Response.ok(service.rollbackTransaction(request, region)).build());
}
private Response handle(HttpHeaders headers, String body, Handler handler) {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.rdsdata;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
@@ -19,33 +20,42 @@ class RdsDataResourceResolver {
}
DatabaseTarget resolve(String resourceArn) {
return resolve(resourceArn, null);
}
DatabaseTarget resolve(String resourceArn, String requestRegion) {
if (resourceArn == null || resourceArn.isBlank()) {
throw new AwsException("BadRequestException", "resourceArn is required.", 400);
}
for (DbCluster cluster : rdsService.listDbClusters(null)) {
if (resourceArn.equals(cluster.getDbClusterArn())) {
return fromCluster(cluster);
try {
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
if (!"rds".equals(arn.service())) {
throw new IllegalArgumentException("not an RDS ARN");
}
}
for (DbInstance instance : rdsService.listDbInstances(null)) {
if (resourceArn.equals(instance.getDbInstanceArn())) {
return fromInstance(instance);
if (requestRegion != null && !requestRegion.isBlank()
&& !requestRegion.equals(arn.region())) {
throw new IllegalArgumentException("RDS ARN is outside the request region");
}
}
String id = identifierFromArn(resourceArn);
if (id != null) {
try {
return fromCluster(rdsService.getDbCluster(id));
} catch (AwsException ignored) {
// Try instances below.
int separator = arn.resource().indexOf(':');
if (separator <= 0 || separator == arn.resource().length() - 1) {
throw new IllegalArgumentException("invalid RDS resource");
}
try {
return fromInstance(rdsService.getDbInstance(id));
} catch (AwsException ignored) {
// Fall through to the Data API error shape.
String type = arn.resource().substring(0, separator);
String id = arn.resource().substring(separator + 1);
if ("cluster".equals(type)) {
DbCluster cluster = rdsService.getDbCluster(id, arn.region());
if (resourceArn.equals(cluster.getDbClusterArn())) {
return fromCluster(cluster);
}
} else if ("db".equals(type)) {
DbInstance instance = rdsService.getDbInstance(id, arn.region());
if (resourceArn.equals(instance.getDbInstanceArn())) {
return fromInstance(instance);
}
}
} catch (AwsException | IllegalArgumentException ignored) {
// Normalize lookup and ARN parsing failures to the RDS Data API error shape below.
}
throw new AwsException("BadRequestException",
@@ -71,18 +81,6 @@ class RdsDataResourceResolver {
return new DatabaseTarget(arn, engine, host, port, username, password, databaseName);
}
private static String identifierFromArn(String arn) {
int marker = arn.lastIndexOf(":cluster:");
if (marker >= 0) {
return arn.substring(marker + ":cluster:".length());
}
marker = arn.lastIndexOf(":db:");
if (marker >= 0) {
return arn.substring(marker + ":db:".length());
}
return null;
}
record DatabaseTarget(String arn, DatabaseEngine engine, String host, int port,
String username, String password, String databaseName) {
}
@@ -120,13 +120,14 @@ public class RdsDataService implements Resettable {
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionIdentity(tx, request);
validateTransactionIdentity(tx, request, region);
tx.refresh(transactionTtl);
return executeOnConnection(tx.connection, tx.engine, sql, parameters, includeMetadata);
}
}
RdsDataResourceResolver.DatabaseTarget target = resourceResolver.resolve(resourceArn);
RdsDataResourceResolver.DatabaseTarget target =
resourceResolver.resolve(resourceArn, region);
Credentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
try (Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
@@ -141,7 +142,8 @@ public class RdsDataService implements Resettable {
cleanupExpiredTransactions();
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
RdsDataResourceResolver.DatabaseTarget target = resourceResolver.resolve(resourceArn);
RdsDataResourceResolver.DatabaseTarget target =
resourceResolver.resolve(resourceArn, region);
Credentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
@@ -150,7 +152,8 @@ public class RdsDataService implements Resettable {
connection = connectionFactory.open(target, credentials.username(), credentials.password(), database);
connection.setAutoCommit(false);
String transactionId = UUID.randomUUID().toString();
transactions.put(transactionId, new TransactionContext(transactionId, connection, target.engine(), target.arn(), database, transactionTtl));
transactions.put(transactionId, new TransactionContext(
transactionId, connection, target.engine(), target.arn(), database, region, transactionTtl));
ObjectNode response = objectMapper.createObjectNode();
response.put("transactionId", transactionId);
@@ -163,14 +166,14 @@ public class RdsDataService implements Resettable {
}
}
public ObjectNode commitTransaction(JsonNode request) {
public ObjectNode commitTransaction(JsonNode request, String region) {
String transactionId = requiredText(request, "transactionId");
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionResource(tx, resourceArn);
validateTransactionResource(tx, resourceArn, region);
if (!transactions.remove(transactionId, tx)) {
throw transactionNotFound(transactionId);
}
@@ -187,14 +190,14 @@ public class RdsDataService implements Resettable {
return response;
}
public ObjectNode rollbackTransaction(JsonNode request) {
public ObjectNode rollbackTransaction(JsonNode request, String region) {
String transactionId = requiredText(request, "transactionId");
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionResource(tx, resourceArn);
validateTransactionResource(tx, resourceArn, region);
if (!transactions.remove(transactionId, tx)) {
throw transactionNotFound(transactionId);
}
@@ -371,21 +374,26 @@ public class RdsDataService implements Resettable {
}
}
private void validateTransactionIdentity(TransactionContext tx, JsonNode request) {
validateTransactionResource(tx, requiredText(request, "resourceArn"));
private void validateTransactionIdentity(
TransactionContext tx, JsonNode request, String region) {
validateTransactionResource(tx, requiredText(request, "resourceArn"), region);
String database = textOrNull(request, "database");
if (database != null && !database.isBlank() && !database.equals(tx.database)) {
throw transactionNotFound(tx.id);
}
}
private void validateTransactionResource(TransactionContext tx, String resourceArn) {
private void validateTransactionResource(
TransactionContext tx, String resourceArn, String region) {
if (region == null || region.isBlank() || !region.equals(tx.region)) {
throw transactionNotFound(tx.id);
}
if (resourceArn.equals(tx.resourceArn)) {
return;
}
RdsDataResourceResolver.DatabaseTarget target;
try {
target = resourceResolver.resolve(resourceArn);
target = resourceResolver.resolve(resourceArn, region);
} catch (AwsException e) {
throw transactionNotFound(tx.id);
}
@@ -485,14 +493,18 @@ public class RdsDataService implements Resettable {
private final DatabaseEngine engine;
private final String resourceArn;
private final String database;
private final String region;
private volatile Instant expiresAt;
private TransactionContext(String id, Connection connection, DatabaseEngine engine, String resourceArn, String database, Duration ttl) {
private TransactionContext(
String id, Connection connection, DatabaseEngine engine, String resourceArn,
String database, String region, Duration ttl) {
this.id = id;
this.connection = connection;
this.engine = engine;
this.resourceArn = resourceArn;
this.database = database;
this.region = region;
refresh(ttl);
}