fix(rds): run MySQL and MariaDB with their parameter group values (#5981)

* fix(rds): run MySQL and MariaDB with their parameter group values

A DB cluster parameter group or DB parameter group was stored but never
reached the engine: the container started with only the authentication
option, so the database kept MySQL's built-in defaults.

Every container start (create, reboot, stop and start, emulator restart)
now passes the group's overrides as --loose-<name>=<value> server options:
the cluster parameter group for a cluster, the DB parameter group for a
standalone instance. The loose prefix makes the server skip an Aurora-only
parameter with a warning. Formula values and the parameters that decide
where the server listens and keeps its data are left out, and Floci's
authentication options come last so the proxy keeps working.

DescribeDBClusters now reports DBClusterParameterGroup.

Fixes #5946

* fix(rds): layer the Aurora writer's parameter group and switch groups on modify

Review follow-up:

- require_secure_transport and skip_grant_tables are no longer passed to
  the server, like port and socket: Floci's proxy talks to MySQL without
  TLS, and skip_grant_tables turns networking off, so either would lock
  every client out.
- An Aurora cluster's engine now runs with its DB cluster parameter group
  and the writer instance's DB parameter group on top, so an
  instance-level value such as max_connections reaches the database.
  Creating the writer restarts the cluster's container when its group
  changes the engine's options; every later start reads the writer's
  group too.
- ModifyDBCluster takes DBClusterParameterGroupName and ModifyDBInstance
  takes DBParameterGroupName. The group is checked against the engine
  before anything else in the request is applied, recorded at once, and
  used from the database's next start (a reboot), as on AWS.

* fix(rds): apply Aurora groups on a writer reboot and report incompatible-parameters

Review follow-up:

- RebootDBInstance on an Aurora cluster's writer restarts the database the
  cluster's members share, which is how AWS applies a changed DB cluster
  parameter group or writer DB parameter group. A reader's reboot still
  only restarts its endpoint.
- time_zone reaches the server as --default-time-zone, since MySQL has no
  time_zone option, and Aurora's binlog_format=OFF, which turns binary
  logging off and which MySQL refuses as a value, as --skip-log-bin.
- A server that stops while starting with its parameter group's options
  leaves no container, and its instance, or every member of its cluster,
  reports incompatible-parameters until a reboot starts it with values the
  server accepts. Floci logs the server's error lines.
- DescribeDBClusters names a default DB cluster parameter group only when
  DescribeDBClusterParameterGroups lists it.
- The integration test reboots the writer rather than the cluster, checks
  that binary logging is off, covers a refused value, and skips through
  RdsRequests.assumeDocker.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
Younes BerianeandPriamo authored and GitHub committed 2026-10-23 23:15:19 -04:00
1 parent 54b3db771a
commit 16c159e5b2
9 files changed
+1431 -140

No files matched your search

@@ -766,7 +766,8 @@ public class RdsQueryHandler {
DbInstance instance = service.modifyDbInstance(
id, newPassword, iamEnabled, dbSubnetGroupName,
vpcSecurityGroupIds, optionGroupName, region, autoMinorVersionUpgrade,
settings, publiclyAccessible, scaling, deletionProtection);
settings, publiclyAccessible, scaling, deletionProtection,
params.getFirst("DBParameterGroupName"));
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -1423,7 +1424,8 @@ public class RdsQueryHandler {
}
DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, region);
manageMasterUserPassword, masterUserSecretKmsKeyId,
params.getFirst("DBClusterParameterGroupName"), region);
if (enableHttpEndpoint != null) {
cluster = service.setHttpEndpoint(region, id, enableHttpEndpoint);
}
@@ -2942,7 +2944,7 @@ public class RdsQueryHandler {
private String dbInstanceInnerXml(DbInstance i) {
DbEndpoint ep = i.getEndpoint();
String engineStr = instanceEngine(i);
String statusStr = i.getStatus() != null ? statusLabel(i.getStatus()) : "available";
String statusStr = statusLabel(reportedStatus(i));
XmlBuilder xml = new XmlBuilder()
.elem("DBInstanceIdentifier", i.getDbInstanceIdentifier())
@@ -3143,6 +3145,25 @@ public class RdsQueryHandler {
.end("Tag"));
}
/**
* The cluster's DB cluster parameter group, or the engine's default group when it was created
* without one, as AWS reports it. Null when the engine has no default group that
* DescribeDBClusterParameterGroups lists.
*/
private String dbClusterParameterGroupName(DbCluster cluster, String engine) {
String name = cluster.getParameterGroupName();
if (name != null && !name.isBlank()) {
return name;
}
String defaultGroup;
try {
defaultGroup = "default." + service.expectedClusterParameterGroupFamily(engine, cluster.getEngineVersion());
} catch (AwsException e) {
return null;
}
return service.isManagedClusterParameterGroup(defaultGroup) ? defaultGroup : null;
}
private String dbClusterXml(DbCluster c) {
return new XmlBuilder().start("DBCluster").raw(dbClusterInnerXml(c)).end("DBCluster").build();
}
@@ -3190,8 +3211,12 @@ public class RdsQueryHandler {
.elem("Status", "active")
.end("VpcSecurityGroupMembership")
.end("VpcSecurityGroups")
.elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default")
.elem("DbClusterResourceId", c.getDbClusterResourceId())
.elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default");
String clusterParameterGroup = dbClusterParameterGroupName(c, engineStr);
if (clusterParameterGroup != null) {
xml.elem("DBClusterParameterGroup", clusterParameterGroup);
}
xml.elem("DbClusterResourceId", c.getDbClusterResourceId())
.elem("DBClusterArn", c.getDbClusterArn());
if (c.getMasterUserSecretArn() != null && !c.getMasterUserSecretArn().isBlank()) {
xml.start("MasterUserSecret")
@@ -3435,6 +3460,13 @@ public class RdsQueryHandler {
.build();
}
/** An available instance whose database refused its parameter group reports incompatible-parameters, as on AWS. */
private DbInstanceStatus reportedStatus(DbInstance instance) {
DbInstanceStatus status = instance.getStatus() != null ? instance.getStatus() : DbInstanceStatus.AVAILABLE;
return status == DbInstanceStatus.AVAILABLE && service.databaseRefusedParameterGroup(instance)
? DbInstanceStatus.INCOMPATIBLE_PARAMETERS : status;
}
private String statusLabel(DbInstanceStatus status) {
return switch (status) {
case CREATING -> "creating";
@@ -3446,6 +3478,7 @@ public class RdsQueryHandler {
case STOPPING -> "stopping";
case STOPPED -> "stopped";
case STARTING -> "starting";
case INCOMPATIBLE_PARAMETERS -> "incompatible-parameters";
};
}
@@ -817,14 +817,15 @@ public class RdsService implements Resettable, ResourceProvider {
RdsContainerHandle handle = containerManager.tryStart(
dbInstanceArn, id, instanceStorageResourceId,
instanceDockerVolumeName, engine, image,
masterUsername, masterPassword, dbName);
masterUsername, masterPassword, dbName,
instanceEngineParameters(currentAccountId(), effectiveRegion, paramGroupName));
if (handle != null) {
backendHost = handle.getHost();
backendPort = handle.getPort();
containerId = handle.getContainerId();
containerHost = handle.getHost();
containerPort = handle.getPort();
} else {
} else if (!containerManager.refusedParameterGroup(dbInstanceArn)) {
LOG.warnv("DB instance {0} created without a backing database container: no "
+ "Docker daemon is reachable. Metadata operations work; connections to "
+ "the database do not until a daemon appears.", id);
@@ -880,6 +881,14 @@ public class RdsService implements Resettable, ResourceProvider {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster is not available for member creation.", 400);
}
if (!mock && currentCluster.resolveWriterIdentifier() == null) {
try {
applyWriterParameterGroup(currentCluster, paramGroupName, effectiveRegion);
} catch (RuntimeException | Error e) {
releaseProxyPort(proxyPort);
throw e;
}
}
backendHost = currentCluster.getContainerHost();
backendPort = currentCluster.getContainerPort();
instance.setContainerId(currentCluster.getContainerId());
@@ -3092,10 +3101,26 @@ public class RdsService implements Resettable, ResourceProvider {
String optionGroupName, String region, Boolean autoMinorVersionUpgrade,
DbInstanceSettings settings, Boolean publiclyAccessible,
DbInstanceScalingChanges scaling, Boolean deletionProtection) {
return modifyDbInstance(id, newPassword, iamEnabled, dbSubnetGroupName,
vpcSecurityGroupIds, optionGroupName, region, autoMinorVersionUpgrade,
settings, publiclyAccessible, scaling, deletionProtection, null);
}
/**
* Like AWS, a new {@code dbParameterGroupName} is recorded at once and the engine runs with
* it from its next start, such as a reboot.
*/
public DbInstance modifyDbInstance(
String id, String newPassword, Boolean iamEnabled,
String dbSubnetGroupName, List<String> vpcSecurityGroupIds,
String optionGroupName, String region, Boolean autoMinorVersionUpgrade,
DbInstanceSettings settings, Boolean publiclyAccessible,
DbInstanceScalingChanges scaling, Boolean deletionProtection,
String dbParameterGroupName) {
return withInstancePublication(id, region, () -> doModifyDbInstance(
id, newPassword, iamEnabled, dbSubnetGroupName, vpcSecurityGroupIds,
optionGroupName, region, autoMinorVersionUpgrade,
settings, publiclyAccessible, scaling, deletionProtection));
settings, publiclyAccessible, scaling, deletionProtection, dbParameterGroupName));
}
private synchronized DbInstance doModifyDbInstance(
@@ -3103,7 +3128,8 @@ public class RdsService implements Resettable, ResourceProvider {
String dbSubnetGroupName, List<String> vpcSecurityGroupIds,
String optionGroupName, String region, Boolean autoMinorVersionUpgrade,
DbInstanceSettings settings, Boolean publiclyAccessible,
DbInstanceScalingChanges scaling, Boolean deletionProtection) {
DbInstanceScalingChanges scaling, Boolean deletionProtection,
String dbParameterGroupName) {
validateInstanceSettings(settings);
String effectiveRegion = effectiveRegion(region);
DbInstance instance = getDbInstance(id, effectiveRegion);
@@ -3123,7 +3149,15 @@ public class RdsService implements Resettable, ResourceProvider {
effective = effective.withStorageType(null);
}
validateAutoscalingMinimum(instance, effective.maxAllocatedStorage());
boolean changesParameterGroup = dbParameterGroupName != null && !dbParameterGroupName.isBlank();
if (changesParameterGroup) {
validateInstanceParameterGroup(dbParameterGroupName, engineName(instance),
instance.getEngineVersion(), effectiveRegion);
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
if (changesParameterGroup) {
instance.setParameterGroupName(dbParameterGroupName);
}
if (optionGroupName != null && !optionGroupName.isBlank()) {
validateInstanceOptionGroup(optionGroupName,
instance.getEngine() == null ? null : instance.getEngine().name().toLowerCase(),
@@ -3557,7 +3591,8 @@ public class RdsService implements Resettable, ResourceProvider {
handle = containerManager.tryStart(
instance.getDbInstanceArn(), id, storageResourceId,
dockerVolumeName, instance.getEngine(), image, instance.getMasterUsername(),
instance.getMasterPassword(), instance.getDbName());
instance.getMasterPassword(), instance.getDbName(),
instanceEngineParameters(instance));
} catch (RuntimeException | Error e) {
instance.setStatus(DbInstanceStatus.FAILED);
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
@@ -3720,8 +3755,36 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.setContainerPort(0);
}
/**
* The first member of a cluster becomes its writer, whose DB parameter group is layered over
* the cluster's group. A running engine is restarted with it when that changes the options
* the engine runs with; one not started yet picks it up when it starts.
*/
private void applyWriterParameterGroup(
DbCluster cluster, String writerParameterGroupName, String effectiveRegion) {
if (cluster.getContainerId() == null || cluster.getEndpoint() == null) {
return;
}
Map<String, String> withWriter = clusterEngineParameters(cluster, writerParameterGroupName);
if (RdsContainerManager.engineParameterOptions(cluster.getEngine(), withWriter).equals(
RdsContainerManager.engineParameterOptions(
cluster.getEngine(), clusterEngineParameters(cluster, null)))) {
return;
}
String id = cluster.getDbClusterIdentifier();
String accountId = accountIdFromArn(cluster.getDbClusterArn());
stopDbClusterRuntime(cluster, id, effectiveRegion, accountId);
startClusterBackend(cluster, id, effectiveRegion, withWriter);
putClusterForScope(accountId, effectiveRegion, id, cluster);
}
/** Brings a cluster's container up on its existing volume and its proxy with it. */
private void startClusterBackend(DbCluster cluster, String id, String effectiveRegion) {
startClusterBackend(cluster, id, effectiveRegion, clusterEngineParameters(cluster));
}
private void startClusterBackend(DbCluster cluster, String id, String effectiveRegion,
Map<String, String> engineParameters) {
if (cluster.getEndpoint() == null) {
try {
ensureClusterBackend(id, effectiveRegion, false);
@@ -3740,7 +3803,7 @@ public class RdsService implements Resettable, ResourceProvider {
handle = containerManager.tryStart(
cluster.getDbClusterArn(), id, storageResourceId, dockerVolumeName,
cluster.getEngine(), image, cluster.getMasterUsername(), cluster.getMasterPassword(),
cluster.getDatabaseName());
cluster.getDatabaseName(), engineParameters);
} catch (RuntimeException | Error e) {
cluster.setStatus(DbInstanceStatus.FAILED);
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
@@ -3783,12 +3846,18 @@ public class RdsService implements Resettable, ResourceProvider {
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
boolean mock = config.services().rds().mock();
DbCluster writtenCluster = mock ? null : availableClusterWrittenBy(instance, id, effectiveRegion);
if (writtenCluster != null) {
return rebootClusterWriter(instance, id, writtenCluster, effectiveRegion);
}
boolean startAttempted = false;
if (!mock) {
// Stop proxy during reboot
proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
// Restart container if it's a standalone instance
if (instance.getDbClusterIdentifier() == null && instance.getContainerId() != null) {
startAttempted = true;
try {
containerManager.stop(buildHandle(instance));
} catch (RuntimeException | Error e) {
@@ -3806,7 +3875,8 @@ public class RdsService implements Resettable, ResourceProvider {
RdsContainerHandle handle = containerManager.tryStart(
instance.getDbInstanceArn(), id, storageResourceId,
dockerVolumeName, instance.getEngine(), image, instance.getMasterUsername(),
instance.getMasterPassword(), instance.getDbName());
instance.getMasterPassword(), instance.getDbName(),
instanceEngineParameters(instance));
instance.setContainerStorageResourceId(storageResourceId);
instance.setDockerVolumeName(dockerVolumeName);
instance.setContainerId(handle != null ? handle.getContainerId() : null);
@@ -3837,8 +3907,9 @@ public class RdsService implements Resettable, ResourceProvider {
proxyBinding(instance.getEngine(), instance.getEndpoint().address(),
instance.getEndpoint().port(), instanceRegion, accountId,
backendIdentity.dbUserResourceId()));
} else {
// No backing container: created or last rebooted while no daemon was reachable.
} else if (!startAttempted) {
// No backing container: created or last rebooted while no daemon was reachable,
// or its server did not start with its parameter group.
instance = doEnsureInstanceBackend(id, effectiveRegion);
}
}
@@ -3847,6 +3918,57 @@ public class RdsService implements Resettable, ResourceProvider {
return instance;
}
/** The available cluster whose writer {@code instance} is, or null. */
private DbCluster availableClusterWrittenBy(DbInstance instance, String id, String effectiveRegion) {
String clusterId = instance.getDbClusterIdentifier();
if (clusterId == null || clusterId.isBlank()) {
return null;
}
DbCluster cluster = findClusterForScope(
accountIdFromArn(instance.getDbInstanceArn()), effectiveRegion, clusterId);
if (cluster == null || !id.equals(cluster.resolveWriterIdentifier())
|| (cluster.getStatus() != null && cluster.getStatus() != DbInstanceStatus.AVAILABLE)) {
return null;
}
return cluster;
}
/**
* Rebooting an Aurora cluster's writer restarts the database the cluster's members share, which
* is how a changed DB cluster parameter group, or the writer's DB parameter group, reaches it.
*/
private DbInstance rebootClusterWriter(
DbInstance writer, String id, DbCluster cluster, String effectiveRegion) {
String clusterId = cluster.getDbClusterIdentifier();
String accountId = accountIdFromArn(cluster.getDbClusterArn());
try {
stopDbClusterRuntime(cluster, clusterId, effectiveRegion, accountId);
startClusterBackend(cluster, clusterId, effectiveRegion);
} catch (RuntimeException | Error e) {
writer.setStatus(DbInstanceStatus.FAILED);
try {
putInstanceForScope(accountId, effectiveRegion, id, writer);
} catch (RuntimeException persistFailure) {
e.addSuppressed(persistFailure);
}
throw e;
}
putClusterForScope(accountId, effectiveRegion, clusterId, cluster);
restoreClusterMemberBackends(cluster, effectiveRegion, true);
LOG.infov("DB instance {0} rebooted with the database of DB cluster {1}", id, clusterId);
return getDbInstance(id, effectiveRegion);
}
/**
* Whether the database an instance runs on did not start with its parameter group's values,
* which AWS reports as incompatible-parameters until a reboot starts it. A cluster member
* shares its cluster's database.
*/
public boolean databaseRefusedParameterGroup(DbInstance instance) {
return !config.services().rds().mock()
&& containerManager.refusedParameterGroup(instanceBackendRuntimeId(instance));
}
/** Returns the runtime that owns an instance's backing container. Cluster members share their cluster runtime. */
public String instanceBackendRuntimeId(DbInstance instance) {
return instanceBackendIdentity(instance).runtimeId();
@@ -3940,7 +4062,8 @@ public class RdsService implements Resettable, ResourceProvider {
started = containerManager.tryStart(
instance.getDbInstanceArn(), id, resolvedInstanceStorageResourceId(instance),
resolvedInstanceDockerVolumeName(instance), instance.getEngine(), image,
instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName());
instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName(),
instanceEngineParameters(instance));
if (started == null) {
return instance;
}
@@ -4045,7 +4168,8 @@ public class RdsService implements Resettable, ResourceProvider {
RdsContainerHandle started = containerManager.tryStart(
cluster.getDbClusterArn(), id, storageResourceId, dockerVolumeName,
cluster.getEngine(), image, cluster.getMasterUsername(),
cluster.getMasterPassword(), cluster.getDatabaseName());
cluster.getMasterPassword(), cluster.getDatabaseName(),
clusterEngineParameters(cluster));
if (started == null) {
return cluster;
}
@@ -4469,12 +4593,13 @@ public class RdsService implements Resettable, ResourceProvider {
RdsContainerHandle handle = containerManager.tryStart(
clusterArn, id, clusterResourceId, clusterDockerVolumeName,
engine, image,
masterUsername, masterPassword, databaseName);
masterUsername, masterPassword, databaseName,
clusterEngineParameters(currentAccountId(), effectiveRegion, paramGroupName));
if (handle != null) {
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
} else {
} else if (!containerManager.refusedParameterGroup(clusterArn)) {
LOG.warnv("DB cluster {0} created without a backing database container: no Docker "
+ "daemon is reachable. Metadata operations work; connections to the "
+ "database do not until a daemon appears.", id);
@@ -4860,6 +4985,20 @@ public class RdsService implements Resettable, ResourceProvider {
Integer serverlessV2SecondsUntilAutoPause,
Boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String region) {
return modifyDbCluster(id, newPassword, iamEnabled, serverlessV2MinCapacity,
serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, null, region);
}
/**
* Like AWS, a new {@code dbClusterParameterGroupName} is recorded at once and the engine runs
* with it from its next start, such as a reboot.
*/
public DbCluster modifyDbCluster(String id, String newPassword, Boolean iamEnabled,
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
Boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String dbClusterParameterGroupName, String region) {
String effectiveRegion = effectiveRegion(region);
while (true) {
DbCluster cluster = getDbCluster(id, effectiveRegion);
@@ -4871,7 +5010,8 @@ public class RdsService implements Resettable, ResourceProvider {
}
return doModifyDbCluster(id, newPassword, iamEnabled, serverlessV2MinCapacity,
serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, region);
manageMasterUserPassword, masterUserSecretKmsKeyId,
dbClusterParameterGroupName, region);
}
}
}
@@ -4881,9 +5021,15 @@ public class RdsService implements Resettable, ResourceProvider {
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
Boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String region) {
String dbClusterParameterGroupName, String region) {
String effectiveRegion = effectiveRegion(region);
DbCluster cluster = getDbCluster(id, effectiveRegion);
boolean changesParameterGroup = dbClusterParameterGroupName != null
&& !dbClusterParameterGroupName.isBlank();
if (changesParameterGroup) {
validateClusterParameterGroup(dbClusterParameterGroupName, engineName(cluster),
cluster.getEngineVersion(), effectiveRegion);
}
boolean modifiesServerlessV2Scaling = serverlessV2MinCapacity != null
|| serverlessV2MaxCapacity != null
|| serverlessV2SecondsUntilAutoPause != null;
@@ -4960,6 +5106,9 @@ public class RdsService implements Resettable, ResourceProvider {
&& !masterUserSecretKmsKeyId.equals(cluster.getMasterUserSecretKmsKeyId())) {
rekeyManagedMasterUserSecret(cluster, masterUserSecretKmsKeyId, effectiveRegion);
}
if (changesParameterGroup) {
cluster.setParameterGroupName(dbClusterParameterGroupName);
}
if (modifiesServerlessV2Scaling) {
cluster.setServerlessV2MinCapacity(effectiveMinCapacity);
cluster.setServerlessV2MaxCapacity(effectiveMaxCapacity);
@@ -8372,7 +8521,8 @@ public class RdsService implements Resettable, ResourceProvider {
restoredHandle = containerManager.tryStart(
cluster.getDbClusterArn(), cluster.getDbClusterIdentifier(),
storageResourceId, dockerVolumeName, cluster.getEngine(), image,
cluster.getMasterUsername(), cluster.getMasterPassword(), cluster.getDatabaseName());
cluster.getMasterUsername(), cluster.getMasterPassword(), cluster.getDatabaseName(),
clusterEngineParameters(cluster));
cluster.setContainerId(restoredHandle != null ? restoredHandle.getContainerId() : null);
cluster.setContainerHost(restoredHandle != null ? restoredHandle.getHost() : null);
cluster.setContainerPort(restoredHandle != null ? restoredHandle.getPort() : 0);
@@ -8514,7 +8664,8 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getDbInstanceArn(), instance.getDbInstanceIdentifier(),
instance.getContainerStorageResourceId(),
instance.getDockerVolumeName(), instance.getEngine(), image,
instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName());
instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName(),
instanceEngineParameters(instance));
backendHost = restoredHandle != null ? restoredHandle.getHost() : null;
backendPort = restoredHandle != null ? restoredHandle.getPort() : 0;
instance.setContainerId(restoredHandle != null ? restoredHandle.getContainerId() : null);
@@ -9090,6 +9241,84 @@ public class RdsService implements Resettable, ResourceProvider {
return legacy.orElse(null);
}
/** The overrides of a standalone instance's DB parameter group, which its engine runs with. */
private Map<String, String> instanceEngineParameters(DbInstance instance) {
return instanceEngineParameters(accountIdFromArn(instance.getDbInstanceArn()),
regionFromArn(instance.getDbInstanceArn()), instance.getParameterGroupName());
}
/**
* The overrides a DB parameter group sets, read in the account and region of the resource
* that uses it. A managed default group has none, and neither has a missing group.
*/
private Map<String, String> instanceEngineParameters(
String accountId, String region, String groupName) {
if (groupName == null || groupName.isBlank()) {
return Map.of();
}
String effectiveRegion = effectiveRegion(region);
DbParameterGroup group;
if (parameterGroups instanceof AccountAwareStorageBackend<DbParameterGroup> aware) {
group = aware.getForAccountMigratingLegacyKeys(
accountId, dbResourceKey(effectiveRegion, groupName), List.of(groupName),
candidate -> Objects.equals(groupName, candidate.getDbParameterGroupName())
&& parameterGroupBelongsToRegion(candidate, effectiveRegion),
Objects.equals(accountId, defaultAccountId())).orElse(null);
} else {
group = findParameterGroupForRegion(groupName, effectiveRegion);
}
return group == null || group.getParameters() == null
? Map.of() : new HashMap<>(group.getParameters());
}
/**
* The overrides a cluster's engine runs with: those of its DB cluster parameter group, with
* those of its writer's DB parameter group on top, as an instance-level value such as
* {@code max_connections} overrides the cluster's on AWS.
*/
private Map<String, String> clusterEngineParameters(DbCluster cluster) {
String writerId = cluster.resolveWriterIdentifier();
DbInstance writer = writerId == null ? null : findInstanceForScope(
accountIdFromArn(cluster.getDbClusterArn()),
effectiveRegion(regionFromArn(cluster.getDbClusterArn())), writerId);
return clusterEngineParameters(cluster, writer == null ? null : writer.getParameterGroupName());
}
private Map<String, String> clusterEngineParameters(
DbCluster cluster, String writerParameterGroupName) {
String accountId = accountIdFromArn(cluster.getDbClusterArn());
String region = regionFromArn(cluster.getDbClusterArn());
Map<String, String> parameters = new HashMap<>(
clusterEngineParameters(accountId, region, cluster.getParameterGroupName()));
parameters.putAll(instanceEngineParameters(accountId, region, writerParameterGroupName));
return parameters;
}
/**
* The overrides a DB cluster parameter group sets, read in the account and region of the
* cluster that uses it. A managed default group has none, and neither has a missing group.
*/
private Map<String, String> clusterEngineParameters(
String accountId, String region, String groupName) {
if (groupName == null || groupName.isBlank()) {
return Map.of();
}
String effectiveRegion = effectiveRegion(region);
DbClusterParameterGroup group;
if (clusterParameterGroups
instanceof AccountAwareStorageBackend<DbClusterParameterGroup> aware) {
group = aware.getForAccountMigratingLegacyKeys(
accountId, dbResourceKey(effectiveRegion, groupName), List.of(groupName),
candidate -> Objects.equals(groupName, candidate.getDbClusterParameterGroupName())
&& clusterParameterGroupBelongsToRegion(candidate, effectiveRegion),
Objects.equals(accountId, defaultAccountId())).orElse(null);
} else {
group = findClusterParameterGroupForRegion(groupName, effectiveRegion);
}
return group == null || group.getParameters() == null
? Map.of() : new HashMap<>(group.getParameters());
}
private synchronized DbParameterGroup findParameterGroupForRegion(
String groupName, String region) {
String effectiveRegion = effectiveRegion(region);
@@ -36,9 +36,11 @@ import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -59,6 +61,20 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
private static final Logger LOG = Logger.getLogger(RdsContainerManager.class);
private static final Pattern SAFE_STORAGE_COMPONENT = Pattern.compile("[A-Za-z0-9._-]+");
private static final Pattern MYSQL_PARAMETER_NAME = Pattern.compile("[A-Za-z][A-Za-z0-9_.-]*");
/**
* Where the server listens and keeps its data, which the proxy and the volume depend on, and
* the settings that would lock the proxy out: it talks to the server without TLS, so
* {@code require_secure_transport} refuses it, and {@code skip_grant_tables} turns
* networking off.
*/
private static final Set<String> FLOCI_CONTROLLED_MYSQL_PARAMETERS = Set.of(
"bind_address", "datadir", "port", "require_secure_transport", "skip_grant_tables",
"skip_networking", "socket");
/** RDS parameters whose server option has another name: {@code time_zone} has no option of its own. */
private static final Map<String, String> MYSQL_OPTION_NAMES = Map.of("time_zone", "default-time-zone");
/** How long a server started with a parameter group's options gets to start listening. */
private static final int PARAMETER_GROUP_START_SECONDS = 120;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -72,6 +88,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
private final Map<String, String> activeStorageOwners = new ConcurrentHashMap<>();
private final Set<String> claimedRuntimes = ConcurrentHashMap.newKeySet();
private final Set<String> cleanupPending = ConcurrentHashMap.newKeySet();
private final Set<String> parameterGroupRefusals = ConcurrentHashMap.newKeySet();
private volatile boolean dockerUnavailableLogged;
// Auto-pause state of every running container, by runtime id. The timer thread only keeps
// time: each task it fires runs on a virtual thread of its own, since a pause first asks the
@@ -157,19 +174,33 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
* start that failed before Docker created anything, and is dropped when the daemon is
* unreachable so the runtime can retry.
*
* @return the container handle, or {@code null} when no Docker daemon is reachable
* A server that stops while starting with its parameter group's options leaves no container
* either, and {@link #refusedParameterGroup} reports it until the runtime's next start.
*
* @param engineParameters the overrides of the parameter group the engine runs with
* @return the container handle, or {@code null} when no Docker daemon is reachable or the
* server refused its parameter group
*/
public RdsContainerHandle tryStart(
String runtimeId, String instanceId, String containerStorageResourceId,
String dockerVolumeName, DatabaseEngine engine, String image,
String masterUsername, String masterPassword, String dbName) {
String masterUsername, String masterPassword, String dbName,
Map<String, String> engineParameters) {
String effectiveRuntimeId = runtimeId == null || runtimeId.isBlank() ? instanceId : runtimeId;
parameterGroupRefusals.remove(effectiveRuntimeId);
try {
retryRetainedCleanup(effectiveRuntimeId);
RdsContainerHandle handle = start(runtimeId, instanceId, containerStorageResourceId,
dockerVolumeName, engine, image, masterUsername, masterPassword, dbName);
dockerVolumeName, engine, image, masterUsername, masterPassword, dbName,
engineParameters);
dockerUnavailableLogged = false;
return handle;
} catch (ParameterGroupRefusedException e) {
parameterGroupRefusals.add(effectiveRuntimeId);
LOG.warnv("The database of {0} did not start with its parameter group, so it reports "
+ "incompatible-parameters until a reboot starts it with values the server accepts: {1}",
instanceId, e.getMessage());
return null;
} catch (RuntimeException e) {
if (isDockerReachable()) {
throw e;
@@ -190,6 +221,14 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
}
}
/**
* Whether the runtime's last start found its server refusing the parameter group's options,
* which AWS reports as incompatible-parameters.
*/
public boolean refusedParameterGroup(String runtimeId) {
return runtimeId != null && parameterGroupRefusals.contains(runtimeId);
}
/**
* Probes the configured Docker endpoint, which is how a missing daemon is told apart from a
* container that failed for its own reasons.
@@ -231,6 +270,15 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
String runtimeId, String instanceId, String containerStorageResourceId,
String dockerVolumeName, DatabaseEngine engine, String image,
String masterUsername, String masterPassword, String dbName) {
return start(runtimeId, instanceId, containerStorageResourceId, dockerVolumeName,
engine, image, masterUsername, masterPassword, dbName, Map.of());
}
public RdsContainerHandle start(
String runtimeId, String instanceId, String containerStorageResourceId,
String dockerVolumeName, DatabaseEngine engine, String image,
String masterUsername, String masterPassword, String dbName,
Map<String, String> engineParameters) {
LOG.infov("Starting RDS backend container for instance: {0} engine={1}", instanceId, engine);
String effectiveRuntimeId = runtimeId == null || runtimeId.isBlank()
@@ -304,7 +352,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
specBuilder, storageResourceId, exactVolumeName, engine, image);
// Add engine-specific command
List<String> cmd = buildContainerCmd(engine, image);
List<String> cmd = buildContainerCmd(engine, image, engineParameters);
if (!cmd.isEmpty()) {
specBuilder.withCmd(cmd);
}
@@ -324,6 +372,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
EndpointInfo endpoint = info.getEndpoint(enginePort);
LOG.infov("RDS backend for instance {0}: {1}", instanceId, endpoint);
if (!engineParameterOptions(engine, engineParameters).isEmpty()) {
awaitServerWithParameterGroup(containerName, info.containerId(), enginePort);
}
initializeEngine(containerName, info.containerId(), engine, masterUsername, masterPassword, dbName);
handle = new RdsContainerHandle(
@@ -547,6 +598,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
for (String runtimeId : List.copyOf(autoPauses.keySet())) {
releaseAutoPause(runtimeId);
}
parameterGroupRefusals.clear();
}
@PreDestroy
@@ -898,6 +950,71 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
throw new IllegalStateException("Timed out initializing " + description + " in " + containerName + ": " + lastOutput);
}
/**
* Waits for a MySQL or MariaDB server started with a parameter group's options to accept TCP
* connections. The image checks the options before it starts anything, and the server reads
* them again as it starts, so a container that stops here refused one of them. A server still
* starting when the wait ends is left to finish, as one started without a group is.
*/
private void awaitServerWithParameterGroup(String containerName, String containerId, int enginePort) {
String[] probe = {"bash", "-c", ": < /dev/tcp/127.0.0.1/" + enginePort};
for (int attempt = 1; attempt <= PARAMETER_GROUP_START_SECONDS; attempt++) {
if (hasStopped(containerId)) {
throw new ParameterGroupRefusedException(serverErrors(containerId));
}
try {
if (execInContainer(containerId, probe, 5).exitCode() == 0) {
return;
}
} catch (RuntimeException e) {
LOG.debugv("RDS container {0} is not accepting connections yet: {1}", containerName, e.getMessage());
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted waiting for the server in " + containerName, e);
}
}
LOG.warnv("The server in RDS container {0} was still starting after {1} s", containerName,
PARAMETER_GROUP_START_SECONDS);
}
/** Whether Docker reports the container stopped; false when Docker cannot say. */
private boolean hasStopped(String containerId) {
try {
InspectContainerResponse.ContainerState state =
lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getState();
return state != null && Boolean.FALSE.equals(state.getRunning());
} catch (RuntimeException e) {
LOG.debugv("Could not inspect RDS container {0}: {1}", containerId, e.getMessage());
return false;
}
}
/** The error lines of a stopped server's log, or its last lines when it named no error. */
private String serverErrors(String containerId) {
List<String> lines;
try {
lines = readLog(containerId);
} catch (RuntimeException e) {
return "its log could not be read: " + e.getMessage();
}
if (lines == null || lines.isEmpty()) {
return "the server stopped without writing a log";
}
List<String> errors = lines.stream().filter(line -> line.contains("ERROR")).toList();
List<String> reported = errors.isEmpty() ? lines : errors;
return String.join(" | ", reported.subList(Math.max(0, reported.size() - 5), reported.size()));
}
/** A server that stopped while starting with a parameter group's options. */
private static final class ParameterGroupRefusedException extends IllegalStateException {
ParameterGroupRefusedException(String serverErrors) {
super(serverErrors);
}
}
/** The most recent lines {@link #readLog} reads, so one call never holds an unbounded history. */
public static final int MAX_LOG_LINES = 100_000;
@@ -1192,6 +1309,59 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
}
static List<String> buildContainerCmd(DatabaseEngine engine, String image) {
return buildContainerCmd(engine, image, Map.of());
}
/**
* The server options for an engine, with a parameter group's overrides ahead of the options
* Floci needs, so a group cannot take away the authentication plugin the proxy relies on.
*/
static List<String> buildContainerCmd(
DatabaseEngine engine, String image, Map<String, String> engineParameters) {
List<String> cmd = new ArrayList<>(engineParameterOptions(engine, engineParameters));
cmd.addAll(authenticationOptions(engine, image));
return cmd;
}
/**
* A parameter group's overrides as MySQL or MariaDB server options. Each takes the
* {@code --loose-} prefix, so a parameter only Aurora or RDS knows (or one an older server
* does not have) is skipped with a warning instead of stopping the server. A value that is a
* formula, such as {@code {DBInstanceClassMemory*3/4}}, is worked out by AWS from the
* instance class and is left to the server's default, as are the parameters that decide
* where the server listens and keeps its data, which Floci controls, and the ones that would
* lock Floci's proxy out. {@code time_zone} is set through {@code --default-time-zone}, and
* Aurora's {@code binlog_format=OFF}, which turns binary logging off, through
* {@code --skip-log-bin}.
*/
public static List<String> engineParameterOptions(
DatabaseEngine engine, Map<String, String> engineParameters) {
if (engineParameters == null || engineParameters.isEmpty()
|| (engine != DatabaseEngine.MYSQL && engine != DatabaseEngine.MARIADB)) {
return List.of();
}
List<String> options = new ArrayList<>();
for (Map.Entry<String, String> parameter : new TreeMap<>(engineParameters).entrySet()) {
String name = parameter.getKey();
String value = parameter.getValue();
if (name == null || value == null || !MYSQL_PARAMETER_NAME.matcher(name).matches()
|| value.contains("{")) {
continue;
}
String normalizedName = name.replace('-', '_').toLowerCase(Locale.ROOT);
if (FLOCI_CONTROLLED_MYSQL_PARAMETERS.contains(normalizedName)) {
continue;
}
if (normalizedName.equals("binlog_format") && value.equalsIgnoreCase("OFF")) {
options.add("--skip-log-bin");
continue;
}
options.add("--loose-" + MYSQL_OPTION_NAMES.getOrDefault(normalizedName, name) + "=" + value);
}
return options;
}
private static List<String> authenticationOptions(DatabaseEngine engine, String image) {
// Keep the backend handshake on mysql_native_password so the transparent proxy can
// validate the client scramble. MySQL 8.4 removed default-authentication-plugin and
// requires the native plugin to be enabled separately before selecting it as the default.
@@ -4,5 +4,6 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum DbInstanceStatus {
CREATING, AVAILABLE, DELETING, REBOOTING, MODIFYING, FAILED, STOPPING, STOPPED, STARTING
CREATING, AVAILABLE, DELETING, REBOOTING, MODIFYING, FAILED, STOPPING, STOPPED, STARTING,
INCOMPATIBLE_PARAMETERS
}