fix(docdb): store and return cluster and instance settings (#2651)

* fix(docdb): store and return cluster and instance settings

CreateDBCluster and ModifyDBCluster dropped DBSubnetGroupName,
DBClusterParameterGroupName, VpcSecurityGroupIds, StorageEncrypted,
KmsKeyId, BackupRetentionPeriod, both windows, DeletionProtection and
tags; instances dropped AutoMinorVersionUpgrade, PreferredMaintenanceWindow,
CopyTagsToSnapshot and PromotionTier. Describe now returns what was given,
or the defaults a live account assigns, and refuses what a live account
refuses before any container is started: an unknown subnet group,
parameter group, security group or KMS key, a KMS key on an unencrypted
cluster, a retention period outside 1..354, malformed or overlapping
windows.

Records persisted before these fields existed are filled in with the
defaults on read. Port is not taken from the request: the port a cluster
reports is the one it is reachable on.

Closes #2614

* fix(docdb): enforce deletion protection, parameter group family and undrivable windows

DeleteDBCluster refuses a cluster with DeletionProtection, before any state
changes. A named parameter group must belong to the family of the engine
version the cluster will run, judged on modify against the requested
version rather than the stored one; a cluster on a default group follows
an engine version change to the new family's default. A window given
without its counterpart that leaves no daily half hour for the derived one
is refused with the live wording instead of a derived window that overlaps.

* fix(docdb): refuse an engine version change that keeps a custom group of the old family

* fix(docdb): judge a retained parameter group by its stored family, not its name

* fix(docdb): classify a retained parameter group through the RDS catalogue, not its name

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
Michal SchreiberandPriamo Germosen authored and GitHub committed 2026-08-28 14:22:23 -04:00
1 parent 231c0972b0
commit f019573bf1
14 files changed
+1224 -28

No files matched your search

@@ -0,0 +1,138 @@
package io.github.hectorvent.floci.core.common;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The daily backup window and weekly maintenance window the RDS family of services carries, with
* the checks a live account applies to them and its wording: times in {@code hh24:mi}, days in
* {@code ddd:hh24:mi}, at least 30 minutes each, and the two may not overlap.
*/
public final class BackupWindows {
private static final Pattern TIME = Pattern.compile("^([01]\\d|2[0-3]):([0-5]\\d)$");
private static final List<String> DAYS = List.of("mon", "tue", "wed", "thu", "fri", "sat", "sun");
private static final int MINUTES_PER_DAY = 24 * 60;
private static final int MINUTES_PER_WEEK = 7 * MINUTES_PER_DAY;
private static final int MINIMUM_WINDOW_MINUTES = 30;
/** Where AWS picks a random 30-minute window, Floci picks these. */
public static final String DEFAULT_BACKUP_WINDOW = "04:00-06:00";
public static final String DEFAULT_MAINTENANCE_WINDOW = "mon:00:00-mon:03:00";
private BackupWindows() {
}
/** Validates a daily window and returns its start and end as minutes of the day. */
public static int[] parseBackupWindow(String window) {
String[] parts = window.split("-", -1);
if (parts.length != 2) {
throw invalidBackupTime(window);
}
int start = minuteOfDay(parts[0], () -> invalidBackupTime(parts[0]));
int end = minuteOfDay(parts[1], () -> invalidBackupTime(parts[1]));
if (end <= start) {
end += MINUTES_PER_DAY;
}
if (end - start < MINIMUM_WINDOW_MINUTES) {
throw new AwsException("InvalidParameterValue",
"Backup window must be at least " + MINIMUM_WINDOW_MINUTES + " minutes.", 400);
}
return new int[] {start, end};
}
/** Validates a weekly window and returns its start and end as minutes of the week. */
public static int[] parseMaintenanceWindow(String window) {
String[] parts = window.split("-", -1);
if (parts.length != 2) {
throw invalidMaintenanceTime(window);
}
int start = minuteOfWeek(parts[0]);
int end = minuteOfWeek(parts[1]);
if (end <= start) {
end += MINUTES_PER_WEEK;
}
if (end - start < MINIMUM_WINDOW_MINUTES) {
throw new AwsException("InvalidParameterValue",
"Maintenance window must be at least " + MINIMUM_WINDOW_MINUTES + " minutes.", 400);
}
if (end - start >= MINUTES_PER_DAY) {
throw new AwsException("InvalidParameterValue",
"Maintenance window must be less than 24 hours.", 400);
}
return new int[] {start, end};
}
public static boolean overlap(String backupWindow, String maintenanceWindow) {
int[] backup = parseBackupWindow(backupWindow);
int[] maintenance = parseMaintenanceWindow(maintenanceWindow);
// the backup window recurs daily: lay it over each day and compare with the maintenance
// window in this week and the neighbouring ones, since either may wrap the week boundary
for (int day = 0; day < 7; day++) {
int start = day * MINUTES_PER_DAY + backup[0];
int end = day * MINUTES_PER_DAY + backup[1];
for (int shift : new int[] {-MINUTES_PER_WEEK, 0, MINUTES_PER_WEEK}) {
if (start < maintenance[1] - shift && maintenance[0] - shift < end) {
return true;
}
}
}
return false;
}
public static AwsException overlapping() {
return new AwsException("InvalidParameterValue",
"The backup window and maintenance window must not overlap.", 400);
}
/** A 30-minute maintenance window starting the minute the given daily window ends. */
public static String maintenanceWindowAfter(String backupWindow) {
int end = parseBackupWindow(backupWindow)[1] % MINUTES_PER_DAY;
return DAYS.get(0) + ":" + time(end) + "-" + DAYS.get((end + MINIMUM_WINDOW_MINUTES) / MINUTES_PER_DAY)
+ ":" + time(end + MINIMUM_WINDOW_MINUTES);
}
/** A 30-minute daily backup window starting the minute the given weekly window ends. */
public static String backupWindowAfter(String maintenanceWindow) {
int end = parseMaintenanceWindow(maintenanceWindow)[1] % MINUTES_PER_DAY;
return time(end) + "-" + time(end + MINIMUM_WINDOW_MINUTES);
}
public static String lowerCase(String window) {
return window == null ? null : window.toLowerCase();
}
private static int minuteOfWeek(String dayAndTime) {
int colon = dayAndTime.indexOf(':');
int day = colon < 0 ? -1 : DAYS.indexOf(dayAndTime.substring(0, colon).toLowerCase());
if (day < 0) {
throw invalidMaintenanceTime(dayAndTime);
}
return day * MINUTES_PER_DAY
+ minuteOfDay(dayAndTime.substring(colon + 1), () -> invalidMaintenanceTime(dayAndTime));
}
private static int minuteOfDay(String time, java.util.function.Supplier<AwsException> invalid) {
Matcher m = TIME.matcher(time);
if (!m.matches()) {
throw invalid.get();
}
return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));
}
private static String time(int minuteOfDay) {
int m = minuteOfDay % MINUTES_PER_DAY;
return String.format("%02d:%02d", m / 60, m % 60);
}
private static AwsException invalidBackupTime(String time) {
return new AwsException("InvalidParameterValue", "Invalid backup window time '" + time
+ "' specified. Should be specified as a time hh24:mi (24H Clock UTC). Example: 03:15", 400);
}
private static AwsException invalidMaintenanceTime(String time) {
return new AwsException("InvalidParameterValue", "Invalid maintenance window time '" + time
+ "' specified. Should be specified as a time ddd:hh24:mi (24H Clock UTC). Example: Mon:00:15", 400);
}
}
@@ -5,7 +5,10 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.BackupWindows;
import io.github.hectorvent.floci.services.docdb.model.DocDbCluster;
import io.github.hectorvent.floci.services.docdb.model.DocDbClusterSettings;
import io.github.hectorvent.floci.services.docdb.model.DocDbInstanceSettings;
import io.github.hectorvent.floci.services.docdb.model.DocDbInstance;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -76,13 +79,9 @@ public class DocDbQueryHandler {
String masterPassword = params.getFirst("MasterUserPassword");
boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication"));
// Tags given at create are readable back on a live account; they go in with the record.
DocDbCluster cluster = service.createDbCluster(id, engineVersion,
masterUsername, masterPassword, iamEnabled);
// Tags given at create are readable back on a live account, so they must not be dropped.
Map<String, String> tags = parseTags(params);
if (!tags.isEmpty()) {
service.addTagsToResource(cluster.getDbClusterArn(), tags);
}
masterUsername, masterPassword, iamEnabled, clusterSettings(params, true), parseTags(params));
return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS,
clusterXml(cluster))).build();
}
@@ -190,7 +189,7 @@ public class DocDbQueryHandler {
String iamStr = params.getFirst("EnableIAMDatabaseAuthentication");
Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null;
DocDbCluster cluster = service.modifyDbCluster(id, engineVersion, iamEnabled);
DocDbCluster cluster = service.modifyDbCluster(id, engineVersion, iamEnabled, clusterSettings(params, false));
return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS,
clusterXml(cluster))).build();
}
@@ -213,7 +212,7 @@ public class DocDbQueryHandler {
boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication"));
DocDbInstance instance = service.createDbInstance(id, dbClusterIdentifier,
dbInstanceClass, engineVersion, iamEnabled);
dbInstanceClass, engineVersion, iamEnabled, instanceSettings(params), parseTags(params));
return Response.ok(AwsQueryResponse.envelope("CreateDBInstance", AwsNamespaces.RDS,
instanceXml(instance))).build();
}
@@ -264,11 +263,68 @@ public class DocDbQueryHandler {
String iamStr = params.getFirst("EnableIAMDatabaseAuthentication");
Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null;
DocDbInstance instance = service.modifyDbInstance(id, dbInstanceClass, iamEnabled);
DocDbInstance instance = service.modifyDbInstance(id, dbInstanceClass, iamEnabled, instanceSettings(params));
return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS,
instanceXml(instance))).build();
}
/**
* The cluster settings a request carries. DBSubnetGroupName, StorageEncrypted and KmsKeyId are
* fixed at create and not in the ModifyDBCluster shape, so a modify reads the rest only. Port
* is not taken from the request: the port a cluster reports is the one it is reachable on.
*/
private static DocDbClusterSettings clusterSettings(MultivaluedMap<String, String> params, boolean create) {
List<String> securityGroups = memberList(params, "VpcSecurityGroupIds.VpcSecurityGroupId.");
return new DocDbClusterSettings(
create ? params.getFirst("DBSubnetGroupName") : null,
params.getFirst("DBClusterParameterGroupName"),
securityGroups.isEmpty() ? null : securityGroups,
create ? optionalBoolean(params.getFirst("StorageEncrypted")) : null,
create ? params.getFirst("KmsKeyId") : null,
optionalInt(params.getFirst("BackupRetentionPeriod")),
params.getFirst("PreferredBackupWindow"),
params.getFirst("PreferredMaintenanceWindow"),
optionalBoolean(params.getFirst("DeletionProtection")));
}
private static DocDbInstanceSettings instanceSettings(MultivaluedMap<String, String> params) {
return new DocDbInstanceSettings(
optionalBoolean(params.getFirst("AutoMinorVersionUpgrade")),
params.getFirst("PreferredMaintenanceWindow"),
optionalBoolean(params.getFirst("CopyTagsToSnapshot")),
optionalInt(params.getFirst("PromotionTier")));
}
private static List<String> memberList(MultivaluedMap<String, String> params, String prefix) {
List<String> values = new java.util.ArrayList<>();
for (int i = 1; ; i++) {
String value = params.getFirst(prefix + i);
if (value == null) {
break;
}
if (!value.isBlank()) {
values.add(value);
}
}
return values;
}
/** A live account reads any Query boolean that is not "false" as true. */
private static Boolean optionalBoolean(String value) {
return value == null ? null : !"false".equalsIgnoreCase(value.trim());
}
private static Integer optionalInt(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", "Value " + value + " is not a valid integer.", 400);
}
}
// ── XML builders ──────────────────────────────────────────────────────────
private String clusterXml(DocDbCluster c) {
@@ -287,11 +343,32 @@ public class DocDbQueryHandler {
.elem("MasterUsername", c.getMasterUsername())
.elem("IAMDatabaseAuthenticationEnabled", c.isIamDatabaseAuthenticationEnabled())
.elem("MultiAZ", false)
.elem("StorageEncrypted", true)
.elem("StorageEncrypted", c.isStorageEncrypted())
.elem("AvailabilityZone", config.defaultAvailabilityZone())
.elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default")
.elem("DBClusterParameterGroup", c.getDbClusterParameterGroupName() != null
? c.getDbClusterParameterGroupName()
: "default." + DocDbService.parameterGroupFamily(c.getEngineVersion()))
.elem("BackupRetentionPeriod", c.getBackupRetentionPeriod())
.elem("PreferredBackupWindow", c.getPreferredBackupWindow() != null
? c.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW)
.elem("PreferredMaintenanceWindow", c.getPreferredMaintenanceWindow() != null
? c.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW)
.elem("DeletionProtection", c.isDeletionProtection())
.elem("DbClusterResourceId", c.getDbClusterResourceId())
.elem("DBClusterArn", c.getDbClusterArn())
.start("DBClusterMembers");
.elem("DBClusterArn", c.getDbClusterArn());
if (c.getKmsKeyId() != null && !c.getKmsKeyId().isBlank()) {
xml.elem("KmsKeyId", c.getKmsKeyId());
}
xml.start("VpcSecurityGroups");
for (String groupId : c.getVpcSecurityGroupIds()) {
xml.start("VpcSecurityGroupMembership")
.elem("VpcSecurityGroupId", groupId)
.elem("Status", "active")
.end("VpcSecurityGroupMembership");
}
xml.end("VpcSecurityGroups")
.start("DBClusterMembers");
if (c.getDbClusterMembers() != null) {
for (String memberId : c.getDbClusterMembers()) {
xml.start("member")
@@ -322,13 +399,27 @@ public class DocDbQueryHandler {
.end("Endpoint")
.elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled())
.elem("MultiAZ", false)
.elem("StorageEncrypted", true)
.elem("StorageEncrypted", storageEncryptedOf(i))
.elem("AvailabilityZone", config.defaultAvailabilityZone())
.elem("AutoMinorVersionUpgrade", i.isAutoMinorVersionUpgrade())
.elem("PreferredMaintenanceWindow", i.getPreferredMaintenanceWindow() != null
? i.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW)
.elem("CopyTagsToSnapshot", i.isCopyTagsToSnapshot())
.elem("PromotionTier", i.getPromotionTier())
.elem("DbiResourceId", i.getDbiResourceId())
.elem("DBInstanceArn", i.getDbInstanceArn())
.build();
}
/** An instance's encryption is its cluster's; a member of a cluster that is gone reads unencrypted. */
private boolean storageEncryptedOf(DocDbInstance i) {
try {
return service.getDbCluster(i.getDbClusterIdentifier()).isStorageEncrypted();
} catch (AwsException e) {
return false;
}
}
private static String extractFilterValue(MultivaluedMap<String, String> params, String filterName) {
for (int i = 1; ; i++) {
String name = params.getFirst("Filters.Filter." + i + ".Name");
@@ -16,6 +16,14 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import io.github.hectorvent.floci.core.common.BackupWindows;
import io.github.hectorvent.floci.services.docdb.model.DocDbClusterSettings;
import io.github.hectorvent.floci.services.docdb.model.DocDbInstanceSettings;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
@@ -39,6 +47,11 @@ public class DocDbService {
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final DocDbContainerManager containerManager;
// DocumentDB subnet groups and cluster parameter groups are the RDS records reached through
// the rds scope; security groups are EC2's; a KMS key is resolved to its ARN as on AWS
private final RdsService rdsService;
private final Ec2Service ec2Service;
private final KmsService kmsService;
/**
* One monitor per stored record, taken by everything that writes it. A tag update is a
* read-modify-write, so without a lock shared with delete it can put a deleted cluster back.
@@ -151,10 +164,16 @@ public class DocDbService {
public DocDbService(EmulatorConfig config,
RegionResolver regionResolver,
DocDbContainerManager containerManager,
StorageFactory storageFactory) {
StorageFactory storageFactory,
RdsService rdsService,
Ec2Service ec2Service,
KmsService kmsService) {
this.config = config;
this.regionResolver = regionResolver;
this.containerManager = containerManager;
this.rdsService = rdsService;
this.ec2Service = ec2Service;
this.kmsService = kmsService;
this.clusters = storageFactory.create("docdb", "docdb-clusters.json",
new TypeReference<Map<String, DocDbCluster>>() {});
this.instances = storageFactory.create("docdb", "docdb-instances.json",
@@ -166,7 +185,19 @@ public class DocDbService {
public DocDbCluster createDbCluster(String id, String engineVersion,
String masterUsername, String masterPassword,
boolean iamEnabled) {
return createDbCluster(id, engineVersion, masterUsername, masterPassword, iamEnabled,
DocDbClusterSettings.defaults(), Map.of());
}
public DocDbCluster createDbCluster(String id, String engineVersion,
String masterUsername, String masterPassword,
boolean iamEnabled, DocDbClusterSettings settings,
Map<String, String> tags) {
String region = regionResolver.getRegion();
settings.validate();
String effectiveEngineVersion = engineVersion != null ? engineVersion : ENGINE_VERSION_DEFAULT;
// every reference checked and every default chosen before a container is started
DocDbClusterSettings resolved = resolveClusterSettings(settings, null, effectiveEngineVersion, region);
synchronized (lockFor("cluster:" + key(region, id))) {
if (findCluster(region, id).isPresent()) {
throw new AwsException("DBClusterAlreadyExistsFault",
@@ -184,6 +215,10 @@ public class DocDbService {
.replace("-", "").substring(0, 24).toUpperCase());
cluster.setCreatedAt(Instant.now());
cluster.setDbClusterMembers(new ArrayList<>());
resolved.applyTo(cluster);
if (tags != null && !tags.isEmpty()) {
cluster.setTags(new LinkedHashMap<>(tags));
}
if (config.services().docdb().mock()) {
LOG.infov("Creating DocDB cluster {0} in mock mode (no container)", id);
@@ -221,13 +256,214 @@ public class DocDbService {
}
}
/**
* The settings that will be in effect after the request, with every reference checked the way
* a live account checks it: the subnet group and cluster parameter group must exist (RDS
* holds both), each security group must exist, a KMS key is resolved to its ARN. On create
* ({@code current} null) an omitted value takes the AWS default — the default subnet group,
* the family's default parameter group, the VPC's default security group, one day of backups
* and windows clear of each other; on modify it keeps the cluster's.
*/
private DocDbClusterSettings resolveClusterSettings(DocDbClusterSettings settings, DocDbCluster current,
String engineVersion, String region) {
boolean create = current == null;
String subnetGroup = settings.dbSubnetGroupName();
if (subnetGroup != null && !subnetGroup.isBlank()) {
if (rdsService == null) {
throw new IllegalStateException("DocDbService was built without an RdsService");
}
try {
rdsService.getDbSubnetGroup(subnetGroup, region);
} catch (AwsException e) {
throw new AwsException("DBSubnetGroupNotFoundFault",
"DB subnet group '" + subnetGroup + "' does not exist.", 404);
}
} else if (create) {
subnetGroup = "default";
}
String parameterGroup = settings.dbClusterParameterGroupName();
if (parameterGroup != null && !parameterGroup.isBlank()) {
if (rdsService == null) {
throw new IllegalStateException("DocDbService was built without an RdsService");
}
DbClusterParameterGroup group;
try {
group = rdsService.getDbClusterParameterGroup(parameterGroup, region);
} catch (AwsException e) {
throw new AwsException("DBClusterParameterGroupNotFound",
"DBClusterParameterGroup not found: " + parameterGroup, 404);
}
requireFamily(group, engineVersion);
} else if (create) {
parameterGroup = "default." + parameterGroupFamily(engineVersion);
} else if (current.getDbClusterParameterGroupName() != null
&& !parameterGroupFamily(engineVersion).equals(parameterGroupFamily(current.getEngineVersion()))) {
// judged by what RDS holds for the group, never by its name: a custom group may be called anything
if (rdsService != null && rdsService.isManagedClusterParameterGroup(current.getDbClusterParameterGroupName())) {
// an engine version change moves a cluster on a default group to the new family's default
parameterGroup = "default." + parameterGroupFamily(engineVersion);
} else if (rdsService != null && !parameterGroupFamily(engineVersion).equals(
currentParameterGroupFamily(current.getDbClusterParameterGroupName(), region))) {
throw new AwsException("InvalidParameterCombination", "The current DB cluster parameter group "
+ current.getDbClusterParameterGroupName() + " is custom. You must explicitly specify a "
+ "new DB cluster parameter group, either default or custom, for the engine version upgrade.",
400);
}
}
List<String> securityGroups = settings.vpcSecurityGroupIds();
if (securityGroups != null && !securityGroups.isEmpty()) {
if (ec2Service == null) {
throw new IllegalStateException("DocDbService was built without an Ec2Service");
}
for (String groupId : securityGroups) {
boolean known = ec2Service.describeSecurityGroups(region, List.of(groupId), null, Map.of())
.stream().anyMatch(sg -> groupId.equals(sg.getGroupId()));
if (!known) {
throw new AwsException("InvalidParameterValue",
"Invalid security group , groupId= " + groupId + ", groupName=.", 400);
}
}
} else if (create) {
securityGroups = List.of(Ec2Service.defaultSecurityGroupId(region));
}
String kmsKeyArn = resolveKmsKeyArn(settings.kmsKeyId(), region);
String backup = settings.preferredBackupWindow();
String maintenance = settings.preferredMaintenanceWindow();
boolean backupGiven = backup != null;
boolean maintenanceGiven = maintenance != null;
if (create) {
if (!backupGiven) {
backup = maintenanceGiven && BackupWindows.overlap(BackupWindows.DEFAULT_BACKUP_WINDOW, maintenance)
? BackupWindows.backupWindowAfter(maintenance) : BackupWindows.DEFAULT_BACKUP_WINDOW;
if (maintenanceGiven && BackupWindows.overlap(backup, maintenance)) {
// the given window leaves no daily half hour free
throw new AwsException("InvalidParameterValue", "The specified maintenance window overlaps "
+ "all available default backup windows. Shrink the maintenance window or specify "
+ "a non-overlapping backup window.", 400);
}
}
if (!maintenanceGiven) {
maintenance = backupGiven && BackupWindows.overlap(backup, BackupWindows.DEFAULT_MAINTENANCE_WINDOW)
? BackupWindows.maintenanceWindowAfter(backup) : BackupWindows.DEFAULT_MAINTENANCE_WINDOW;
if (BackupWindows.overlap(backup, maintenance)) {
throw new AwsException("InvalidParameterValue", "The specified backup window overlaps "
+ "all available default maintenance windows. Shrink the backup window or specify "
+ "a non-overlapping maintenance window.", 400);
}
}
} else {
if (!backupGiven) {
backup = current.getPreferredBackupWindow() != null
? current.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW;
}
if (!maintenanceGiven) {
maintenance = current.getPreferredMaintenanceWindow() != null
? current.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW;
}
}
if (BackupWindows.overlap(backup, maintenance)) {
throw BackupWindows.overlapping();
}
return new DocDbClusterSettings(subnetGroup, parameterGroup, securityGroups,
settings.storageEncrypted(), kmsKeyArn, settings.backupRetentionPeriod(),
backup, maintenance, settings.deletionProtection());
}
/** The family of the group a cluster is on; a group deleted since is judged by nothing. */
private String currentParameterGroupFamily(String name, String region) {
try {
return rdsService.getDbClusterParameterGroup(name, region).getDbParameterGroupFamily();
} catch (AwsException e) {
return null;
}
}
private static void requireFamily(DbClusterParameterGroup group, String engineVersion) {
String family = parameterGroupFamily(engineVersion);
if (group.getDbParameterGroupFamily() != null && !family.equals(group.getDbParameterGroupFamily())) {
throw new AwsException("InvalidParameterCombination", "The Parameter Group "
+ group.getDbClusterParameterGroupName() + " with DBParameterGroupFamily "
+ group.getDbParameterGroupFamily() + " cannot be used for this instance. "
+ "Please use a Parameter Group with DBParameterGroupFamily " + family, 400);
}
}
/** The parameter group family an engine version belongs to: {@code 5.0.0} is {@code docdb5.0}. */
static String parameterGroupFamily(String engineVersion) {
String version = engineVersion == null || engineVersion.isBlank() ? ENGINE_VERSION_DEFAULT : engineVersion;
String[] parts = version.split("\\.");
return "docdb" + parts[0] + "." + (parts.length > 1 ? parts[1] : "0");
}
/**
* A live account takes the key as an ARN, a key id, an alias ARN or an alias name and reports
* the key ARN on the cluster; a key it cannot use is one fault whatever the reason.
*/
private String resolveKmsKeyArn(String kmsKeyId, String region) {
if (kmsKeyId == null || kmsKeyId.isBlank()) {
return null;
}
if (kmsService == null) {
throw new IllegalStateException("DocDbService was built without a KmsService; a KmsKeyId cannot be resolved");
}
KmsKey key;
try {
key = kmsService.describeKey(kmsKeyId, region);
} catch (AwsException e) {
throw kmsKeyNotAccessible(kmsKeyId);
}
if (!key.isEnabled() || "PendingDeletion".equals(key.getKeyState())) {
throw kmsKeyNotAccessible(kmsKeyId);
}
return key.getArn();
}
private static AwsException kmsKeyNotAccessible(String kmsKeyId) {
return new AwsException("KMSKeyNotAccessibleFault", "The specified KMS key [" + kmsKeyId
+ "] does not exist, is not enabled or you do not have permissions to access it.", 400);
}
public DocDbCluster getDbCluster(String id) {
String region = regionResolver.getRegion();
DocDbCluster cluster = findCluster(region, id).orElseThrow(() ->
new AwsException("DBClusterNotFoundFault",
"DocDB cluster " + id + " not found.", 404));
return filled(cluster, region);
}
/**
* A cluster with what a record written by an earlier version lacks: its ARN, and the settings
* a live account gives a cluster that names none — the default subnet group, the engine's
* default parameter group, the VPC's default security group and the default windows.
*/
private DocDbCluster filled(DocDbCluster cluster, String region) {
String id = cluster.getDbClusterIdentifier();
boolean changed = false;
if (cluster.getDbClusterArn() == null || cluster.getDbClusterArn().isBlank()) {
cluster.setDbClusterArn(legacyArn(region, "cluster:" + id));
changed = true;
}
if (cluster.getDbSubnetGroupName() == null) {
cluster.setDbSubnetGroupName("default");
changed = true;
}
if (cluster.getDbClusterParameterGroupName() == null) {
cluster.setDbClusterParameterGroupName("default." + parameterGroupFamily(cluster.getEngineVersion()));
changed = true;
}
if (cluster.getVpcSecurityGroupIds() == null || cluster.getVpcSecurityGroupIds().isEmpty()) {
cluster.setVpcSecurityGroupIds(List.of(Ec2Service.defaultSecurityGroupId(region)));
changed = true;
}
if (cluster.getPreferredBackupWindow() == null) {
cluster.setPreferredBackupWindow(BackupWindows.DEFAULT_BACKUP_WINDOW);
changed = true;
}
if (cluster.getPreferredMaintenanceWindow() == null) {
cluster.setPreferredMaintenanceWindow(BackupWindows.DEFAULT_MAINTENANCE_WINDOW);
changed = true;
}
if (changed) {
persistIfStillPresent(clusters, "cluster:" + key(region, id), key(region, id), cluster);
}
return cluster;
@@ -314,24 +550,36 @@ public class DocDbService {
// resolve a same-named local cluster.
if (filterId.startsWith("arn:")) {
return inRegion(clusters, region, DocDbCluster::getDbClusterIdentifier).stream()
.map(c -> filled(c, region))
.filter(c -> filterId.equalsIgnoreCase(c.getDbClusterArn()))
.toList();
}
return findCluster(region, filterId).map(List::of).orElseGet(List::of);
return findCluster(region, filterId).map(c -> List.of(filled(c, region))).orElseGet(List::of);
}
return inRegion(clusters, region, DocDbCluster::getDbClusterIdentifier);
return inRegion(clusters, region, DocDbCluster::getDbClusterIdentifier).stream()
.map(c -> filled(c, region))
.toList();
}
public DocDbCluster modifyDbCluster(String id, String engineVersion, Boolean iamEnabled) {
return modifyDbCluster(id, engineVersion, iamEnabled, DocDbClusterSettings.unchanged());
}
public DocDbCluster modifyDbCluster(String id, String engineVersion, Boolean iamEnabled,
DocDbClusterSettings settings) {
String region = regionResolver.getRegion();
settings.validate();
synchronized (lockFor("cluster:" + key(region, id))) {
DocDbCluster cluster = getDbCluster(id);
if (engineVersion != null && !engineVersion.isBlank()) {
cluster.setEngineVersion(engineVersion);
}
// every check before any change: the store hands out its own object
String effectiveEngineVersion = engineVersion != null && !engineVersion.isBlank()
? engineVersion : cluster.getEngineVersion();
DocDbClusterSettings resolved = resolveClusterSettings(settings, cluster, effectiveEngineVersion, region);
cluster.setEngineVersion(effectiveEngineVersion);
if (iamEnabled != null) {
cluster.setIamDatabaseAuthenticationEnabled(iamEnabled);
}
resolved.applyTo(cluster);
clusters.put(key(region, id), cluster);
LOG.infov("DocDB cluster {0} modified", id);
return cluster;
@@ -345,6 +593,10 @@ public class DocDbService {
new AwsException("DBClusterNotFoundFault",
"DocDB cluster " + id + " not found.", 404));
if (cluster.isDeletionProtection()) {
throw new AwsException("InvalidParameterCombination",
"Cannot delete protected Cluster, please disable deletion protection and try again.", 400);
}
if (cluster.getDbClusterMembers() != null && !cluster.getDbClusterMembers().isEmpty()) {
throw new AwsException("InvalidDBClusterStateFault",
"Cannot delete DocDB cluster " + id + " — it still has DB instances.", 400);
@@ -370,7 +622,16 @@ public class DocDbService {
public DocDbInstance createDbInstance(String id, String dbClusterIdentifier,
String dbInstanceClass, String engineVersion,
boolean iamEnabled) {
return createDbInstance(id, dbClusterIdentifier, dbInstanceClass, engineVersion, iamEnabled,
DocDbInstanceSettings.defaults(), Map.of());
}
public DocDbInstance createDbInstance(String id, String dbClusterIdentifier,
String dbInstanceClass, String engineVersion,
boolean iamEnabled, DocDbInstanceSettings settings,
Map<String, String> tags) {
String region = regionResolver.getRegion();
settings.validate();
// Instance monitor before cluster monitor, the one order every path that holds both uses.
synchronized (lockFor("instance:" + key(region, id))) {
synchronized (lockFor("cluster:" + key(region, dbClusterIdentifier))) {
@@ -394,6 +655,12 @@ public class DocDbService {
instance.setDbiResourceId("db-" + UUID.randomUUID().toString()
.replace("-", "").substring(0, 24).toUpperCase());
instance.setCreatedAt(Instant.now());
instance.setPreferredMaintenanceWindow(cluster.getPreferredMaintenanceWindow() != null
? cluster.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW);
settings.applyTo(instance);
if (tags != null && !tags.isEmpty()) {
instance.setTags(new LinkedHashMap<>(tags));
}
cluster.getDbClusterMembers().add(id);
clusters.put(key(region, dbClusterIdentifier), cluster);
@@ -410,8 +677,24 @@ public class DocDbService {
DocDbInstance instance = findInstance(region, id).orElseThrow(() ->
new AwsException("DBInstanceNotFound",
"DocDB instance " + id + " not found.", 404));
return filled(instance, region);
}
/** An instance with its ARN and, as on a live account, its cluster's maintenance window. */
private DocDbInstance filled(DocDbInstance instance, String region) {
String id = instance.getDbInstanceIdentifier();
boolean changed = false;
if (instance.getDbInstanceArn() == null || instance.getDbInstanceArn().isBlank()) {
instance.setDbInstanceArn(legacyArn(region, "db:" + id));
changed = true;
}
if (instance.getPreferredMaintenanceWindow() == null) {
instance.setPreferredMaintenanceWindow(findCluster(region, instance.getDbClusterIdentifier())
.map(c -> filled(c, region).getPreferredMaintenanceWindow())
.orElse(BackupWindows.DEFAULT_MAINTENANCE_WINDOW));
changed = true;
}
if (changed) {
persistIfStillPresent(instances, "instance:" + key(region, id), key(region, id), instance);
}
return instance;
@@ -424,16 +707,25 @@ public class DocDbService {
// listDbClusters for why the match is against the stored ARN.
if (filterId.startsWith("arn:")) {
return inRegion(instances, region, DocDbInstance::getDbInstanceIdentifier).stream()
.map(i -> filled(i, region))
.filter(i -> filterId.equalsIgnoreCase(i.getDbInstanceArn()))
.toList();
}
return findInstance(region, filterId).map(List::of).orElseGet(List::of);
return findInstance(region, filterId).map(i -> List.of(filled(i, region))).orElseGet(List::of);
}
return inRegion(instances, region, DocDbInstance::getDbInstanceIdentifier);
return inRegion(instances, region, DocDbInstance::getDbInstanceIdentifier).stream()
.map(i -> filled(i, region))
.toList();
}
public DocDbInstance modifyDbInstance(String id, String dbInstanceClass, Boolean iamEnabled) {
return modifyDbInstance(id, dbInstanceClass, iamEnabled, DocDbInstanceSettings.defaults());
}
public DocDbInstance modifyDbInstance(String id, String dbInstanceClass, Boolean iamEnabled,
DocDbInstanceSettings settings) {
String region = regionResolver.getRegion();
settings.validate();
synchronized (lockFor("instance:" + key(region, id))) {
DocDbInstance instance = getDbInstance(id);
if (dbInstanceClass != null && !dbInstanceClass.isBlank()) {
@@ -442,6 +734,7 @@ public class DocDbService {
if (iamEnabled != null) {
instance.setIamDatabaseAuthenticationEnabled(iamEnabled);
}
settings.applyTo(instance);
instances.put(key(region, id), instance);
LOG.infov("DocDB instance {0} modified", id);
return instance;
@@ -23,6 +23,16 @@ public class DocDbCluster {
private String dbClusterArn;
private String dbClusterResourceId;
private List<String> dbClusterMembers = new ArrayList<>();
private String dbSubnetGroupName;
private String dbClusterParameterGroupName;
private List<String> vpcSecurityGroupIds = new ArrayList<>();
private boolean storageEncrypted;
private String kmsKeyId;
// AWS defaults to one day of automated backups; a record persisted before the field reads the same
private int backupRetentionPeriod = 1;
private String preferredBackupWindow;
private String preferredMaintenanceWindow;
private boolean deletionProtection;
private Instant createdAt;
// Docker / proxy runtime fields — persisted so cleanup works across restarts
@@ -64,6 +74,25 @@ public class DocDbCluster {
public String getDbClusterResourceId() { return dbClusterResourceId; }
public void setDbClusterResourceId(String dbClusterResourceId) { this.dbClusterResourceId = dbClusterResourceId; }
public String getDbSubnetGroupName() { return dbSubnetGroupName; }
public void setDbSubnetGroupName(String dbSubnetGroupName) { this.dbSubnetGroupName = dbSubnetGroupName; }
public String getDbClusterParameterGroupName() { return dbClusterParameterGroupName; }
public void setDbClusterParameterGroupName(String dbClusterParameterGroupName) { this.dbClusterParameterGroupName = dbClusterParameterGroupName; }
public List<String> getVpcSecurityGroupIds() { return vpcSecurityGroupIds; }
public void setVpcSecurityGroupIds(List<String> vpcSecurityGroupIds) { this.vpcSecurityGroupIds = vpcSecurityGroupIds == null ? new ArrayList<>() : vpcSecurityGroupIds; }
public boolean isStorageEncrypted() { return storageEncrypted; }
public void setStorageEncrypted(boolean storageEncrypted) { this.storageEncrypted = storageEncrypted; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
public int getBackupRetentionPeriod() { return backupRetentionPeriod; }
public void setBackupRetentionPeriod(int backupRetentionPeriod) { this.backupRetentionPeriod = backupRetentionPeriod; }
public String getPreferredBackupWindow() { return preferredBackupWindow; }
public void setPreferredBackupWindow(String preferredBackupWindow) { this.preferredBackupWindow = preferredBackupWindow; }
public String getPreferredMaintenanceWindow() { return preferredMaintenanceWindow; }
public void setPreferredMaintenanceWindow(String preferredMaintenanceWindow) { this.preferredMaintenanceWindow = preferredMaintenanceWindow; }
public boolean isDeletionProtection() { return deletionProtection; }
public void setDeletionProtection(boolean deletionProtection) { this.deletionProtection = deletionProtection; }
public List<String> getDbClusterMembers() { return dbClusterMembers; }
public void setDbClusterMembers(List<String> dbClusterMembers) {
this.dbClusterMembers = dbClusterMembers != null ? new ArrayList<>(dbClusterMembers) : new ArrayList<>();
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.docdb.model;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.BackupWindows;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* The placement, encryption and backup settings of a DocumentDB cluster as a request carries
* them: a null member is one the request left out — the AWS default on create, unchanged on modify.
*/
@RegisterForReflection
public record DocDbClusterSettings(String dbSubnetGroupName,
String dbClusterParameterGroupName,
List<String> vpcSecurityGroupIds,
Boolean storageEncrypted,
String kmsKeyId,
Integer backupRetentionPeriod,
String preferredBackupWindow,
String preferredMaintenanceWindow,
Boolean deletionProtection) {
public static DocDbClusterSettings defaults() {
return new DocDbClusterSettings(null, null, null, null, null, null, null, null, null);
}
public static DocDbClusterSettings unchanged() {
return defaults();
}
/** The per-parameter checks a live account applies, with its wording. */
public void validate() {
if (kmsKeyId != null && !kmsKeyId.isBlank() && !Boolean.TRUE.equals(storageEncrypted)) {
throw new AwsException("InvalidParameterCombination",
"You cannot specify KMS key for unencrypted clusters.", 400);
}
if (backupRetentionPeriod != null && (backupRetentionPeriod < 1 || backupRetentionPeriod > 354)) {
throw new AwsException("InvalidParameterValue", "Invalid backup retention period: "
+ backupRetentionPeriod + ". Retention period must be between 1 and 354.", 400);
}
if (preferredBackupWindow != null) {
BackupWindows.parseBackupWindow(preferredBackupWindow);
}
if (preferredMaintenanceWindow != null) {
BackupWindows.parseMaintenanceWindow(preferredMaintenanceWindow);
}
}
public DocDbClusterSettings with(String resolvedKmsKeyId, String backupWindow, String maintenanceWindow) {
return new DocDbClusterSettings(dbSubnetGroupName, dbClusterParameterGroupName, vpcSecurityGroupIds,
storageEncrypted, resolvedKmsKeyId, backupRetentionPeriod, backupWindow, maintenanceWindow,
deletionProtection);
}
public void applyTo(DocDbCluster cluster) {
if (dbSubnetGroupName != null && !dbSubnetGroupName.isBlank()) {
cluster.setDbSubnetGroupName(dbSubnetGroupName);
}
if (dbClusterParameterGroupName != null && !dbClusterParameterGroupName.isBlank()) {
cluster.setDbClusterParameterGroupName(dbClusterParameterGroupName);
}
if (vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty()) {
cluster.setVpcSecurityGroupIds(List.copyOf(vpcSecurityGroupIds));
}
if (storageEncrypted != null) {
cluster.setStorageEncrypted(storageEncrypted);
}
if (kmsKeyId != null && !kmsKeyId.isBlank()) {
cluster.setKmsKeyId(kmsKeyId);
}
if (backupRetentionPeriod != null) {
cluster.setBackupRetentionPeriod(backupRetentionPeriod);
}
if (preferredBackupWindow != null && !preferredBackupWindow.isBlank()) {
cluster.setPreferredBackupWindow(preferredBackupWindow);
}
if (preferredMaintenanceWindow != null && !preferredMaintenanceWindow.isBlank()) {
cluster.setPreferredMaintenanceWindow(BackupWindows.lowerCase(preferredMaintenanceWindow));
}
if (deletionProtection != null) {
cluster.setDeletionProtection(deletionProtection);
}
}
}
@@ -17,6 +17,11 @@ public class DocDbInstance {
private int port;
private boolean iamDatabaseAuthenticationEnabled;
private String dbInstanceArn;
// AWS defaults minor-version upgrades to on when CreateDBInstance omits the flag
private boolean autoMinorVersionUpgrade = true;
private String preferredMaintenanceWindow;
private boolean copyTagsToSnapshot;
private int promotionTier = 1;
private String dbiResourceId;
private Instant createdAt;
@@ -48,6 +53,15 @@ public class DocDbInstance {
this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled;
}
public boolean isAutoMinorVersionUpgrade() { return autoMinorVersionUpgrade; }
public void setAutoMinorVersionUpgrade(boolean autoMinorVersionUpgrade) { this.autoMinorVersionUpgrade = autoMinorVersionUpgrade; }
public String getPreferredMaintenanceWindow() { return preferredMaintenanceWindow; }
public void setPreferredMaintenanceWindow(String preferredMaintenanceWindow) { this.preferredMaintenanceWindow = preferredMaintenanceWindow; }
public boolean isCopyTagsToSnapshot() { return copyTagsToSnapshot; }
public void setCopyTagsToSnapshot(boolean copyTagsToSnapshot) { this.copyTagsToSnapshot = copyTagsToSnapshot; }
public int getPromotionTier() { return promotionTier; }
public void setPromotionTier(int promotionTier) { this.promotionTier = promotionTier; }
public String getDbInstanceArn() { return dbInstanceArn; }
public void setDbInstanceArn(String dbInstanceArn) { this.dbInstanceArn = dbInstanceArn; }
@@ -0,0 +1,37 @@
package io.github.hectorvent.floci.services.docdb.model;
import io.github.hectorvent.floci.core.common.BackupWindows;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** The settings of a DocumentDB instance as a request carries them; null means left out. */
@RegisterForReflection
public record DocDbInstanceSettings(Boolean autoMinorVersionUpgrade,
String preferredMaintenanceWindow,
Boolean copyTagsToSnapshot,
Integer promotionTier) {
public static DocDbInstanceSettings defaults() {
return new DocDbInstanceSettings(null, null, null, null);
}
public void validate() {
if (preferredMaintenanceWindow != null) {
BackupWindows.parseMaintenanceWindow(preferredMaintenanceWindow);
}
}
public void applyTo(DocDbInstance instance) {
if (autoMinorVersionUpgrade != null) {
instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade);
}
if (preferredMaintenanceWindow != null && !preferredMaintenanceWindow.isBlank()) {
instance.setPreferredMaintenanceWindow(BackupWindows.lowerCase(preferredMaintenanceWindow));
}
if (copyTagsToSnapshot != null) {
instance.setCopyTagsToSnapshot(copyTagsToSnapshot);
}
if (promotionTier != null) {
instance.setPromotionTier(promotionTier);
}
}
}
@@ -90,7 +90,12 @@ public class RdsService implements Resettable, ResourceProvider {
managedDefault("postgres15"),
managedDefault("postgres16"),
managedDefault("postgres17"),
managedDefault("postgres18"));
managedDefault("postgres18"),
// DocumentDB clusters name these as their default (the families the DocDB engine
// versions map to); DocDbService validates a cluster's parameter group here
managedDefault("docdb3.6"),
managedDefault("docdb4.0"),
managedDefault("docdb5.0"));
/**
* Engines AWS accepts for {@code EngineName} on an option group. Floci can only run
@@ -2642,6 +2647,11 @@ public class RdsService implements Resettable, ResourceProvider {
return unique.values();
}
/** Whether a name is one of the default cluster parameter groups the service itself provides. */
public boolean isManagedClusterParameterGroup(String name) {
return managedClusterParameterGroup(name) != null;
}
private static ManagedClusterParameterGroup managedClusterParameterGroup(String name) {
for (ManagedClusterParameterGroup group : MANAGED_CLUSTER_PARAMETER_GROUPS) {
if (group.name().equals(name)) {