diff --git a/docs/services/rds.md b/docs/services/rds.md index 050fb41081..62a751ee6e 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -554,6 +554,29 @@ mysql -h 127.0.0.1 -P 7002 -u root -psecret123 Override the image per-instance with the `--engine-version` flag or globally via environment variables. Aurora MySQL versions such as `8.0.mysql_aurora.3.08.0` use the MySQL version in front, so that example runs `mysql:8.0`. +## Parameter groups + +A MySQL or MariaDB database runs with its parameter group: an Aurora MySQL cluster with its DB +cluster parameter group, with the writer instance's DB parameter group on top (so an +instance-level value such as `max_connections` wins, as on AWS), and a standalone instance with +its DB parameter group. Floci passes each override to the server when it starts the database +container, so a value set in the group is the engine's value; creating a cluster's writer restarts +the cluster's container when the writer's group changes anything. A later change to a group, or a +new `DBClusterParameterGroupName` on `ModifyDBCluster` or `DBParameterGroupName` on +`ModifyDBInstance`, takes effect the next time the container starts: `RebootDBInstance` on the +writer or on a standalone instance, a stop and start, or a Floci restart. A cluster's members share +one database, so rebooting the writer restarts it for every member, and a reader's own DB +parameter group is not applied. `time_zone` is passed as `--default-time-zone`, and Aurora's +`binlog_format` of `OFF` turns binary logging off. A parameter the server does not know, such as +one only Aurora has, is skipped with a warning in the database log. A formula value such as +`{DBInstanceClassMemory*3/4}` keeps the server's default, and so do `port`, `bind_address`, +`socket`, `datadir` and `skip_networking`, which Floci needs to reach the database, and +`require_secure_transport` and `skip_grant_tables`, which would lock out Floci's proxy (it talks +to the server without TLS). When the server refuses a value and stops, the instance, or every +member of the cluster, reports `incompatible-parameters` and Floci logs the server's error; correct +the group and reboot to start it again. PostgreSQL and SQL Server databases do not take parameter +group values yet. + ## Option Groups Option groups are metadata: Floci stores the options you add, returns them on the wire, and diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index f4d2d1e143..8fd36383df 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -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"; }; } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index e237710dde..43e1579aa6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -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 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 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 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 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 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 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 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 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 clusterEngineParameters( + DbCluster cluster, String writerParameterGroupName) { + String accountId = accountIdFromArn(cluster.getDbClusterArn()); + String region = regionFromArn(cluster.getDbClusterArn()); + Map 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 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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java index 6deac66f88..9043000f2c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java @@ -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 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 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 activeStorageOwners = new ConcurrentHashMap<>(); private final Set claimedRuntimes = ConcurrentHashMap.newKeySet(); private final Set cleanupPending = ConcurrentHashMap.newKeySet(); + private final Set 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 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 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 cmd = buildContainerCmd(engine, image); + List 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 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 errors = lines.stream().filter(line -> line.contains("ERROR")).toList(); + List 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 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 buildContainerCmd( + DatabaseEngine engine, String image, Map engineParameters) { + List 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 engineParameterOptions( + DatabaseEngine engine, Map engineParameters) { + if (engineParameters == null || engineParameters.isEmpty() + || (engine != DatabaseEngine.MYSQL && engine != DatabaseEngine.MARIADB)) { + return List.of(); + } + List options = new ArrayList<>(); + for (Map.Entry 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 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. diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java index 32862819b0..5536f3d812 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java @@ -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 } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsParameterGroupEngineIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsParameterGroupEngineIntegrationTest.java new file mode 100644 index 0000000000..6db3bd079a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsParameterGroupEngineIntegrationTest.java @@ -0,0 +1,348 @@ +package io.github.hectorvent.floci.services.rds; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.testing.RdsRequests.assumeDocker; +import static io.github.hectorvent.floci.testing.RdsRequests.deleteInstance; +import static io.github.hectorvent.floci.testing.RdsRequests.rds; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +/** + * A parameter group's overrides are the engine's configuration: an Aurora MySQL cluster runs with + * its DB cluster parameter group with its writer's DB parameter group on top, a standalone MySQL + * instance with its DB parameter group, and a value changed in the group, or a group switched by + * ModifyDBCluster or ModifyDBInstance, takes effect when the writer or the instance is rebooted. A + * value the server refuses leaves the instance incompatible-parameters. Skipped without Docker. + */ +@QuarkusTest +@Tag("docker") +class RdsParameterGroupEngineIntegrationTest { + + private static final String MASTER_USER = "admin"; + private static final String MASTER_PASSWORD = "Passw0rd12345"; + + @BeforeEach + void checkDocker() throws InterruptedException { + assumeDocker(); + } + + @Test + void auroraMysqlClusterRunsWithItsClusterParameterGroup() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String group = "engine-cpg-" + suffix; + String clusterId = "engine-cpg-cluster-" + suffix; + String writerId = "engine-cpg-writer-" + suffix; + rds("CreateDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", group) + .formParam("DBParameterGroupFamily", "aurora-mysql8.0") + .formParam("Description", "engine parameters") + .when().post("/").then().statusCode(200); + try { + rds("ModifyDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", group) + .formParam("Parameters.member.1.ParameterName", "max_connections") + .formParam("Parameters.member.1.ParameterValue", "500") + .formParam("Parameters.member.1.ApplyMethod", "immediate") + .formParam("Parameters.member.2.ParameterName", "slow_query_log") + .formParam("Parameters.member.2.ParameterValue", "1") + .formParam("Parameters.member.2.ApplyMethod", "immediate") + .formParam("Parameters.member.3.ParameterName", "long_query_time") + .formParam("Parameters.member.3.ParameterValue", "1") + .formParam("Parameters.member.3.ApplyMethod", "immediate") + // Exists only on Aurora: the engine must still start. + .formParam("Parameters.member.4.ParameterName", "aurora_binlog_replication_max_yield_seconds") + .formParam("Parameters.member.4.ParameterValue", "0") + .formParam("Parameters.member.4.ApplyMethod", "immediate") + // A formula is resolved by AWS from the instance class, so it is left out. + .formParam("Parameters.member.5.ParameterName", "innodb_buffer_pool_size") + .formParam("Parameters.member.5.ParameterValue", "{DBInstanceClassMemory*3/4}") + .formParam("Parameters.member.5.ApplyMethod", "pending-reboot") + // Aurora's way of turning binary logging off, which MySQL itself does not accept. + .formParam("Parameters.member.6.ParameterName", "binlog_format") + .formParam("Parameters.member.6.ParameterValue", "OFF") + .formParam("Parameters.member.6.ApplyMethod", "pending-reboot") + .when().post("/").then().statusCode(200); + + XmlPath created = rds("CreateDBCluster") + .formParam("DBClusterIdentifier", clusterId) + .formParam("Engine", "aurora-mysql") + .formParam("DBClusterParameterGroupName", group) + .formParam("MasterUsername", MASTER_USER) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/").then().statusCode(200).extract().xmlPath(); + int port = created.getInt("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.Port"); + + assertThat(query(port, "SELECT @@GLOBAL.max_connections, @@GLOBAL.slow_query_log, " + + "@@GLOBAL.long_query_time, @@GLOBAL.log_bin"), equalTo("500 1 1.0 0")); + + String reported = rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", clusterId) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getString("DescribeDBClustersResponse.DescribeDBClustersResult.DBClusters" + + ".DBCluster.DBClusterParameterGroup"); + assertThat(reported, equalTo(group)); + + createWriter(writerId, clusterId, null); + rds("ModifyDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", group) + .formParam("Parameters.member.1.ParameterName", "max_connections") + .formParam("Parameters.member.1.ParameterValue", "400") + .formParam("Parameters.member.1.ApplyMethod", "pending-reboot") + .when().post("/").then().statusCode(200); + rebootInstance(writerId); + + assertThat(query(port, "SELECT @@GLOBAL.max_connections"), equalTo("400")); + } finally { + deleteInstance(writerId); + rds("DeleteDBCluster") + .formParam("DBClusterIdentifier", clusterId) + .formParam("SkipFinalSnapshot", "true") + .when().post("/"); + rds("DeleteDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", group) + .when().post("/"); + } + } + + @Test + void auroraMysqlWriterRunsWithItsDbParameterGroupOverTheClusterGroup() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String clusterGroup = "engine-wcpg-" + suffix; + String switchedClusterGroup = "engine-wcpg2-" + suffix; + String writerGroup = "engine-wpg-" + suffix; + String clusterId = "engine-w-cluster-" + suffix; + String writerId = "engine-w-writer-" + suffix; + createClusterParameterGroup(clusterGroup, "max_connections", "500", "slow_query_log", "1"); + createClusterParameterGroup(switchedClusterGroup, "max_connections", "450", "slow_query_log", "0"); + createParameterGroup(writerGroup, "aurora-mysql8.0", "max_connections", "800"); + try { + int port = rds("CreateDBCluster") + .formParam("DBClusterIdentifier", clusterId) + .formParam("Engine", "aurora-mysql") + .formParam("DBClusterParameterGroupName", clusterGroup) + .formParam("MasterUsername", MASTER_USER) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getInt("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.Port"); + assertThat(query(port, "SELECT @@GLOBAL.max_connections, @@GLOBAL.slow_query_log"), + equalTo("500 1")); + + createWriter(writerId, clusterId, writerGroup); + assertThat(query(port, "SELECT @@GLOBAL.max_connections, @@GLOBAL.slow_query_log"), + equalTo("800 1")); + + String reported = rds("ModifyDBCluster") + .formParam("DBClusterIdentifier", clusterId) + .formParam("DBClusterParameterGroupName", switchedClusterGroup) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getString("ModifyDBClusterResponse.ModifyDBClusterResult.DBCluster.DBClusterParameterGroup"); + assertThat(reported, equalTo(switchedClusterGroup)); + rebootInstance(writerId); + assertThat(query(port, "SELECT @@GLOBAL.max_connections, @@GLOBAL.slow_query_log"), + equalTo("800 0")); + } finally { + deleteInstance(writerId); + rds("DeleteDBCluster") + .formParam("DBClusterIdentifier", clusterId) + .formParam("SkipFinalSnapshot", "true") + .when().post("/"); + for (String group : new String[] {clusterGroup, switchedClusterGroup}) { + rds("DeleteDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", group) + .when().post("/"); + } + rds("DeleteDBParameterGroup") + .formParam("DBParameterGroupName", writerGroup) + .when().post("/"); + } + } + + @Test + void mysqlInstanceRunsWithItsDbParameterGroup() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String group = "engine-pg-" + suffix; + String switchedGroup = "engine-pg2-" + suffix; + String instanceId = "engine-pg-db-" + suffix; + createParameterGroup(group, "mysql8.0", "max_connections", "300"); + createParameterGroup(switchedGroup, "mysql8.0", "max_connections", "600"); + try { + int port = createMysqlInstance(instanceId, group); + + assertThat(query(port, "SELECT @@GLOBAL.max_connections"), equalTo("300")); + + String reported = rds("ModifyDBInstance") + .formParam("DBInstanceIdentifier", instanceId) + .formParam("DBParameterGroupName", switchedGroup) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getString("ModifyDBInstanceResponse.ModifyDBInstanceResult.DBInstance" + + ".DBParameterGroups.DBParameterGroup.DBParameterGroupName"); + assertThat(reported, equalTo(switchedGroup)); + rebootInstance(instanceId); + assertThat(query(port, "SELECT @@GLOBAL.max_connections"), equalTo("600")); + } finally { + deleteInstance(instanceId); + for (String name : new String[] {group, switchedGroup}) { + rds("DeleteDBParameterGroup") + .formParam("DBParameterGroupName", name) + .when().post("/"); + } + } + } + + @Test + void mysqlInstanceWhoseServerRefusesAValueIsIncompatibleParametersUntilRebootedWithAFix() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String group = "engine-bad-" + suffix; + String instanceId = "engine-bad-db-" + suffix; + createParameterGroup(group, "mysql8.0", "sql_mode", "NOT_A_MODE"); + try { + int port = createMysqlInstance(instanceId, group); + assertThat(instanceStatus(instanceId), equalTo("incompatible-parameters")); + + rds("ModifyDBParameterGroup") + .formParam("DBParameterGroupName", group) + .formParam("Parameters.member.1.ParameterName", "sql_mode") + .formParam("Parameters.member.1.ParameterValue", "STRICT_TRANS_TABLES") + .formParam("Parameters.member.1.ApplyMethod", "immediate") + .when().post("/").then().statusCode(200); + rebootInstance(instanceId); + + assertThat(instanceStatus(instanceId), equalTo("available")); + assertThat(query(port, "SELECT @@GLOBAL.sql_mode"), equalTo("STRICT_TRANS_TABLES")); + } finally { + deleteInstance(instanceId); + rds("DeleteDBParameterGroup") + .formParam("DBParameterGroupName", group) + .when().post("/"); + } + } + + private static int createMysqlInstance(String instanceId, String parameterGroup) { + return rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", instanceId) + .formParam("Engine", "mysql") + .formParam("EngineVersion", "8.0") + .formParam("DBInstanceClass", "db.t3.micro") + .formParam("AllocatedStorage", "20") + .formParam("DBParameterGroupName", parameterGroup) + .formParam("MasterUsername", MASTER_USER) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port"); + } + + private static void createWriter(String writerId, String clusterId, String parameterGroup) { + RequestSpecification request = rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", writerId) + .formParam("DBClusterIdentifier", clusterId) + .formParam("Engine", "aurora-mysql") + .formParam("DBInstanceClass", "db.r6g.large"); + if (parameterGroup != null) { + request = request.formParam("DBParameterGroupName", parameterGroup); + } + request.when().post("/").then().statusCode(200); + } + + private static void rebootInstance(String instanceId) { + rds("RebootDBInstance") + .formParam("DBInstanceIdentifier", instanceId) + .when().post("/").then().statusCode(200); + } + + private static String instanceStatus(String instanceId) { + return rds("DescribeDBInstances") + .formParam("DBInstanceIdentifier", instanceId) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getString("DescribeDBInstancesResponse.DescribeDBInstancesResult.DBInstances" + + ".DBInstance.DBInstanceStatus"); + } + + private static void createParameterGroup(String name, String family, String parameter, String value) { + rds("CreateDBParameterGroup") + .formParam("DBParameterGroupName", name) + .formParam("DBParameterGroupFamily", family) + .formParam("Description", "engine parameters") + .when().post("/").then().statusCode(200); + rds("ModifyDBParameterGroup") + .formParam("DBParameterGroupName", name) + .formParam("Parameters.member.1.ParameterName", parameter) + .formParam("Parameters.member.1.ParameterValue", value) + .formParam("Parameters.member.1.ApplyMethod", "immediate") + .when().post("/").then().statusCode(200); + } + + private static void createClusterParameterGroup( + String name, String parameter, String value, String secondParameter, String secondValue) { + rds("CreateDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", name) + .formParam("DBParameterGroupFamily", "aurora-mysql8.0") + .formParam("Description", "engine parameters") + .when().post("/").then().statusCode(200); + rds("ModifyDBClusterParameterGroup") + .formParam("DBClusterParameterGroupName", name) + .formParam("Parameters.member.1.ParameterName", parameter) + .formParam("Parameters.member.1.ParameterValue", value) + .formParam("Parameters.member.1.ApplyMethod", "immediate") + .formParam("Parameters.member.2.ParameterName", secondParameter) + .formParam("Parameters.member.2.ParameterValue", secondValue) + .formParam("Parameters.member.2.ApplyMethod", "immediate") + .when().post("/").then().statusCode(200); + } + + /** + * The first row of a query, its columns joined by single spaces. The MySQL image restarts its + * server once after initializing a new data directory, so a refused connection is retried. + */ + private static String query(int port, String sql) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(90); + while (true) { + try { + return queryOnce(port, sql); + } catch (SQLException e) { + if (System.nanoTime() > deadline) { + throw e; + } + Thread.sleep(1000); + } + } + } + + private static String queryOnce(int port, String sql) throws SQLException { + Properties properties = new Properties(); + properties.setProperty("user", MASTER_USER); + properties.setProperty("password", MASTER_PASSWORD); + properties.setProperty("useSSL", "false"); + properties.setProperty("allowPublicKeyRetrieval", "true"); + // A server still initializing can accept a connection and never answer it: give up and retry. + properties.setProperty("connectTimeout", "10000"); + properties.setProperty("socketTimeout", "10000"); + try (Connection connection = DriverManager.getConnection( + "jdbc:mysql://127.0.0.1:" + port + "/", properties); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery(sql)) { + rows.next(); + StringBuilder row = new StringBuilder(); + for (int column = 1; column <= rows.getMetaData().getColumnCount(); column++) { + if (column > 1) { + row.append(' '); + } + row.append(rows.getString(column)); + } + return row.toString(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java index 2ab1d9d591..d266a64f77 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java @@ -250,7 +250,7 @@ class RdsQueryHandlerTest { Boolean enabled = value == null ? null : Boolean.parseBoolean(value); ArgumentCaptor settings = ArgumentCaptor.forClass(DbInstanceSettings.class); when(service.modifyDbInstance(eq("mydb"), isNull(), eq(enabled), isNull(), any(), isNull(), any(), - isNull(), settings.capture(), isNull(), any(DbInstanceScalingChanges.class), isNull())) + isNull(), settings.capture(), isNull(), any(DbInstanceScalingChanges.class), isNull(), isNull())) .thenReturn(makeInstance("mydb")); MultivaluedMap p = params(); p.putSingle("DBInstanceIdentifier", "mydb"); @@ -348,10 +348,46 @@ class RdsQueryHandlerTest { assertTrue(body.contains("true"), body); } + @Test + void describeDbInstances_reportsIncompatibleParametersWhenTheDatabaseRefusedItsGroup() { + DbInstance refused = makeInstance("refused"); + DbInstance rebooting = makeInstance("rebooting"); + rebooting.setStatus(DbInstanceStatus.REBOOTING); + when(service.listDbInstances(null, null)).thenReturn(List.of(refused, rebooting)); + when(service.databaseRefusedParameterGroup(any())).thenReturn(true); + + String body = (String) handler.handle("DescribeDBInstances", params()).getEntity(); + + assertTrue(body.contains("incompatible-parameters"), body); + assertTrue(body.contains("rebooting"), body); + } + + @Test + void describeDbClusters_namesOnlyADefaultClusterParameterGroupThatCanBeDescribed() { + DbCluster postgres = makeCluster("postgres-cluster"); + postgres.setEngineIdentifier("postgres"); + DbCluster mariadb = makeCluster("mariadb-cluster"); + mariadb.setEngineIdentifier("mariadb"); + mariadb.setEngine(DatabaseEngine.MARIADB); + mariadb.setEngineVersion("10.11"); + DbCluster named = makeCluster("named-cluster"); + named.setParameterGroupName("app-cluster-params"); + when(service.listDbClusters(null, null)).thenReturn(List.of(postgres, mariadb, named)); + when(service.expectedClusterParameterGroupFamily("postgres", "15")).thenReturn("postgres15"); + when(service.expectedClusterParameterGroupFamily("mariadb", "10.11")).thenReturn("mariadb10.11"); + when(service.isManagedClusterParameterGroup("default.postgres15")).thenReturn(true); + + String body = (String) handler.handle("DescribeDBClusters", params()).getEntity(); + + assertTrue(body.contains("default.postgres15"), body); + assertTrue(body.contains("app-cluster-params"), body); + assertFalse(body.contains("default.mariadb10.11"), body); + } + @Test void modifyDbInstance_forwardsPubliclyAccessible() { when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), - isNull(), any(DbInstanceSettings.class), eq(true), any(DbInstanceScalingChanges.class), isNull())) + isNull(), any(DbInstanceSettings.class), eq(true), any(DbInstanceScalingChanges.class), isNull(), isNull())) .thenReturn(makeInstance("mydb")); MultivaluedMap p = params(); p.putSingle("DBInstanceIdentifier", "mydb"); @@ -360,7 +396,7 @@ class RdsQueryHandlerTest { handler.handle("ModifyDBInstance", p); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), - isNull(), any(DbInstanceSettings.class), eq(true), any(DbInstanceScalingChanges.class), isNull()); + isNull(), any(DbInstanceSettings.class), eq(true), any(DbInstanceScalingChanges.class), isNull(), isNull()); } @Test @@ -374,7 +410,7 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(((String) response.getEntity()).contains("InvalidParameterValue")); verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), - any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any()); } @Test @@ -393,7 +429,7 @@ class RdsQueryHandlerTest { @Test void modifyDbInstance_forwardsDeletionProtection() { when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), - isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), eq(true))) + isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), eq(true), isNull())) .thenReturn(makeInstance("mydb")); MultivaluedMap p = params(); p.putSingle("DBInstanceIdentifier", "mydb"); @@ -402,7 +438,39 @@ class RdsQueryHandlerTest { handler.handle("ModifyDBInstance", p); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), - isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), eq(true)); + isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), eq(true), isNull()); + } + + @Test + void modifyDbInstance_forwardsDbParameterGroupName() { + when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), + isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull(), + eq("app-params"))) + .thenReturn(makeInstance("mydb")); + MultivaluedMap p = params(); + p.putSingle("DBInstanceIdentifier", "mydb"); + p.putSingle("DBParameterGroupName", "app-params"); + + assertEquals(200, handler.handle("ModifyDBInstance", p).getStatus()); + + verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), + isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull(), + eq("app-params")); + } + + @Test + void modifyDbCluster_forwardsDbClusterParameterGroupName() { + when(service.modifyDbCluster(eq("mycluster"), isNull(), isNull(), + isNull(), isNull(), isNull(), isNull(), isNull(), eq("app-cluster-params"), any())) + .thenReturn(makeCluster("mycluster")); + MultivaluedMap p = params(); + p.putSingle("DBClusterIdentifier", "mycluster"); + p.putSingle("DBClusterParameterGroupName", "app-cluster-params"); + + assertEquals(200, handler.handle("ModifyDBCluster", p).getStatus()); + + verify(service).modifyDbCluster(eq("mycluster"), isNull(), isNull(), + isNull(), isNull(), isNull(), isNull(), isNull(), eq("app-cluster-params"), any()); } @Test @@ -416,7 +484,7 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(((String) response.getEntity()).contains("InvalidParameterValue")); verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), - any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any()); } @Test @@ -651,13 +719,13 @@ class RdsQueryHandlerTest { when(service.getDbInstance("mydb", "us-west-2")).thenReturn(instance); when(service.modifyDbInstance( eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), - any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull())) + any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull(), isNull())) .thenReturn(instance); when(service.rebootDbInstance("mydb", "us-west-2")).thenReturn(instance); when(service.listDbClusters(null, "us-west-2")).thenReturn(List.of()); when(service.getDbCluster("mycluster", "us-west-2")).thenReturn(cluster); when(service.modifyDbCluster("mycluster", null, null, - null, null, null, null, null, "us-west-2")) + null, null, null, null, null, null, "us-west-2")) .thenReturn(cluster); handler.handle("DescribeDBInstances", params(), "us-west-2"); @@ -678,13 +746,13 @@ class RdsQueryHandlerTest { verify(service).deleteDbInstance("mydb", "us-west-2"); verify(service).modifyDbInstance( eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), - any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull()); + any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull(), isNull()); verify(service).rebootDbInstance("mydb", "us-west-2"); verify(service).listDbClusters(null, "us-west-2"); verify(service).getDbCluster("mycluster", "us-west-2"); verify(service).deleteDbCluster("mycluster", "us-west-2"); verify(service).modifyDbCluster("mycluster", null, null, - null, null, null, null, null, "us-west-2"); + null, null, null, null, null, null, "us-west-2"); } @Test @@ -764,7 +832,7 @@ class RdsQueryHandlerTest { void modifyDbClusterPassesManagedMasterUserSecretOptions() { DbCluster cluster = makeCluster("mycluster"); when(service.modifyDbCluster(eq("mycluster"), isNull(), isNull(), - isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), any())) + isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), isNull(), any())) .thenReturn(cluster); MultivaluedMap p = params(); @@ -774,7 +842,7 @@ class RdsQueryHandlerTest { handler.handle("ModifyDBCluster", p); verify(service).modifyDbCluster(eq("mycluster"), isNull(), isNull(), - isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), any()); + isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), isNull(), any()); } @Test @@ -951,7 +1019,7 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(((String) response.getEntity()).contains("InvalidParameterValue")); verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), - any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any()); } @Test @@ -3517,7 +3585,7 @@ class RdsQueryHandlerTest { DbInstance instance = makeInstance("mydb"); when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), isNull(), isNull(), any(DbInstanceSettings.class), isNull(), - any(DbInstanceScalingChanges.class), isNull())).thenReturn(instance); + any(DbInstanceScalingChanges.class), isNull(), isNull())).thenReturn(instance); MultivaluedMap p = params(); p.add("DBInstanceIdentifier", "mydb"); @@ -3531,7 +3599,7 @@ class RdsQueryHandlerTest { ArgumentCaptor captor = ArgumentCaptor.forClass(DbInstanceSettings.class); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), - isNull(), isNull(), captor.capture(), isNull(), any(DbInstanceScalingChanges.class), isNull()); + isNull(), isNull(), captor.capture(), isNull(), any(DbInstanceScalingChanges.class), isNull(), isNull()); assertEquals(new DbInstanceSettings(null, null, 3, "01:00-01:30", null, true), captor.getValue()); } @@ -3540,7 +3608,7 @@ class RdsQueryHandlerTest { DbInstance instance = makeInstance("mydb"); when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), isNull(), isNull(), any(DbInstanceSettings.class), isNull(), - any(DbInstanceScalingChanges.class), isNull())).thenReturn(instance); + any(DbInstanceScalingChanges.class), isNull(), isNull())).thenReturn(instance); MultivaluedMap p = params(); p.add("DBInstanceIdentifier", "mydb"); @@ -3553,7 +3621,7 @@ class RdsQueryHandlerTest { ArgumentCaptor captor = ArgumentCaptor.forClass(DbInstanceScalingChanges.class); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), - isNull(), isNull(), any(DbInstanceSettings.class), isNull(), captor.capture(), isNull()); + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), captor.capture(), isNull(), isNull()); assertEquals(new DbInstanceScalingChanges("db.t3.large", 100, "14.7", true), captor.getValue()); } @@ -3562,7 +3630,7 @@ class RdsQueryHandlerTest { DbInstance instance = makeInstance("mydb"); when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), isNull(), isNull(), any(DbInstanceSettings.class), isNull(), - any(DbInstanceScalingChanges.class), isNull())).thenReturn(instance); + any(DbInstanceScalingChanges.class), isNull(), isNull())).thenReturn(instance); MultivaluedMap p = params(); p.add("DBInstanceIdentifier", "mydb"); @@ -3572,7 +3640,7 @@ class RdsQueryHandlerTest { ArgumentCaptor captor = ArgumentCaptor.forClass(DbInstanceScalingChanges.class); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), - isNull(), isNull(), any(DbInstanceSettings.class), isNull(), captor.capture(), isNull()); + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), captor.capture(), isNull(), isNull()); assertEquals(DbInstanceScalingChanges.unchanged(), captor.getValue()); } @@ -3588,7 +3656,7 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(body.contains("InvalidParameterValue"), body); verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), - any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 6b05383680..1c9f371c42 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -186,7 +186,7 @@ class RdsServiceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 5432)); when(ec2Service.resolveDefaultVpcId(any())) .thenAnswer(invocation -> Ec2Service.defaultVpcId(invocation.getArgument(0))); @@ -243,7 +243,7 @@ class RdsServiceTest { assertEquals(DatabaseEngine.SQLSERVER, instance.getEngine()); assertEquals("sqlserver-se", instance.getEngineIdentifier()); verify(containerManager).tryStart(any(), any(), any(), any(), eq(DatabaseEngine.SQLSERVER), - eq("mcr.microsoft.com/mssql/server:2022-latest"), eq("sa"), eq("Password123!"), isNull()); + eq("mcr.microsoft.com/mssql/server:2022-latest"), eq("sa"), eq("Password123!"), isNull(), any()); } @Test @@ -302,7 +302,7 @@ class RdsServiceTest { }) void memberIamBindingUsesClusterResourceIdAcrossRuntimePaths(String engine, String path) { if ("retry".equals(path)) { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); } DbCluster cluster = rdsService.createDbCluster("iam-cluster", engine, null, @@ -316,7 +316,7 @@ class RdsServiceTest { if ("reboot".equals(path)) { rdsService.rebootDbInstance("iam-member"); } else { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("late-container", cluster.getDbClusterArn(), "iam-cluster", "127.0.0.1", 15432)); rdsService.ensureInstanceBackend("iam-member", "us-east-1"); @@ -798,7 +798,7 @@ class RdsServiceTest { Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults())); assertTrue(published.await(5, TimeUnit.SECONDS)); if ("reboot".equals(operation)) { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("replacement-container", "race-cluster", "new-backend", 6543)); } Future modification = workers.submit(() -> { @@ -912,7 +912,7 @@ class RdsServiceTest { DbInstance started = rdsService.ensureInstanceBackend("offline-member", "us-east-1"); assertNotNull(started.getContainerId()); verify(containerManager).tryStart(eq(cluster.getDbClusterArn()), eq("offline-credentials"), any(), any(), - eq(cluster.getEngine()), any(), eq("clusteradmin"), eq("AcceptedPassword!"), eq("dbname")); + eq(cluster.getEngine()), any(), eq("clusteradmin"), eq("AcceptedPassword!"), eq("dbname"), any()); verify(proxyManager).startProxy(eq("rds-resource:" + member.getDbInstanceArn()), eq(cluster.getDbClusterArn()), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), eq("clusteradmin"), eq("AcceptedPassword!"), eq("dbname"), any(), any()); @@ -1444,7 +1444,7 @@ class RdsServiceTest { rdsService.createDbCluster("dup-cluster", "postgres", "17.5", "admin", "password", "dbname", false, null, null, null, false)); assertEquals("DBClusterAlreadyExistsFault", exception.getErrorCode()); - verify(containerManager, times(1)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(1)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } /** @@ -1458,7 +1458,7 @@ class RdsServiceTest { void createDbClusterRejectsADuplicateWhileTheFirstIsStillProvisioning() throws Exception { CountDownLatch insideStart = new CountDownLatch(1); CountDownLatch releaseStart = new CountDownLatch(1); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> { insideStart.countDown(); assertTrue(releaseStart.await(5, TimeUnit.SECONDS), "test released the latch"); @@ -1483,7 +1483,7 @@ class RdsServiceTest { } finally { executor.shutdownNow(); } - verify(containerManager, times(1)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(1)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); assertNotNull(rdsService.getDbCluster("racy-cluster")); } @@ -1491,7 +1491,7 @@ class RdsServiceTest { void createDbInstanceRejectsADuplicateWhileTheFirstIsStillProvisioning() throws Exception { CountDownLatch insideStart = new CountDownLatch(1); CountDownLatch releaseStart = new CountDownLatch(1); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> { insideStart.countDown(); assertTrue(releaseStart.await(5, TimeUnit.SECONDS), "test released the latch"); @@ -1517,7 +1517,7 @@ class RdsServiceTest { } finally { executor.shutdownNow(); } - verify(containerManager, times(1)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(1)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); assertNotNull(rdsService.getDbInstance("racy-db")); } @@ -1531,7 +1531,7 @@ class RdsServiceTest { CountDownLatch insideStart = new CountDownLatch(1); CountDownLatch releaseStart = new CountDownLatch(1); AtomicBoolean firstCall = new AtomicBoolean(true); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> { if (firstCall.getAndSet(false)) { insideStart.countDown(); @@ -1566,7 +1566,7 @@ class RdsServiceTest { rdsService.deleteDbCluster("reused-cluster"); assertNotNull(rdsService.createDbCluster("reused-cluster", "postgres", "17.5", "admin", "password", "dbname", false, null, null, null, false)); - verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } /** The instance-side twin: a successful create must release the identifier too. */ @@ -1579,7 +1579,7 @@ class RdsServiceTest { assertNotNull(rdsService.createDbInstance("reused-db", "postgres", "17.5", "admin", "password", "dbname", "db.t3.micro", 20, false, null, null, null, null, false)); - verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } /** @@ -1629,7 +1629,7 @@ class RdsServiceTest { /** A failed create must release the identifier so a clean retry can proceed. */ @Test void createDbClusterFailureReleasesTheIdentifierForRetry() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new RuntimeException("image pull failed")) .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 5432)); @@ -1639,7 +1639,7 @@ class RdsServiceTest { assertNotNull(rdsService.createDbCluster("retry-cluster", "postgres", "17.5", "admin", "password", "dbname", false, null, null, null, false)); - verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test @@ -1651,7 +1651,231 @@ class RdsServiceTest { verify(containerManager).tryStart( eq("arn:aws:rds:us-east-1:123456789012:db:mydb"), eq("mydb"), any(), any(), eq(DatabaseEngine.POSTGRES), - eq("postgres:18.1-alpine"), eq("admin"), eq("password"), eq("dbname")); + eq("postgres:18.1-alpine"), eq("admin"), eq("password"), eq("dbname"), any()); + } + + @Test + void clusterContainerRunsWithItsClusterParameterGroupAndPicksUpChangesOnReboot() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 3306)); + rdsService.createDbClusterParameterGroup("app-cluster-params", "aurora-mysql8.0", "app"); + rdsService.modifyDbClusterParameterGroup("app-cluster-params", + Map.of("max_connections", "500", "slow_query_log", "1")); + + DbCluster cluster = rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, "app-cluster-params"); + + verify(containerManager).tryStart(eq(cluster.getDbClusterArn()), eq("app-cluster"), + any(), any(), any(), any(), any(), any(), any(), + eq(Map.of("max_connections", "500", "slow_query_log", "1"))); + + rdsService.modifyDbClusterParameterGroup("app-cluster-params", Map.of("max_connections", "400")); + rdsService.rebootDbCluster("app-cluster", "us-east-1"); + + verify(containerManager).tryStart(eq(cluster.getDbClusterArn()), eq("app-cluster"), + any(), any(), any(), any(), any(), any(), any(), + eq(Map.of("max_connections", "400", "slow_query_log", "1"))); + } + + @Test + void auroraWriterDbParameterGroupIsLayeredOverTheClusterParameterGroup() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 3306)); + rdsService.createDbClusterParameterGroup("app-cluster-params", "aurora-mysql8.0", "app"); + rdsService.modifyDbClusterParameterGroup("app-cluster-params", + Map.of("max_connections", "500", "slow_query_log", "1")); + rdsService.createDbParameterGroup("writer-params", "aurora-mysql8.0", "writer"); + rdsService.modifyDbParameterGroup("writer-params", Map.of("max_connections", "800")); + rdsService.createDbParameterGroup("reader-params", "aurora-mysql8.0", "reader"); + rdsService.modifyDbParameterGroup("reader-params", Map.of("max_connections", "50")); + DbCluster cluster = rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, "app-cluster-params"); + Map writerLayered = Map.of("max_connections", "800", "slow_query_log", "1"); + + // The writer's group reaches the database as soon as the writer exists. + rdsService.createDbInstance("writer", "aurora-mysql", "8.0.mysql_aurora.3.05.2", null, null, null, + "db.r6g.large", 0, false, "writer-params", null, "app-cluster"); + verify(containerManager).tryStart(eq(cluster.getDbClusterArn()), eq("app-cluster"), + any(), any(), any(), any(), any(), any(), any(), eq(writerLayered)); + + // A reader's group does not, and the writer's survives a reboot. + rdsService.createDbInstance("reader", "aurora-mysql", "8.0.mysql_aurora.3.05.2", null, null, null, + "db.r6g.large", 0, false, "reader-params", null, "app-cluster"); + rdsService.rebootDbCluster("app-cluster", "us-east-1"); + verify(containerManager, times(2)).tryStart(eq(cluster.getDbClusterArn()), eq("app-cluster"), + any(), any(), any(), any(), any(), any(), any(), eq(writerLayered)); + verify(containerManager, times(3)) + .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void auroraWriterWithoutOverridesDoesNotRestartTheClusterEngine() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 3306)); + rdsService.createDbParameterGroup("writer-params", "aurora-mysql8.0", "writer"); + rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, null); + + rdsService.createDbInstance("writer", "aurora-mysql", "8.0.mysql_aurora.3.05.2", null, null, null, + "db.r6g.large", 0, false, "writer-params", null, "app-cluster"); + + verify(containerManager, times(1)) + .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).stop(any()); + } + + @Test + void rebootingTheAuroraWriterRestartsTheClusterEngineWithItsGroupsAndAReaderRebootDoesNot() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 3306)); + rdsService.createDbClusterParameterGroup("app-cluster-params", "aurora-mysql8.0", "app"); + rdsService.createDbParameterGroup("writer-params", "aurora-mysql8.0", "writer"); + rdsService.modifyDbParameterGroup("writer-params", Map.of("max_connections", "800")); + DbCluster cluster = rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, "app-cluster-params"); + rdsService.createDbInstance("writer", "aurora-mysql", "8.0.mysql_aurora.3.05.2", null, null, null, + "db.r6g.large", 0, false, "writer-params", null, "app-cluster"); + rdsService.createDbInstance("reader", "aurora-mysql", "8.0.mysql_aurora.3.05.2", null, null, null, + "db.r6g.large", 0, false, null, null, "app-cluster"); + clearInvocations(containerManager); + + rdsService.rebootDbInstance("reader"); + verify(containerManager, never()) + .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + + rdsService.modifyDbClusterParameterGroup("app-cluster-params", Map.of("slow_query_log", "1")); + DbInstance rebooted = rdsService.rebootDbInstance("writer"); + + verify(containerManager).stop(any()); + verify(containerManager).tryStart(eq(cluster.getDbClusterArn()), eq("app-cluster"), + any(), any(), any(), any(), any(), any(), any(), + eq(Map.of("max_connections", "800", "slow_query_log", "1"))); + assertEquals(DbInstanceStatus.AVAILABLE, rebooted.getStatus()); + assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbInstance("reader").getStatus()); + } + + @Test + void aClusterMemberSharesItsClusterDatabaseRefusingItsParameterGroup() { + rdsService.createDbInstance("app-db", "mysql", "8.0.36", "admin", "password", "app", + "db.t3.micro", 20, false, null, null, null); + DbCluster cluster = rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, null); + rdsService.createDbInstance("writer", "aurora-mysql", "8.0.mysql_aurora.3.05.2", null, null, null, + "db.r6g.large", 0, false, null, null, "app-cluster"); + DbInstance standalone = rdsService.getDbInstance("app-db"); + DbInstance member = rdsService.getDbInstance("writer"); + assertFalse(rdsService.databaseRefusedParameterGroup(standalone)); + + when(containerManager.refusedParameterGroup(cluster.getDbClusterArn())).thenReturn(true); + + assertTrue(rdsService.databaseRefusedParameterGroup(member)); + assertFalse(rdsService.databaseRefusedParameterGroup(standalone)); + when(containerManager.refusedParameterGroup(standalone.getDbInstanceArn())).thenReturn(true); + assertTrue(rdsService.databaseRefusedParameterGroup(standalone)); + } + + @Test + void modifyDbInstanceSwitchesTheParameterGroupTheEngineRunsWithAfterAReboot() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "app-db", "localhost", 3306)); + rdsService.createDbParameterGroup("old-params", "mysql8.0", "old"); + rdsService.modifyDbParameterGroup("old-params", Map.of("max_connections", "300")); + rdsService.createDbParameterGroup("new-params", "mysql8.0", "new"); + rdsService.modifyDbParameterGroup("new-params", Map.of("max_connections", "600")); + rdsService.createDbInstance("app-db", "mysql", "8.0.36", "admin", "password", "app", + "db.t3.micro", 20, false, "old-params", null, null); + + DbInstance modified = rdsService.modifyDbInstance("app-db", null, null, null, null, null, + "us-east-1", null, DbInstanceSettings.unchanged(), null, + DbInstanceScalingChanges.unchanged(), null, "new-params"); + assertEquals("new-params", modified.getParameterGroupName()); + assertEquals("new-params", rdsService.getDbInstance("app-db").getParameterGroupName()); + + rdsService.rebootDbInstance("app-db"); + verify(containerManager).tryStart(eq("arn:aws:rds:us-east-1:123456789012:db:app-db"), eq("app-db"), + any(), any(), eq(DatabaseEngine.MYSQL), any(), any(), any(), any(), + eq(Map.of("max_connections", "600"))); + } + + @Test + void modifyDbInstanceRefusesAMissingOrMismatchedParameterGroupAndChangesNothing() { + rdsService.createDbParameterGroup("pg-params", "postgres16", "pg"); + rdsService.createDbInstance("app-db", "mysql", "8.0.36", "admin", "password", "app", + "db.t3.micro", 20, false, null, null, null); + + AwsException missing = assertThrows(AwsException.class, () -> rdsService.modifyDbInstance( + "app-db", null, null, null, null, null, "us-east-1", null, DbInstanceSettings.unchanged(), + null, DbInstanceScalingChanges.unchanged(), true, "no-such-params")); + assertEquals("DBParameterGroupNotFound", missing.getErrorCode()); + AwsException mismatched = assertThrows(AwsException.class, () -> rdsService.modifyDbInstance( + "app-db", null, null, null, null, null, "us-east-1", null, DbInstanceSettings.unchanged(), + null, DbInstanceScalingChanges.unchanged(), true, "pg-params")); + assertEquals("InvalidParameterCombination", mismatched.getErrorCode()); + + DbInstance unchanged = rdsService.getDbInstance("app-db"); + assertNull(unchanged.getParameterGroupName()); + assertFalse(unchanged.isDeletionProtection()); + } + + @Test + void modifyDbClusterSwitchesTheClusterParameterGroupTheEngineRunsWithAfterAReboot() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 3306)); + rdsService.createDbClusterParameterGroup("new-cluster-params", "aurora-mysql8.0", "new"); + rdsService.modifyDbClusterParameterGroup("new-cluster-params", Map.of("max_connections", "700")); + DbCluster cluster = rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, null); + + DbCluster modified = rdsService.modifyDbCluster("app-cluster", null, null, null, null, null, + null, null, "new-cluster-params", "us-east-1"); + assertEquals("new-cluster-params", modified.getParameterGroupName()); + assertEquals("new-cluster-params", rdsService.getDbCluster("app-cluster").getParameterGroupName()); + + rdsService.rebootDbCluster("app-cluster", "us-east-1"); + verify(containerManager).tryStart(eq(cluster.getDbClusterArn()), eq("app-cluster"), + any(), any(), any(), any(), any(), any(), any(), eq(Map.of("max_connections", "700"))); + } + + @Test + void modifyDbClusterRefusesAMissingOrMismatchedClusterParameterGroupAndChangesNothing() { + rdsService.createDbClusterParameterGroup("pg-cluster-params", "aurora-postgresql16", "pg"); + rdsService.createDbCluster("app-cluster", "aurora-mysql", + "8.0.mysql_aurora.3.05.2", "admin", "password", null, false, null); + + AwsException missing = assertThrows(AwsException.class, () -> rdsService.modifyDbCluster( + "app-cluster", "NewPassword1!", null, null, null, null, null, null, + "no-such-params", "us-east-1")); + assertEquals("DBClusterParameterGroupNotFound", missing.getErrorCode()); + AwsException mismatched = assertThrows(AwsException.class, () -> rdsService.modifyDbCluster( + "app-cluster", "NewPassword1!", null, null, null, null, null, null, + "pg-cluster-params", "us-east-1")); + assertEquals("InvalidParameterCombination", mismatched.getErrorCode()); + + DbCluster unchanged = rdsService.getDbCluster("app-cluster"); + assertNull(unchanged.getParameterGroupName()); + assertEquals("password", unchanged.getMasterPassword()); + } + + @Test + void standaloneInstanceContainerRunsWithItsDbParameterGroup() { + rdsService.createDbParameterGroup("app-params", "mysql8.0", "app"); + rdsService.modifyDbParameterGroup("app-params", Map.of("max_connections", "300")); + + rdsService.createDbInstance("app-db", "mysql", "8.0.36", "admin", "password", "app", + "db.t3.micro", 20, false, "app-params", null, null); + + verify(containerManager).tryStart(eq("arn:aws:rds:us-east-1:123456789012:db:app-db"), eq("app-db"), + any(), any(), eq(DatabaseEngine.MYSQL), any(), any(), any(), any(), + eq(Map.of("max_connections", "300"))); + } + + @Test + void containerWithoutAParameterGroupStartsWithNoOverrides() { + rdsService.createDbInstance("plain-db", "mysql", "8.0.36", "admin", "password", "app", + "db.t3.micro", 20, false, null, null, null); + + verify(containerManager).tryStart(eq("arn:aws:rds:us-east-1:123456789012:db:plain-db"), eq("plain-db"), + any(), any(), eq(DatabaseEngine.MYSQL), any(), any(), any(), any(), eq(Map.of())); } @Test @@ -1664,7 +1888,7 @@ class RdsServiceTest { verify(containerManager).tryStart( eq("arn:aws:rds:us-east-1:123456789012:cluster:cluster1"), eq("cluster1"), any(), any(), eq(DatabaseEngine.POSTGRES), - eq("postgres:16.14-alpine3.23"), eq("admin"), eq("password"), eq("dbname")); + eq("postgres:16.14-alpine3.23"), eq("admin"), eq("password"), eq("dbname"), any()); } @Test @@ -1679,7 +1903,7 @@ class RdsServiceTest { eq("arn:aws:rds:us-east-1:123456789012:cluster:cluster1"), eq("cluster1"), any(), any(), eq(DatabaseEngine.POSTGRES), eq(EmulatorConfig.RdsServiceConfig.DEFAULT_POSTGRES_IMAGE), - eq("admin"), eq("password"), eq("dbname")); + eq("admin"), eq("password"), eq("dbname"), any()); } @Test @@ -3254,7 +3478,7 @@ class RdsServiceTest { 20, false, null, "missing-subnet-group", null)); assertEquals("DBSubnetGroupNotFoundFault", exception.getErrorCode()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(proxyManager, never()).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); } @@ -3386,7 +3610,7 @@ class RdsServiceTest { assertEquals("localhost", cluster.getEndpoint().address()); assertTrue(cluster.getEndpoint().port() > 0); assertNull(cluster.getContainerId()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(proxyManager, never()).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); } @@ -3715,7 +3939,7 @@ class RdsServiceTest { // No Docker volume name may be persisted: the mock cluster has a null volume id, so the // fallback would fabricate a name that a later non-mock restore could try to reference. assertNull(instance.getDockerVolumeName()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(proxyManager, never()).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); } @@ -3726,7 +3950,7 @@ class RdsServiceTest { @Test void createDbInstanceSucceedsAsMetadataWhenNoDockerDaemonIsReachable() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbInstance instance = rdsService.createDbInstance("probe-db", "postgres", "16.3", @@ -3749,7 +3973,7 @@ class RdsServiceTest { @Test void instanceMetadataCrudWorksWhenNoDockerDaemonIsReachable() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbInstance created = rdsService.createDbInstance("probe-db", "postgres", "16.3", @@ -3777,7 +4001,7 @@ class RdsServiceTest { @Test void deleteStillRemovesTheVolumeWhenADaemonIsReachableAgain() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbInstance created = rdsService.createDbInstance("probe-db", "postgres", "16.3", "admin", "password", "dbname", "db.t3.micro", @@ -3795,7 +4019,7 @@ class RdsServiceTest { @Test void createDbClusterAndMemberSucceedAsMetadataWhenNoDockerDaemonIsReachable() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbCluster cluster = rdsService.createDbCluster("probe-cluster", "aurora-postgresql", "16.3", @@ -3821,7 +4045,7 @@ class RdsServiceTest { @Test void backendIsRetriedOncePerCallSoTheContainerStartsWhenADaemonAppears() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbInstance created = rdsService.createDbInstance("probe-db", "postgres", "16.3", "admin", "password", "dbname", "db.t3.micro", @@ -3831,7 +4055,7 @@ class RdsServiceTest { created.setStatus(DbInstanceStatus.FAILED); // A Docker daemon appears. - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("late-container", created.getDbInstanceArn(), "probe-db", "127.0.0.1", 15432)); @@ -3847,7 +4071,7 @@ class RdsServiceTest { eq(created.getDbInstanceArn()), eq("probe-db"), eq(created.getContainerStorageResourceId()), eq(created.getDockerVolumeName()), eq(DatabaseEngine.POSTGRES), eq("postgres:16.3-alpine"), - eq("admin"), eq("password"), eq("dbname")); + eq("admin"), eq("password"), eq("dbname"), any()); verify(proxyManager).startProxy( eq("rds-resource:" + created.getDbInstanceArn()), eq(created.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES), eq(false), eq(created.getProxyPort()), @@ -3858,12 +4082,12 @@ class RdsServiceTest { // calls in total: the create, the retry that found no daemon, and the retry that started it. rdsService.ensureInstanceBackend("probe-db", "us-east-1"); verify(containerManager, times(3)) - .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test void retryLeavesTheRecordWithoutABackendWhenTheProxyDoesNotStart() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbInstance created = rdsService.createDbInstance("probe-db", "postgres", "16.3", "admin", "password", "dbname", "db.t3.micro", @@ -3871,7 +4095,7 @@ class RdsServiceTest { RdsContainerHandle late = new RdsContainerHandle("late-container", created.getDbInstanceArn(), "probe-db", "127.0.0.1", 15432); created.setStatus(DbInstanceStatus.FAILED); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(late); doThrow(new IllegalStateException("port in use")).doNothing() .when(proxyManager).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), @@ -3890,12 +4114,12 @@ class RdsServiceTest { assertEquals(DbInstanceStatus.AVAILABLE, started.getStatus()); assertEquals("late-container", started.getContainerId()); verify(containerManager, times(3)) - .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + .tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test void clusterMemberBackendIsRetriedThroughItsCluster() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbCluster cluster = rdsService.createDbCluster("probe-cluster", "aurora-postgresql", "16.3", "admin", "password", "dbname", false, null); @@ -3906,7 +4130,7 @@ class RdsServiceTest { cluster.setStatus(DbInstanceStatus.FAILED); member.setStatus(DbInstanceStatus.FAILED); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("late-cluster-container", cluster.getDbClusterArn(), "probe-cluster", "127.0.0.1", 15432)); @@ -3920,7 +4144,7 @@ class RdsServiceTest { rdsService.getDbCluster("probe-cluster").getContainerId()); verify(containerManager, times(2)).tryStart( eq(cluster.getDbClusterArn()), eq("probe-cluster"), any(), any(), - eq(DatabaseEngine.POSTGRES), any(), eq("admin"), eq("password"), eq("dbname")); + eq(DatabaseEngine.POSTGRES), any(), eq("admin"), eq("password"), eq("dbname"), any()); verify(proxyManager).startProxy( eq("rds-resource:" + cluster.getDbClusterArn()), eq(cluster.getDbClusterArn()), any(), anyBoolean(), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432), @@ -3933,13 +4157,13 @@ class RdsServiceTest { @Test void rebootRetriesTheBackendForAnInstanceCreatedWithoutADaemon() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbInstance created = rdsService.createDbInstance("probe-db", "postgres", "16.3", "admin", "password", "dbname", "db.t3.micro", 20, false, null, null, null); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("late-container", created.getDbInstanceArn(), "probe-db", "127.0.0.1", 15432)); @@ -3968,7 +4192,7 @@ class RdsServiceTest { RdsContainerManager daemonlessContainerManager = mock(RdsContainerManager.class); RdsProxyManager daemonlessProxyManager = mock(RdsProxyManager.class); - when(daemonlessContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(daemonlessContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); RdsService restoredService = newService(daemonlessContainerManager, daemonlessProxyManager, @@ -3999,7 +4223,7 @@ class RdsServiceTest { RdsContainerManager daemonlessContainerManager = mock(RdsContainerManager.class); RdsProxyManager daemonlessProxyManager = mock(RdsProxyManager.class); - when(daemonlessContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(daemonlessContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); RdsService restoredService = newService(daemonlessContainerManager, daemonlessProxyManager, @@ -4024,7 +4248,7 @@ class RdsServiceTest { assertEquals(DbInstanceStatus.AVAILABLE, instance.getStatus()); assertNull(instance.getContainerId()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test @@ -4093,7 +4317,7 @@ class RdsServiceTest { assertEquals(DbInstanceStatus.AVAILABLE, started.getStatus()); assertEquals("cont-id", started.getContainerId()); assertEquals(port, started.getEndpoint().port()); - verify(containerManager, times(2)).tryStart(any(), any(), any(), eq(volume), any(), any(), any(), any(), any()); + verify(containerManager, times(2)).tryStart(any(), any(), any(), eq(volume), any(), any(), any(), any(), any(), any()); verify(proxyManager, times(2)).startProxy(any(), any(), any(), anyBoolean(), eq(port), any(), anyInt(), any(), any(), any(), any(), any(), any()); assertEquals("InvalidDBInstanceState", assertThrows(AwsException.class, @@ -4108,7 +4332,7 @@ class RdsServiceTest { rdsService.createDbCluster("pitr-cluster", "aurora-postgresql", "16.3", "admin", "password", "dbname", false, null); // The target's container fails to start, so there is nothing to copy the source into. - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); AwsException instanceFault = assertThrows(AwsException.class, () -> rdsService.restoreDbInstanceToPointInTime( @@ -4161,7 +4385,7 @@ class RdsServiceTest { assertEquals(DbInstanceStatus.STOPPED, rdsService.getDbInstance("aurora-member").getStatus()); rdsService.startDbCluster("aurora-cluster", "us-east-1"); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> new RdsContainerHandle( "cont-" + invocation.getArgument(1), invocation.getArgument(1), "localhost", 5432)); createPostgresSource("primary"); @@ -4208,7 +4432,7 @@ class RdsServiceTest { assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbCluster("aurora-cluster").getStatus()); assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbInstance("aurora-member").getStatus()); // create, start and reboot each brought the cluster container up once. - verify(containerManager, times(3)).tryStart(eq(created.getDbClusterArn()), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(3)).tryStart(eq(created.getDbClusterArn()), any(), any(), any(), any(), any(), any(), any(), any(), any()); assertEquals("DBClusterNotFoundFault", assertThrows(AwsException.class, () -> rdsService.stopDbCluster("absent", "us-east-1")).getErrorCode()); } @@ -4225,7 +4449,7 @@ class RdsServiceTest { rdsService.startDbInstance("standalone"); assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbInstance("standalone").getStatus()); verify(containerManager, never()).stop(any()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(proxyManager, never()).stopProxy(any()); } @@ -4239,7 +4463,7 @@ class RdsServiceTest { DbInstance rebooted = rdsService.rebootDbInstance("standalone"); assertEquals(DbInstanceStatus.AVAILABLE, rebooted.getStatus()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(containerManager, never()).stop(any()); verify(proxyManager, never()).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); @@ -4260,7 +4484,7 @@ class RdsServiceTest { assertEquals(DbInstanceStatus.FAILED, failed.getStatus()); assertEquals(instance.getContainerId(), failed.getContainerId()); verify(containerManager, times(1)).tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(proxyManager).stopProxy("rds-resource:" + instance.getDbInstanceArn()); } @@ -4747,7 +4971,7 @@ class RdsServiceTest { 20, false, null, "single-az-group", null, null, true)); assertEquals("DBSubnetGroupDoesNotCoverEnoughAZs", exception.getErrorCode()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test @@ -4758,7 +4982,7 @@ class RdsServiceTest { null, null, "us-east-1a", true)); assertEquals("InvalidParameterCombination", exception.getErrorCode()); - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test @@ -4870,7 +5094,7 @@ class RdsServiceTest { StorageBackend parameterGroups = new InMemoryStorage<>(); StorageBackend clusterParameterGroups = new InMemoryStorage<>(); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("initial-container", "mydb", "localhost", 5432)); RdsService initialService = newService(containerManager, proxyManager, @@ -4886,7 +5110,7 @@ class RdsServiceTest { RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class); RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class); - when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("restored-container", "mydb", "127.0.0.1", 15432)); RdsService restoredService = newService(restoredContainerManager, restoredProxyManager, @@ -4907,7 +5131,7 @@ class RdsServiceTest { eq(restored.getDbInstanceArn()), eq("mydb"), eq(restored.getContainerStorageResourceId()), eq(restored.getDockerVolumeName()), eq(DatabaseEngine.POSTGRES), - eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app")); + eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"), any()); verify(restoredProxyManager).startProxy( eq("rds-resource:" + restored.getDbInstanceArn()), eq(restored.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES), eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432), any(), @@ -4925,7 +5149,7 @@ class RdsServiceTest { StorageBackend parameterGroups = new InMemoryStorage<>(); StorageBackend clusterParameterGroups = new InMemoryStorage<>(); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("initial-cluster-container", "cluster1", "localhost", 5432)); RdsService initialService = newService(containerManager, proxyManager, @@ -4938,7 +5162,7 @@ class RdsServiceTest { RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class); RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class); - when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("restored-cluster-container", "cluster1", "127.0.0.1", 15432)); RdsService restoredService = newService(restoredContainerManager, restoredProxyManager, @@ -4960,7 +5184,7 @@ class RdsServiceTest { eq(restoredCluster.getDbClusterArn()), eq("cluster1"), eq(restoredCluster.getContainerStorageResourceId()), eq(restoredCluster.getDockerVolumeName()), eq(DatabaseEngine.POSTGRES), - eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app")); + eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"), any()); verify(restoredProxyManager).startProxy( eq("rds-resource:" + restoredCluster.getDbClusterArn()), eq(restoredCluster.getDbClusterArn()), eq(DatabaseEngine.POSTGRES), @@ -5808,7 +6032,7 @@ class RdsServiceTest { "replacement-container", "arn:aws:rds:us-east-1:123456789012:db:replacement", "replacement", "127.0.0.1", 15433); when(restoredContainerManager.tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any())) + any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(restoredHandle, replacementHandle); org.mockito.Mockito.doThrow(new IllegalStateException("relay failed")) .doNothing() @@ -5867,7 +6091,7 @@ class RdsServiceTest { instances.put("oms", persistedInstance("oms", "123456789012", "secret", 7003)); RdsContainerManager failingContainerManager = mock(RdsContainerManager.class); when(failingContainerManager.tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any())) + any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("Docker start failed")); RdsService failedBoot = newService( failingContainerManager, mock(RdsProxyManager.class), instances, @@ -5885,7 +6109,7 @@ class RdsServiceTest { RdsContainerManager healthyContainerManager = mock(RdsContainerManager.class); when(healthyContainerManager.tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any())) + any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> new RdsContainerHandle( "container-" + invocation.getArgument(1), invocation.getArgument(0), invocation.getArgument(1), "127.0.0.1", 15432)); @@ -5913,7 +6137,7 @@ class RdsServiceTest { RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class); RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class); when(restoredContainerManager.tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any())) + any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("Docker start failed")) .thenReturn(new RdsContainerHandle( "retried-container", persisted.getDbInstanceArn(), "broken", "127.0.0.1", 15432)); @@ -5959,7 +6183,7 @@ class RdsServiceTest { instances.put("broken", persisted); RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class); when(restoredContainerManager.tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any())) + any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("Docker start failed")); RdsService restoredService = newService( restoredContainerManager, mock(RdsProxyManager.class), instances, @@ -6021,7 +6245,7 @@ class RdsServiceTest { RdsProxyManager proxies = mock(RdsProxyManager.class); RdsContainerHandle recovered = new RdsContainerHandle("recovered-container", "arn:aws:rds:us-east-1:123456789012:db:broken", "broken", "127.0.0.1", 15432); - when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("temporary Docker error")) .thenReturn(recovered); RdsService service = newService(manager, proxies, instances, new InMemoryStorage<>(), @@ -6055,7 +6279,7 @@ class RdsServiceTest { RdsProxyManager proxies = mock(RdsProxyManager.class); RdsContainerHandle recovered = new RdsContainerHandle("recovered-container", cluster.getDbClusterArn(), "cluster1", "127.0.0.1", 15432); - when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(recovered); doThrow(new IllegalStateException("temporary relay error")).doNothing() .when(proxies).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), @@ -6082,14 +6306,14 @@ class RdsServiceTest { RdsProxyManager proxies = mock(RdsProxyManager.class); RdsContainerHandle recovered = new RdsContainerHandle("recovered-container", persisted.getDbInstanceArn(), "broken", "127.0.0.1", 15432); - when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("temporary Docker error")) .thenReturn(recovered); if (legacy) { persisted.setEndpoint(null); persisted.setProxyPort(0); doReturn(recovered).when(manager).tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } RdsService service = newService(manager, proxies, instances, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); @@ -6124,7 +6348,7 @@ class RdsServiceTest { RdsProxyManager proxies = mock(RdsProxyManager.class); RdsContainerHandle recovered = new RdsContainerHandle("recovered-container", persisted.getDbClusterArn(), "cluster1", "127.0.0.1", 15432); - when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("temporary Docker error")) .thenReturn(recovered); if (legacy) { @@ -6134,7 +6358,7 @@ class RdsServiceTest { member.setEndpoint(null); member.setProxyPort(0); doReturn(recovered).when(manager).tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } RdsService service = newService(manager, proxies, instances, clusters, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); @@ -6175,7 +6399,7 @@ class RdsServiceTest { @Test void directClusterRetryRestoresAllMissingMemberRelaysAndRetriesFailures() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbCluster cluster = rdsService.createDbCluster("retry-cluster", "aurora-postgresql", "16.3", "admin", "password", "dbname", false, null); @@ -6193,7 +6417,7 @@ class RdsServiceTest { .when(proxyManager).startProxy(eq("rds-resource:" + first.getDbInstanceArn()), eq(cluster.getDbClusterArn()), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("recovered-container", cluster.getDbClusterArn(), "retry-cluster", "127.0.0.1", 15432)); assertDoesNotThrow(() -> rdsService.ensureClusterBackend("retry-cluster", "us-east-1")); @@ -6215,12 +6439,12 @@ class RdsServiceTest { eq(cluster.getDbClusterArn()), any(), anyBoolean(), eq(second.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any(), any()); verify(containerManager, times(2)).tryStart(eq(cluster.getDbClusterArn()), any(), any(), - any(), any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any(), any()); } @Test void clusterMemberRelayFailureWarnsOncePerMemberUntilRecovery() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbCluster cluster = rdsService.createDbCluster("log-cluster", "aurora-postgresql", "16.3", "admin", "password", "dbname", false, null); @@ -6239,7 +6463,7 @@ class RdsServiceTest { .when(proxyManager).startProxy(eq("rds-resource:" + second.getDbInstanceArn()), eq(cluster.getDbClusterArn()), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("log-container", cluster.getDbClusterArn(), "log-cluster", "127.0.0.1", 15432)); @@ -6264,7 +6488,7 @@ class RdsServiceTest { @Test void clusterMemberRestartWithoutBackendKeepsRelayWarningUntilRecovery() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(null); DbCluster cluster = rdsService.createDbCluster("restart-log-cluster", "aurora-postgresql", "16.3", "admin", "password", "dbname", false, null); @@ -6280,7 +6504,7 @@ class RdsServiceTest { any(), any(), any(), any(), any(), any()); RdsContainerHandle handle = new RdsContainerHandle("restart-log-container", cluster.getDbClusterArn(), "restart-log-cluster", "127.0.0.1", 15432); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(handle, null, handle); List records = LogCapture.capture(RdsService.class, () -> { @@ -6338,7 +6562,7 @@ class RdsServiceTest { eq(cluster.getDbClusterArn()), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); verify(containerManager, times(2)).tryStart(eq(cluster.getDbClusterArn()), any(), any(), - any(), any(), any(), any(), any(), any()); + any(), any(), any(), any(), any(), any(), any()); } @Test @@ -6354,7 +6578,7 @@ class RdsServiceTest { "replacement-container", "arn:aws:rds:us-east-1:123456789012:cluster:replacement", "replacement", "127.0.0.1", 15433); when(restoredContainerManager.tryStart( - any(), any(), any(), any(), any(), any(), any(), any(), any())) + any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(restoredHandle, replacementHandle); org.mockito.Mockito.doThrow(new IllegalStateException("relay failed")) .doNothing() @@ -8525,7 +8749,7 @@ class RdsServiceTest { StorageBackend proxies = new InMemoryStorage<>(); StorageBackend proxyTargetGroups = new InMemoryStorage<>(); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("initial-container", "cluster1", "localhost", 5432)); RdsService initialService = new RdsService(containerManager, proxyManager, ec2Service, @@ -8539,7 +8763,7 @@ class RdsServiceTest { RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class); RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class); - when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("restored-container", "cluster1", "127.0.0.1", 15432)); RdsService restoredService = new RdsService(restoredContainerManager, restoredProxyManager, ec2Service, @@ -8603,7 +8827,7 @@ class RdsServiceTest { RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class); RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class); - when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(restoredContainerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(new RdsContainerHandle("restored-container", "cluster1", "127.0.0.1", 15432)); @@ -9494,7 +9718,7 @@ class RdsServiceTest { + "or you do not have permissions to access it.", missing.getMessage()); assertThrows(AwsException.class, () -> rdsService.getDbInstance("mydb")); // refused before any side effect: no container was started for the rejected create - verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); KmsKey disabled = knownKey("k1"); disabled.setEnabled(false); @@ -9798,7 +10022,7 @@ class RdsServiceTest { @Test void createReadReplicaInheritsTheSourceAndLinksBothEnds() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> new RdsContainerHandle( "cont-" + invocation.getArgument(1), invocation.getArgument(1), "localhost", 5432)); createPostgresSource("primary"); @@ -9960,7 +10184,7 @@ class RdsServiceTest { assertFalse(rdsService.getDbInstance("primary-replica").hasReadReplicaSource()); // AWS reboots the promoted instance before it is available again. verify(containerManager).stop(any()); - verify(containerManager, times(3)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, times(3)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); // Omitted retention means one day, as on AWS; a standalone instance cannot be promoted. rdsService.createDbInstanceReadReplica(replicaRequest("second-replica", "primary"), null); @@ -10063,7 +10287,7 @@ class RdsServiceTest { @Test void globalClusterGrowsFromEmptyToPrimaryAndSecondary() { - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> new RdsContainerHandle( "cont-" + invocation.getArgument(1), invocation.getArgument(1), "localhost", 5432)); GlobalCluster global = rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", null, @@ -10129,7 +10353,7 @@ class RdsServiceTest { void concurrentJoinsCannotProduceTwoPrimariesOrTwoSecondariesInOneRegion() { rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", null, null, null, null, Map.of(), null); when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP"); - when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any())) + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer(invocation -> { String id = invocation.getArgument(1); if ("primary-a".equals(id)) { diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java index 489d9ea6de..3ad0b5ad20 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java @@ -3,6 +3,13 @@ package io.github.hectorvent.floci.services.rds.container; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; +import com.github.dockerjava.api.command.ExecCreateCmd; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.InspectExecCmd; +import com.github.dockerjava.api.command.InspectExecResponse; import com.github.dockerjava.api.command.LogContainerCmd; import com.github.dockerjava.api.command.PauseContainerCmd; import com.github.dockerjava.api.command.UnpauseContainerCmd; @@ -35,6 +42,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -50,7 +58,9 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; @@ -101,6 +111,141 @@ class RdsContainerManagerTest { DatabaseEngine.SQLSERVER, "mcr.microsoft.com/mssql/server:2022-latest").isEmpty()); } + @Test + void parameterGroupOverridesBecomeLooseServerOptionsAheadOfTheAuthenticationOptions() { + Map overrides = new LinkedHashMap<>(); + overrides.put("slow_query_log", "1"); + overrides.put("max_connections", "500"); + overrides.put("aurora_binlog_replication_max_yield_seconds", "0"); + overrides.put("innodb_buffer_pool_size", "{DBInstanceClassMemory*3/4}"); + overrides.put("port", "3307"); + overrides.put("bind-address", "127.0.0.1"); + overrides.put("default_authentication_plugin", "caching_sha2_password"); + overrides.put("max_connections --skip-grant-tables", "1"); + + assertEquals( + List.of( + "--loose-aurora_binlog_replication_max_yield_seconds=0", + "--loose-default_authentication_plugin=caching_sha2_password", + "--loose-max_connections=500", + "--loose-slow_query_log=1", + "--default-authentication-plugin=mysql_native_password"), + RdsContainerManager.buildContainerCmd(DatabaseEngine.MYSQL, "mysql:8.0.36", overrides)); + assertEquals( + List.of( + "--loose-max_connections=500", + "--mysql-native-password=ON", + "--authentication-policy=mysql_native_password"), + RdsContainerManager.buildContainerCmd( + DatabaseEngine.MYSQL, "mysql:8.4", Map.of("max_connections", "500"))); + assertEquals(List.of("--loose-max_connections=500"), + RdsContainerManager.buildContainerCmd( + DatabaseEngine.MARIADB, "mariadb:11", Map.of("max_connections", "500"))); + } + + @Test + void parameterGroupCannotTurnOnSettingsThatLockTheProxyOut() { + Map overrides = new LinkedHashMap<>(); + overrides.put("require_secure_transport", "ON"); + overrides.put("require-secure-transport", "1"); + overrides.put("skip_grant_tables", "ON"); + overrides.put("skip-grant-tables", "1"); + overrides.put("max_connections", "500"); + + assertEquals(List.of("--loose-max_connections=500"), + RdsContainerManager.engineParameterOptions(DatabaseEngine.MYSQL, overrides)); + assertEquals(List.of("--loose-max_connections=500"), + RdsContainerManager.engineParameterOptions(DatabaseEngine.MARIADB, overrides)); + } + + @Test + void timeZoneAndAuroraBinlogOffTakeTheServerOptionsThatSetThem() { + Map overrides = new LinkedHashMap<>(); + overrides.put("time_zone", "UTC"); + overrides.put("binlog_format", "OFF"); + + assertEquals(List.of("--skip-log-bin", "--loose-default-time-zone=UTC"), + RdsContainerManager.engineParameterOptions(DatabaseEngine.MYSQL, overrides)); + assertEquals(List.of("--loose-binlog_format=ROW"), + RdsContainerManager.engineParameterOptions(DatabaseEngine.MYSQL, Map.of("binlog_format", "ROW"))); + } + + @Test + void parameterGroupOverridesAreNotPassedToOtherEngines() { + assertTrue(RdsContainerManager.buildContainerCmd( + DatabaseEngine.POSTGRES, "postgres:18", Map.of("max_connections", "500")).isEmpty()); + assertTrue(RdsContainerManager.buildContainerCmd( + DatabaseEngine.SQLSERVER, "mcr.microsoft.com/mssql/server:2022-latest", + Map.of("max_connections", "500")).isEmpty()); + } + + @Test + void mysqlContainerIsCreatedWithItsParameterGroupOverrides() { + EmulatorConfig config = config(tempDir.resolve("mysql-params-root")); + ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); + stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo( + "mysql-container", Map.of(3306, + new ContainerLifecycleManager.EndpointInfo("db1", 3306)))); + DockerClient dockerClient = databaseDockerClient("mysql-container"); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + ContainerDetector detector = mock(ContainerDetector.class); + when(detector.isRunningInContainer()).thenReturn(false); + ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class); + lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream"); + RdsContainerManager manager = new RdsContainerManager( + new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)), + lifecycleManager, logStreamer, detector, config, + new RegionResolver("us-east-1", "000000000000"), mock(ServiceConfigAccess.class)); + + manager.start("db1", "db1", "db1", "floci-rds-db1", DatabaseEngine.MYSQL, "mysql:8.0.36", + "root", "password", "db", Map.of("max_connections", "500")); + + ArgumentCaptor spec = ArgumentCaptor.forClass(ContainerSpec.class); + verify(lifecycleManager).create(spec.capture()); + assertEquals( + List.of("--loose-max_connections=500", "--default-authentication-plugin=mysql_native_password"), + spec.getValue().cmd()); + } + + @Test + void aServerThatStopsOnItsParameterGroupLeavesNoContainerAndIsReportedUntilItStarts() { + EmulatorConfig config = config(tempDir.resolve("mysql-refused-root")); + ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); + stubStarts(lifecycleManager, + new ContainerLifecycleManager.ContainerInfo("refused-container", Map.of(3306, + new ContainerLifecycleManager.EndpointInfo("db1", 3306))), + new ContainerLifecycleManager.ContainerInfo("accepted-container", Map.of(3306, + new ContainerLifecycleManager.EndpointInfo("db1", 3306)))); + DockerClient dockerClient = databaseDockerClient("accepted-container"); + stubStoppedServer(dockerClient, "refused-container", + "2026-10-23T10:00:00Z [ERROR] [MY-000077] [Server] mysqld: Error while setting value " + + "'NOT_A_MODE' to 'sql_mode'.\n2026-10-23T10:00:01Z [ERROR] [MY-010119] [Server] Aborting\n"); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + ContainerDetector detector = mock(ContainerDetector.class); + when(detector.isRunningInContainer()).thenReturn(false); + ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class); + lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream"); + RdsContainerManager manager = new RdsContainerManager( + new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)), + lifecycleManager, logStreamer, detector, config, + new RegionResolver("us-east-1", "000000000000"), mock(ServiceConfigAccess.class)); + String runtimeId = "arn:aws:rds:us-east-1:000000000000:db:db1"; + + assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", DatabaseEngine.MYSQL, + "mysql:8.0.36", "root", "password", "db", Map.of("sql_mode", "NOT_A_MODE"))); + + assertTrue(manager.refusedParameterGroup(runtimeId)); + assertNull(manager.getActiveHandle(runtimeId)); + verify(lifecycleManager).stopAndRemoveStrict(eq("refused-container"), any()); + + RdsContainerHandle accepted = manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", + DatabaseEngine.MYSQL, "mysql:8.0.36", "root", "password", "db", + Map.of("sql_mode", "STRICT_TRANS_TABLES")); + + assertEquals("accepted-container", accepted.getContainerId()); + assertFalse(manager.refusedParameterGroup(runtimeId)); + } + @Test void sqlServerUsesPersistentDataDirectory() { assertEquals("/var/opt/mssql", @@ -656,7 +801,7 @@ class RdsContainerManagerTest { for (int attempt = 0; attempt < 3; attempt++) { assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"), + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of()), "attempt " + attempt + " should report unavailable"); } assertFalse(manager.isDockerReachable()); @@ -677,7 +822,7 @@ class RdsContainerManagerTest { IllegalStateException failure = assertThrows(IllegalStateException.class, () -> manager.tryStart("arn:aws:rds:us-east-1:000000000000:db:db1", "db1", "db1", - "floci-rds-db1", DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db")); + "floci-rds-db1", DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of())); assertEquals("no such image: mysql:8.0", failure.getMessage()); assertTrue(manager.isDockerReachable()); @@ -696,7 +841,7 @@ class RdsContainerManagerTest { String runtimeId = "arn:aws:rds:us-east-1:000000000000:db:db1"; assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db")); + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of())); // A Docker daemon appears. org.mockito.Mockito.reset(lifecycleManager); @@ -706,7 +851,7 @@ class RdsContainerManagerTest { when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); RdsContainerHandle handle = manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"); + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of()); assertEquals("late-container", handle.getContainerId()); assertEquals(3306, handle.getPort()); @@ -729,12 +874,12 @@ class RdsContainerManagerTest { String runtimeId = "arn:aws:rds:us-east-1:000000000000:db:db1"; assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db")); + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of())); assertEquals("created-container", manager.getActiveHandle(runtimeId).getContainerId()); // Still no daemon: the retry keeps the identity rather than dropping it. assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db")); + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of())); assertEquals("created-container", manager.getActiveHandle(runtimeId).getContainerId()); // The daemon is back: the leftover is removed first, then the start goes through. @@ -745,7 +890,7 @@ class RdsContainerManagerTest { when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); RdsContainerHandle handle = manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"); + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of()); assertEquals("late-container", handle.getContainerId()); verify(lifecycleManager).stopAndRemoveStrict( @@ -778,7 +923,7 @@ class RdsContainerManagerTest { assertEquals(first, manager.getActiveHandle(runtimeId)); RdsContainerHandle retried = manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1", - DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"); + DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of()); assertEquals("second-container", retried.getContainerId()); assertEquals(retried, manager.getActiveHandle(runtimeId)); @@ -1458,6 +1603,56 @@ class RdsContainerManagerTest { return config; } + /** + * A Docker client on which {@code runningContainerId} runs and every exec succeeds, so a + * server started with a parameter group is seen listening at once. + */ + private static DockerClient databaseDockerClient(String runningContainerId) { + DockerClient dockerClient = mock(DockerClient.class); + stubContainerState(dockerClient, runningContainerId, true); + ExecCreateCmd createCmd = mock(ExecCreateCmd.class, RETURNS_SELF); + ExecCreateCmdResponse created = mock(ExecCreateCmdResponse.class); + when(created.getId()).thenReturn("probe"); + when(createCmd.exec()).thenReturn(created); + when(dockerClient.execCreateCmd(anyString())).thenReturn(createCmd); + ExecStartCmd startCmd = mock(ExecStartCmd.class); + when(startCmd.exec(any())).thenAnswer(invocation -> { + ResultCallback.Adapter callback = invocation.getArgument(0); + callback.onComplete(); + return callback; + }); + when(dockerClient.execStartCmd(anyString())).thenReturn(startCmd); + InspectExecCmd inspectExec = mock(InspectExecCmd.class); + InspectExecResponse inspected = mock(InspectExecResponse.class); + when(inspected.getExitCodeLong()).thenReturn(0L); + when(inspectExec.exec()).thenReturn(inspected); + when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec); + return dockerClient; + } + + /** {@code containerId} has stopped after writing {@code log}. */ + private static void stubStoppedServer(DockerClient dockerClient, String containerId, String log) { + stubContainerState(dockerClient, containerId, false); + LogContainerCmd logCmd = mock(LogContainerCmd.class, RETURNS_SELF); + when(dockerClient.logContainerCmd(containerId)).thenReturn(logCmd); + when(logCmd.exec(any())).thenAnswer(invocation -> { + ResultCallback.Adapter callback = invocation.getArgument(0); + callback.onNext(new Frame(StreamType.STDERR, log.getBytes(StandardCharsets.UTF_8))); + callback.onComplete(); + return callback; + }); + } + + private static void stubContainerState(DockerClient dockerClient, String containerId, boolean running) { + InspectContainerResponse.ContainerState state = mock(InspectContainerResponse.ContainerState.class); + when(state.getRunning()).thenReturn(running); + InspectContainerResponse response = mock(InspectContainerResponse.class); + when(response.getState()).thenReturn(state); + InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class); + when(inspectCmd.exec()).thenReturn(response); + when(dockerClient.inspectContainerCmd(containerId)).thenReturn(inspectCmd); + } + private static void stubStarts( ContainerLifecycleManager lifecycleManager, ContainerLifecycleManager.ContainerInfo... infos) {