diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 5f25f33f3d..1c137659ce 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -365,6 +365,7 @@ public interface EmulatorConfig { AutoScalingServiceConfig autoscaling(); BackupServiceConfig backup(); NeptuneServiceConfig neptune(); + DocDbServiceConfig docdb(); Route53ServiceConfig route53(); TransferServiceConfig transfer(); TextractServiceConfig textract(); @@ -582,6 +583,19 @@ public interface EmulatorConfig { Optional dockerNetwork(); } + interface DocDbServiceConfig { + @WithDefault("true") + boolean enabled(); + + @WithDefault("false") + boolean mock(); + + @WithDefault("mongo:7.0") + String defaultImage(); + + Optional dockerNetwork(); + } + interface EventBridgeServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 4f97b5c293..152ef96aaa 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -2,6 +2,8 @@ package io.github.hectorvent.floci.core.common; import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler; import io.github.hectorvent.floci.services.neptune.NeptuneService; +import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler; +import io.github.hectorvent.floci.services.docdb.DocDbService; import io.github.hectorvent.floci.services.autoscaling.AutoScalingQueryHandler; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; import io.github.hectorvent.floci.services.ec2.Ec2QueryHandler; @@ -174,6 +176,8 @@ public class AwsQueryController { private final RdsQueryHandler rdsQueryHandler; private final NeptuneQueryHandler neptuneQueryHandler; private final NeptuneService neptuneService; + private final DocDbQueryHandler docDbQueryHandler; + private final DocDbService docDbService; private final SqsQueryHandler sqsQueryHandler; private final SnsQueryHandler snsQueryHandler; private final SesQueryHandler sesQueryHandler; @@ -193,6 +197,8 @@ public class AwsQueryController { RdsQueryHandler rdsQueryHandler, NeptuneQueryHandler neptuneQueryHandler, NeptuneService neptuneService, + DocDbQueryHandler docDbQueryHandler, + DocDbService docDbService, SqsQueryHandler sqsQueryHandler, SnsQueryHandler snsQueryHandler, SesQueryHandler sesQueryHandler, IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler, @@ -208,6 +214,8 @@ public class AwsQueryController { this.rdsQueryHandler = rdsQueryHandler; this.neptuneQueryHandler = neptuneQueryHandler; this.neptuneService = neptuneService; + this.docDbQueryHandler = docDbQueryHandler; + this.docDbService = docDbService; this.sqsQueryHandler = sqsQueryHandler; this.snsQueryHandler = snsQueryHandler; this.sesQueryHandler = sesQueryHandler; @@ -246,7 +254,7 @@ public class AwsQueryController { case "iam" -> iamQueryHandler.handle(action, formParams); case "sts" -> stsQueryHandler.handle(action, formParams); case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams); - case "rds" -> { + case "rds" -> { // Neptune signs requests with "rds" credential scope (same wire protocol). // Route to Neptune when Engine=neptune (create ops) or when the cluster/instance // already exists in Neptune storage (describe/modify/delete ops). @@ -258,9 +266,16 @@ public class AwsQueryController { || neptuneService.hasInstance(instanceId)) { yield neptuneQueryHandler.handle(action, formParams); } + + if ("docdb".equalsIgnoreCase(engine) + || docDbService.hasCluster(clusterId) + || docDbService.hasInstance(instanceId)) { + yield docDbQueryHandler.handle(action, formParams); + } yield rdsQueryHandler.handle(action, formParams); } case "neptune" -> neptuneQueryHandler.handle(action, formParams); + case "docdb" -> docDbQueryHandler.handle(action, formParams); case "email" -> sesQueryHandler.handle(action, formParams, region); case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region); case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 2e2c838c70..5ca506234d 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -101,6 +101,12 @@ public class ResolvedServiceCatalog { 5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY), Set.of(), Set.of("neptune"), Set.of(), Set.of()), + descriptor("docdb", "docdb", config.services().docdb().enabled(), true, + "docdb", config.storage().mode(), + 5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("docdb"), Set.of(), Set.of()), + descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true, "eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbQueryHandler.java new file mode 100644 index 0000000000..17b392796b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbQueryHandler.java @@ -0,0 +1,266 @@ +package io.github.hectorvent.floci.services.docdb; + +import io.github.hectorvent.floci.config.EmulatorConfig; +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.services.docdb.model.DocDbCluster; +import io.github.hectorvent.floci.services.docdb.model.DocDbInstance; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.Collection; + +@ApplicationScoped +public class DocDbQueryHandler { + + private static final Logger LOG = Logger.getLogger(DocDbQueryHandler.class); + + private final DocDbService service; + private final EmulatorConfig config; + + @Inject + public DocDbQueryHandler(DocDbService service, EmulatorConfig config) { + this.service = service; + this.config = config; + } + + public Response handle(String action, MultivaluedMap params) { + LOG.infov("DocDB action: {0}", action); + try { + return switch (action) { + case "CreateDBCluster" -> handleCreateDbCluster(params); + case "DescribeDBClusters" -> handleDescribeDbClusters(params); + case "DeleteDBCluster" -> handleDeleteDbCluster(params); + case "ModifyDBCluster" -> handleModifyDbCluster(params); + case "CreateDBInstance" -> handleCreateDbInstance(params); + case "DescribeDBInstances"-> handleDescribeDbInstances(params); + case "DeleteDBInstance" -> handleDeleteDbInstance(params); + case "ModifyDBInstance" -> handleModifyDbInstance(params); + default -> AwsQueryResponse.error("UnsupportedOperation", + "Operation " + action + " is not supported by DocDB.", AwsNamespaces.RDS, 400); + }; + } catch (AwsException e) { + return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus()); + } catch (Exception e) { + LOG.errorv(e, "Unexpected error in DocDB {0}", action); + return AwsQueryResponse.error("InternalFailure", + "An internal error occurred while processing the request.", + AwsNamespaces.RDS, 500); + } + } + + // ── Clusters ────────────────────────────────────────────────────────────── + + private Response handleCreateDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + String engineVersion = params.getFirst("EngineVersion"); + String masterUsername = params.getFirst("MasterUsername"); + String masterPassword = params.getFirst("MasterUserPassword"); + boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication")); + + DocDbCluster cluster = service.createDbCluster(id, engineVersion, + masterUsername, masterPassword, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, + clusterXml(cluster))).build(); + } + + private Response handleDescribeDbClusters(MultivaluedMap params) { + String filterId = params.getFirst("DBClusterIdentifier"); + if (filterId == null || filterId.isBlank()) { + filterId = extractFilterValue(params, "db-cluster-id"); + } + + // When a specific cluster ID is requested, AWS returns 404 if not found + if (filterId != null && !filterId.isBlank()) { + service.getDbCluster(filterId); // throws DBClusterNotFoundFault if absent + } + + Collection result = service.listDbClusters(filterId); + + XmlBuilder xml = new XmlBuilder().start("DBClusters"); + for (DocDbCluster c : result) { + xml.start("DBCluster").raw(clusterInnerXml(c)).end("DBCluster"); + } + xml.end("DBClusters").start("Marker").end("Marker"); + return Response.ok(AwsQueryResponse.envelope("DescribeDBClusters", AwsNamespaces.RDS, xml.build())).build(); + } + + private Response handleDeleteDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + DocDbCluster cluster = service.getDbCluster(id); + service.deleteDbCluster(id); + return Response.ok(AwsQueryResponse.envelope("DeleteDBCluster", AwsNamespaces.RDS, + clusterXml(cluster))).build(); + } + + private Response handleModifyDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + String engineVersion = params.getFirst("EngineVersion"); + String iamStr = params.getFirst("EnableIAMDatabaseAuthentication"); + Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null; + + DocDbCluster cluster = service.modifyDbCluster(id, engineVersion, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, + clusterXml(cluster))).build(); + } + + // ── Instances ───────────────────────────────────────────────────────────── + + private Response handleCreateDbInstance(MultivaluedMap params) { + String id = params.getFirst("DBInstanceIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); + } + String dbClusterIdentifier = params.getFirst("DBClusterIdentifier"); + if (dbClusterIdentifier == null || dbClusterIdentifier.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required for DocDB instances.", AwsNamespaces.RDS, 400); + } + String dbInstanceClass = params.getFirst("DBInstanceClass"); + String engineVersion = params.getFirst("EngineVersion"); + boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication")); + + DocDbInstance instance = service.createDbInstance(id, dbClusterIdentifier, + dbInstanceClass, engineVersion, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("CreateDBInstance", AwsNamespaces.RDS, + instanceXml(instance))).build(); + } + + private Response handleDescribeDbInstances(MultivaluedMap params) { + String filterId = params.getFirst("DBInstanceIdentifier"); + if (filterId == null || filterId.isBlank()) { + filterId = extractFilterValue(params, "db-instance-id"); + } + + if (filterId != null && !filterId.isBlank()) { + service.getDbInstance(filterId); // throws DBInstanceNotFound if absent + } + + Collection result = service.listDbInstances(filterId); + + XmlBuilder xml = new XmlBuilder().start("DBInstances"); + for (DocDbInstance i : result) { + xml.start("DBInstance").raw(instanceInnerXml(i)).end("DBInstance"); + } + xml.end("DBInstances").start("Marker").end("Marker"); + return Response.ok(AwsQueryResponse.envelope("DescribeDBInstances", AwsNamespaces.RDS, xml.build())).build(); + } + + private Response handleDeleteDbInstance(MultivaluedMap params) { + String id = params.getFirst("DBInstanceIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); + } + DocDbInstance instance = service.getDbInstance(id); + service.deleteDbInstance(id); + return Response.ok(AwsQueryResponse.envelope("DeleteDBInstance", AwsNamespaces.RDS, + instanceXml(instance))).build(); + } + + private Response handleModifyDbInstance(MultivaluedMap params) { + String id = params.getFirst("DBInstanceIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); + } + String dbInstanceClass = params.getFirst("DBInstanceClass"); + String iamStr = params.getFirst("EnableIAMDatabaseAuthentication"); + Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null; + + DocDbInstance instance = service.modifyDbInstance(id, dbInstanceClass, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, + instanceXml(instance))).build(); + } + + // ── XML builders ────────────────────────────────────────────────────────── + + private String clusterXml(DocDbCluster c) { + return new XmlBuilder().start("DBCluster").raw(clusterInnerXml(c)).end("DBCluster").build(); + } + + private String clusterInnerXml(DocDbCluster c) { + XmlBuilder xml = new XmlBuilder() + .elem("DBClusterIdentifier", c.getDbClusterIdentifier()) + .elem("Status", c.getStatus()) + .elem("Engine", "docdb") + .elem("EngineVersion", c.getEngineVersion()) + .elem("Endpoint", c.getEndpoint()) + .elem("ReaderEndpoint", c.getReaderEndpoint()) + .elem("Port", c.getPort()) + .elem("MasterUsername", c.getMasterUsername()) + .elem("IAMDatabaseAuthenticationEnabled", c.isIamDatabaseAuthenticationEnabled()) + .elem("MultiAZ", false) + .elem("StorageEncrypted", true) + .elem("AvailabilityZone", config.defaultAvailabilityZone()) + .elem("DbClusterResourceId", c.getDbClusterResourceId()) + .elem("DBClusterArn", c.getDbClusterArn()) + .start("DBClusterMembers"); + if (c.getDbClusterMembers() != null) { + for (String memberId : c.getDbClusterMembers()) { + xml.start("member") + .elem("DBInstanceIdentifier", memberId) + .elem("IsClusterWriter", true) + .end("member"); + } + } + xml.end("DBClusterMembers"); + return xml.build(); + } + + private String instanceXml(DocDbInstance i) { + return new XmlBuilder().start("DBInstance").raw(instanceInnerXml(i)).end("DBInstance").build(); + } + + private String instanceInnerXml(DocDbInstance i) { + return new XmlBuilder() + .elem("DBInstanceIdentifier", i.getDbInstanceIdentifier()) + .elem("DBClusterIdentifier", i.getDbClusterIdentifier()) + .elem("DBInstanceClass", i.getDbInstanceClass()) + .elem("DBInstanceStatus", i.getStatus()) + .elem("Engine", "docdb") + .elem("EngineVersion", i.getEngineVersion()) + .start("Endpoint") + .elem("Address", i.getEndpoint()) + .elem("Port", i.getPort()) + .end("Endpoint") + .elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled()) + .elem("MultiAZ", false) + .elem("StorageEncrypted", true) + .elem("AvailabilityZone", config.defaultAvailabilityZone()) + .elem("DbiResourceId", i.getDbiResourceId()) + .elem("DBInstanceArn", i.getDbInstanceArn()) + .build(); + } + + private static String extractFilterValue(MultivaluedMap params, String filterName) { + for (int i = 1; ; i++) { + String name = params.getFirst("Filters.Filter." + i + ".Name"); + if (name == null) { + break; + } + if (filterName.equals(name)) { + return params.getFirst("Filters.Filter." + i + ".Values.Value.1"); + } + } + return null; + } +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.java b/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.java new file mode 100644 index 0000000000..82ede0b73b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.java @@ -0,0 +1,242 @@ +package io.github.hectorvent.floci.services.docdb; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.docdb.container.DocDbContainerHandle; +import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager; +import io.github.hectorvent.floci.services.docdb.model.DocDbCluster; +import io.github.hectorvent.floci.services.docdb.model.DocDbInstance; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + +@ApplicationScoped +public class DocDbService { + + private static final Logger LOG = Logger.getLogger(DocDbService.class); + private static final String ENGINE_VERSION_DEFAULT = "5.0.0"; + private static final int MONGO_PORT = 27017; + + private final StorageBackend clusters; + private final StorageBackend instances; + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final DocDbContainerManager containerManager; + + @Inject + public DocDbService(EmulatorConfig config, + RegionResolver regionResolver, + DocDbContainerManager containerManager, + StorageFactory storageFactory) { + this.config = config; + this.regionResolver = regionResolver; + this.containerManager = containerManager; + this.clusters = storageFactory.create("docdb", "docdb-clusters.json", + new TypeReference>() {}); + this.instances = storageFactory.create("docdb", "docdb-instances.json", + new TypeReference>() {}); + } + + // ── Clusters ────────────────────────────────────────────────────────────── + + public DocDbCluster createDbCluster(String id, String engineVersion, + String masterUsername, String masterPassword, + boolean iamEnabled) { + if (clusters.get(id).isPresent()) { + throw new AwsException("DBClusterAlreadyExistsFault", + "DocDB cluster " + id + " already exists.", 400); + } + + String region = regionResolver.getDefaultRegion(); + + DocDbCluster cluster = new DocDbCluster(); + cluster.setDbClusterIdentifier(id); + cluster.setStatus("available"); + cluster.setEngineVersion(engineVersion != null ? engineVersion : ENGINE_VERSION_DEFAULT); + cluster.setMasterUsername(masterUsername); + cluster.setIamDatabaseAuthenticationEnabled(iamEnabled); + cluster.setDbClusterArn(regionResolver.buildArn("rds", region, "cluster:" + id)); + cluster.setDbClusterResourceId("cluster-" + UUID.randomUUID().toString() + .replace("-", "").substring(0, 24).toUpperCase()); + cluster.setCreatedAt(Instant.now()); + cluster.setDbClusterMembers(new ArrayList<>()); + + if (config.services().docdb().mock()) { + LOG.infov("Creating DocDB cluster {0} in mock mode (no container)", id); + cluster.setEndpoint("localhost"); + cluster.setReaderEndpoint("localhost"); + cluster.setPort(MONGO_PORT); + } else { + String image = config.services().docdb().defaultImage(); + LOG.infov("Creating DocDB cluster {0}, image={1}", id, image); + DocDbContainerHandle handle = containerManager.start(id, image, masterUsername, masterPassword); + cluster.setEndpoint(handle.getHost()); + cluster.setReaderEndpoint(handle.getHost()); + cluster.setPort(handle.getPort()); + cluster.setContainerId(handle.getContainerId()); + cluster.setContainerHost(handle.getHost()); + cluster.setContainerPort(handle.getPort()); + } + + clusters.put(id, cluster); + LOG.infov("DocDB cluster {0} created, endpoint={1}:{2}", + id, cluster.getEndpoint(), String.valueOf(cluster.getPort())); + return cluster; + } + + public DocDbCluster getDbCluster(String id) { + return clusters.get(id).orElseThrow(() -> + new AwsException("DBClusterNotFoundFault", + "DocDB cluster " + id + " not found.", 404)); + } + + public boolean hasCluster(String id) { + if (id == null || id.isBlank()) { + return false; + } + return clusters.get(id).isPresent(); + } + + public boolean hasInstance(String id) { + if (id == null || id.isBlank()) { + return false; + } + return instances.get(id).isPresent(); + } + + public Collection listDbClusters(String filterId) { + if (filterId != null && !filterId.isBlank()) { + return clusters.scan(k -> k.equalsIgnoreCase(filterId)); + } + return clusters.scan(k -> true); + } + + public DocDbCluster modifyDbCluster(String id, String engineVersion, Boolean iamEnabled) { + DocDbCluster cluster = getDbCluster(id); + if (engineVersion != null && !engineVersion.isBlank()) { + cluster.setEngineVersion(engineVersion); + } + if (iamEnabled != null) { + cluster.setIamDatabaseAuthenticationEnabled(iamEnabled); + } + clusters.put(id, cluster); + LOG.infov("DocDB cluster {0} modified", id); + return cluster; + } + + public void deleteDbCluster(String id) { + DocDbCluster cluster = clusters.get(id).orElseThrow(() -> + new AwsException("DBClusterNotFoundFault", + "DocDB cluster " + id + " not found.", 404)); + + if (cluster.getDbClusterMembers() != null && !cluster.getDbClusterMembers().isEmpty()) { + throw new AwsException("InvalidDBClusterStateFault", + "Cannot delete DocDB cluster " + id + " — it still has DB instances.", 400); + } + + cluster.setStatus("deleting"); + clusters.put(id, cluster); + + if (cluster.getContainerId() != null) { + containerManager.stop(new DocDbContainerHandle( + cluster.getContainerId(), id, + cluster.getContainerHost(), cluster.getContainerPort())); + } + + clusters.delete(id); + LOG.infov("DocDB cluster {0} deleted", id); + } + + // ── Instances ───────────────────────────────────────────────────────────── + + public DocDbInstance createDbInstance(String id, String dbClusterIdentifier, + String dbInstanceClass, String engineVersion, + boolean iamEnabled) { + if (instances.get(id).isPresent()) { + throw new AwsException("DBInstanceAlreadyExists", + "DocDB instance " + id + " already exists.", 400); + } + + DocDbCluster cluster = getDbCluster(dbClusterIdentifier); + String region = regionResolver.getDefaultRegion(); + + DocDbInstance instance = new DocDbInstance(); + instance.setDbInstanceIdentifier(id); + instance.setDbClusterIdentifier(dbClusterIdentifier); + instance.setDbInstanceClass(dbInstanceClass != null ? dbInstanceClass : "db.r5.large"); + instance.setEngineVersion(engineVersion != null ? engineVersion : cluster.getEngineVersion()); + instance.setStatus("available"); + instance.setEndpoint(cluster.getEndpoint()); + instance.setPort(cluster.getPort()); + instance.setIamDatabaseAuthenticationEnabled(iamEnabled); + instance.setDbInstanceArn(regionResolver.buildArn("rds", region, "db:" + id)); + instance.setDbiResourceId("db-" + UUID.randomUUID().toString() + .replace("-", "").substring(0, 24).toUpperCase()); + instance.setCreatedAt(Instant.now()); + + cluster.getDbClusterMembers().add(id); + clusters.put(dbClusterIdentifier, cluster); + + instances.put(id, instance); + LOG.infov("DocDB instance {0} created in cluster {1}", id, dbClusterIdentifier); + return instance; + } + + public DocDbInstance getDbInstance(String id) { + return instances.get(id).orElseThrow(() -> + new AwsException("DBInstanceNotFound", + "DocDB instance " + id + " not found.", 404)); + } + + public Collection listDbInstances(String filterId) { + if (filterId != null && !filterId.isBlank()) { + return instances.scan(k -> k.equalsIgnoreCase(filterId)); + } + return instances.scan(k -> true); + } + + public DocDbInstance modifyDbInstance(String id, String dbInstanceClass, Boolean iamEnabled) { + DocDbInstance instance = getDbInstance(id); + if (dbInstanceClass != null && !dbInstanceClass.isBlank()) { + instance.setDbInstanceClass(dbInstanceClass); + } + if (iamEnabled != null) { + instance.setIamDatabaseAuthenticationEnabled(iamEnabled); + } + instances.put(id, instance); + LOG.infov("DocDB instance {0} modified", id); + return instance; + } + + public void deleteDbInstance(String id) { + DocDbInstance instance = instances.get(id).orElseThrow(() -> + new AwsException("DBInstanceNotFound", + "DocDB instance " + id + " not found.", 404)); + + String clusterId = instance.getDbClusterIdentifier(); + DocDbCluster cluster = clusters.get(clusterId).orElse(null); + if (cluster != null) { + cluster.getDbClusterMembers().remove(id); + clusters.put(clusterId, cluster); + } + + instances.delete(id); + LOG.infov("DocDB instance {0} deleted", id); + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + private String resolveEndpointHost() { + return config.hostname().orElse("localhost"); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerHandle.java new file mode 100644 index 0000000000..a07902620d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerHandle.java @@ -0,0 +1,26 @@ +package io.github.hectorvent.floci.services.docdb.container; + +import java.io.Closeable; + +public class DocDbContainerHandle { + + private final String containerId; + private final String clusterId; + private final String host; + private final int port; + private Closeable logStream; + + public DocDbContainerHandle(String containerId, String clusterId, String host, int port) { + this.containerId = containerId; + this.clusterId = clusterId; + this.host = host; + this.port = port; + } + + public String getContainerId() { return containerId; } + public String getClusterId() { return clusterId; } + public String getHost() { return host; } + public int getPort() { return port; } + public Closeable getLogStream() { return logStream; } + public void setLogStream(Closeable logStream) { this.logStream = logStream; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.java new file mode 100644 index 0000000000..75d8352ffc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.docdb.container; + + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.Closeable; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@ApplicationScoped +public class DocDbContainerManager { + + private static final Logger LOG = Logger.getLogger(DocDbContainerManager.class); + private static final int MONGO_PORT = 27017; + private static final int BACKEND_READY_DEADLINE_MS = 60_000; + private static final int BACKEND_READY_RETRY_MS = 200; + private static final int BACKEND_PROBE_CONNECT_MS = 2_000; + + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final ContainerLogStreamer logStreamer; + private final ContainerDetector containerDetector; + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final Map activeContainers = new ConcurrentHashMap<>(); + + @Inject + public DocDbContainerManager(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerLogStreamer logStreamer, + ContainerDetector containerDetector, + EmulatorConfig config, + RegionResolver regionResolver) { + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.logStreamer = logStreamer; + this.containerDetector = containerDetector; + this.config = config; + this.regionResolver = regionResolver; + } + + public DocDbContainerHandle start(String clusterId, String image, String masterUsername, String masterPassword) { + LOG.infov("Starting DocumentDB container for cluster: {0}", clusterId); + + String containerName = "floci-docdb-" + clusterId; + lifecycleManager.removeIfExists(containerName); + + List envVars = List.of( + "MONGO_INITDB_ROOT_USERNAME=" + masterUsername, + "MONGO_INITDB_ROOT_PASSWORD=" + masterPassword + ); + + ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image) + .withName(containerName) + .withDockerNetwork(config.services().docdb().dockerNetwork()) + .withLogRotation() + .withEnv(envVars); + + if (!containerDetector.isRunningInContainer()) { + specBuilder.withDynamicPort(MONGO_PORT); + } else { + specBuilder.withExposedPort(MONGO_PORT); + } + + + ContainerSpec spec = specBuilder.build(); + ContainerInfo info = lifecycleManager.createAndStart(spec); + EndpointInfo endpoint = info.getEndpoint(MONGO_PORT); + + LOG.infov("DocumentDB container for cluster {0}: {1}", clusterId, endpoint); + + DocDbContainerHandle handle = new DocDbContainerHandle( + info.containerId(), clusterId, endpoint.host(), endpoint.port()); + activeContainers.put(clusterId, handle); + + String shortId = info.containerId().length() >= 8 + ? info.containerId().substring(0, 8) + : info.containerId(); + String logGroup = "/aws/docdb/cluster/" + clusterId + "/audit"; + String logStream = logStreamer.generateLogStreamName(shortId); + String region = regionResolver.getDefaultRegion(); + + Closeable logHandle = logStreamer.attach( + info.containerId(), logGroup, logStream, region, "docdb:" + clusterId); + handle.setLogStream(logHandle); + + waitForBackendReady(clusterId, endpoint.host(), endpoint.port()); + + return handle; + } + + public void stop(DocDbContainerHandle handle) { + if (handle == null) { + return; + } + activeContainers.remove(handle.getClusterId()); + lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream()); + } + + public void stopAll() { + List handles = new ArrayList<>(activeContainers.values()); + if (!handles.isEmpty()) { + LOG.infov("Stopping {0} DocumentDB container(s) on shutdown", handles.size()); + } + for (DocDbContainerHandle handle : handles) { + stop(handle); + } + } + + private static void waitForBackendReady(String clusterId, String host, int port) { + long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS; + int attempt = 0; + while (System.currentTimeMillis() < deadline) { + attempt++; + try (Socket s = new Socket()) { + s.connect(new InetSocketAddress(host, port), BACKEND_PROBE_CONNECT_MS); + if (attempt > 1) { + LOG.infov("MongoDB backend ready for cluster {0} after {1} probe attempt(s)", + clusterId, attempt); + } + return; + } catch (IOException e) { + if (LOG.isDebugEnabled()) { + LOG.debugv("MongoDB probe for cluster {0} attempt {1}: {2}", + clusterId, attempt, e.getMessage()); + } + } + try { + Thread.sleep(BACKEND_READY_RETRY_MS); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException( + "Interrupted while waiting for MongoDB backend " + clusterId, ie); + } + } + throw new RuntimeException( + "MongoDB backend for cluster " + clusterId + " did not become ready on " + + host + ":" + port + " within " + BACKEND_READY_DEADLINE_MS + "ms"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/model/DocDbCluster.java b/src/main/java/io/github/hectorvent/floci/services/docdb/model/DocDbCluster.java new file mode 100644 index 0000000000..98e074720e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/docdb/model/DocDbCluster.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.docdb.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +@RegisterForReflection +public class DocDbCluster { + private String masterUsername; + + private String dbClusterIdentifier; + private String status; + private String engineVersion; + private String endpoint; + private int port; + private String readerEndpoint; + private boolean iamDatabaseAuthenticationEnabled; + private String dbClusterArn; + private String dbClusterResourceId; + private List dbClusterMembers = new ArrayList<>(); + private Instant createdAt; + + // Docker / proxy runtime fields — persisted so cleanup works across restarts + private String containerId; + private String containerHost; + private int containerPort; + + public DocDbCluster (){} + + public String getMasterUsername(){return masterUsername;} + public void setMasterUsername(String masterUsername){this.masterUsername = masterUsername;} + + public String getDbClusterIdentifier() { return dbClusterIdentifier; } + public void setDbClusterIdentifier(String dbClusterIdentifier) { this.dbClusterIdentifier = dbClusterIdentifier; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getEngineVersion() { return engineVersion; } + public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } + + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + public int getPort() { return port; } + public void setPort(int port) { this.port = port; } + + public String getReaderEndpoint() { return readerEndpoint; } + public void setReaderEndpoint(String readerEndpoint) { this.readerEndpoint = readerEndpoint; } + + public boolean isIamDatabaseAuthenticationEnabled() { return iamDatabaseAuthenticationEnabled; } + public void setIamDatabaseAuthenticationEnabled(boolean iamDatabaseAuthenticationEnabled) { + this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled; + } + + public String getDbClusterArn() { return dbClusterArn; } + public void setDbClusterArn(String dbClusterArn) { this.dbClusterArn = dbClusterArn; } + + public String getDbClusterResourceId() { return dbClusterResourceId; } + public void setDbClusterResourceId(String dbClusterResourceId) { this.dbClusterResourceId = dbClusterResourceId; } + + public List getDbClusterMembers() { return dbClusterMembers; } + public void setDbClusterMembers(List dbClusterMembers) { + this.dbClusterMembers = dbClusterMembers != null ? new ArrayList<>(dbClusterMembers) : new ArrayList<>(); + } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public String getContainerId() { return containerId; } + public void setContainerId(String containerId) { this.containerId = containerId; } + + public String getContainerHost() { return containerHost; } + public void setContainerHost(String containerHost) { this.containerHost = containerHost; } + + public int getContainerPort() { return containerPort; } + public void setContainerPort(int containerPort) { this.containerPort = containerPort; } + + +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/model/DocDbInstance.java b/src/main/java/io/github/hectorvent/floci/services/docdb/model/DocDbInstance.java new file mode 100644 index 0000000000..81eb57332a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/docdb/model/DocDbInstance.java @@ -0,0 +1,58 @@ +package io.github.hectorvent.floci.services.docdb.model; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +@RegisterForReflection +public class DocDbInstance { + + private String dbInstanceIdentifier; + private String dbClusterIdentifier; + private String dbInstanceClass; + private String engineVersion; + private String status; + private String endpoint; + private int port; + private boolean iamDatabaseAuthenticationEnabled; + private String dbInstanceArn; + private String dbiResourceId; + private Instant createdAt; + + public DocDbInstance(){} + + public String getDbInstanceIdentifier() { return dbInstanceIdentifier; } + public void setDbInstanceIdentifier(String dbInstanceIdentifier) { this.dbInstanceIdentifier = dbInstanceIdentifier; } + + public String getDbClusterIdentifier() { return dbClusterIdentifier; } + public void setDbClusterIdentifier(String dbClusterIdentifier) { this.dbClusterIdentifier = dbClusterIdentifier; } + + public String getDbInstanceClass() { return dbInstanceClass; } + public void setDbInstanceClass(String dbInstanceClass) { this.dbInstanceClass = dbInstanceClass; } + + public String getEngineVersion() { return engineVersion; } + public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + public int getPort() { return port; } + public void setPort(int port) { this.port = port; } + + public boolean isIamDatabaseAuthenticationEnabled() { return iamDatabaseAuthenticationEnabled; } + public void setIamDatabaseAuthenticationEnabled(boolean iamDatabaseAuthenticationEnabled) { + this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled; + } + + public String getDbInstanceArn() { return dbInstanceArn; } + public void setDbInstanceArn(String dbInstanceArn) { this.dbInstanceArn = dbInstanceArn; } + + public String getDbiResourceId() { return dbiResourceId; } + public void setDbiResourceId(String dbiResourceId) { this.dbiResourceId = dbiResourceId; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + +} \ No newline at end of file diff --git a/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbIntegrationTest.java new file mode 100644 index 0000000000..7dc0db4b96 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbIntegrationTest.java @@ -0,0 +1,323 @@ +package io.github.hectorvent.floci.services.docdb; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class DocDbIntegrationTest { + + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String CLUSTER_ID = "my-docdb-cluster"; + private static final String INSTANCE_ID = "my-docdb-instance"; + private static final String MASTER_USERNAME = "docdbadmin"; + private static final String MASTER_PASSWORD = "secret99password"; + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260615/us-east-1/docdb/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + + private static final String AUTH_RDS_SCOPE = + "AWS4-HMAC-SHA256 Credential=test/20260615/us-east-1/rds/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + + @Test + @Order(1) + void createCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("Engine", "docdb") + .formParam("MasterUsername", MASTER_USERNAME) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)) + .body(containsString("available")) + .body(containsString("docdb")) + .body(containsString("5.0.0")) + .body(containsString(MASTER_USERNAME)) + .body(not(containsString(MASTER_PASSWORD))); + } + + @Test + @Order(2) + void createClusterDuplicateFails() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("Engine", "docdb") + .formParam("MasterUsername", MASTER_USERNAME) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/") + .then() + .statusCode(400) + .body(containsString("DBClusterAlreadyExistsFault")); + } + + @Test + @Order(3) + void describeClusters() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)); + } + + @Test + @Order(4) + void describeClusterById() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)) + .body(containsString("docdb")); + } + + @Test + @Order(5) + void describeClusterNotFound() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", "nonexistent-cluster") + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(6) + void modifyCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "ModifyDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("EngineVersion", "6.0.0") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)) + .body(containsString("6.0.0")); + } + + @Test + @Order(7) + void createInstance() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBInstance") + .formParam("DBInstanceIdentifier", INSTANCE_ID) + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "docdb") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)) + .body(containsString(CLUSTER_ID)) + .body(containsString("available")) + .body(containsString("db.r5.large")); + } + + @Test + @Order(8) + void clusterHasInstanceMember() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)); + } + + @Test + @Order(9) + void describeInstances() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBInstances") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)); + } + + @Test + @Order(10) + void createInstanceRequiresCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBInstance") + .formParam("DBInstanceIdentifier", "orphan-instance") + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "docdb") + .when().post("/") + .then() + .statusCode(400) + .body(containsString("DBClusterIdentifier is required")); + } + + @Test + @Order(11) + void deleteClusterWithInstanceFails() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(400) + .body(containsString("InvalidDBClusterStateFault")); + } + + @Test + @Order(12) + void deleteInstance() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBInstance") + .formParam("DBInstanceIdentifier", INSTANCE_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)); + } + + @Test + @Order(13) + void clusterHasNoMembersAfterInstanceDelete() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(not(containsString(INSTANCE_ID))); + } + + @Test + @Order(14) + void deleteCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)); + } + + @Test + @Order(15) + void describeAfterDeleteReturnsNotFound() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(16) + void unsupportedAction() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "RestoreDBClusterFromSnapshot") + .when().post("/") + .then() + .statusCode(400) + .body(containsString("UnsupportedOperation")); + } + + private static final String RDS_SCOPE_CLUSTER_ID = "rds-scope-docdb-cluster"; + + @Test + @Order(17) + void realSdkPathCreateRoutesToDocDbViaEngine() { + given() + .header("Authorization", AUTH_RDS_SCOPE) + .contentType(FORM) + .formParam("Action", "CreateDBCluster") + .formParam("DBClusterIdentifier", RDS_SCOPE_CLUSTER_ID) + .formParam("Engine", "docdb") + .formParam("MasterUsername", MASTER_USERNAME) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(RDS_SCOPE_CLUSTER_ID)) + .body(containsString("available")) + .body(containsString("docdb")); + } + + @Test + @Order(18) + void realSdkPathDescribeByIdRoutesToDocDbViaExistingCluster() { + given() + .header("Authorization", AUTH_RDS_SCOPE) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", RDS_SCOPE_CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(RDS_SCOPE_CLUSTER_ID)) + .body(containsString("docdb")); + } + + @Test + @Order(19) + void realSdkPathDeleteCleansUp() { + given() + .header("Authorization", AUTH_RDS_SCOPE) + .contentType(FORM) + .formParam("Action", "DeleteDBCluster") + .formParam("DBClusterIdentifier", RDS_SCOPE_CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(RDS_SCOPE_CLUSTER_ID)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java new file mode 100644 index 0000000000..02d5870657 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java @@ -0,0 +1,94 @@ +package io.github.hectorvent.floci.services.docdb; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager; +import io.github.hectorvent.floci.services.docdb.model.DocDbCluster; +import io.github.hectorvent.floci.services.docdb.model.DocDbInstance; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DocDbServiceTest { + + private DocDbService docDbService; + private DocDbContainerManager containerManager; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = Mockito.mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(invocation -> new InMemoryStorage<>()); + + EmulatorConfig config = Mockito.mock(EmulatorConfig.class); + var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); + var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class); + when(config.services()).thenReturn(servicesConfig); + when(servicesConfig.docdb()).thenReturn(docdbConfig); + when(docdbConfig.mock()).thenReturn(true); + + containerManager = Mockito.mock(DocDbContainerManager.class); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + docDbService = new DocDbService(config, regionResolver, containerManager, storageFactory); + } + + @Test + void createClusterInMockModeSkipsContainer() { + DocDbCluster cluster = docDbService.createDbCluster( + "mock-cluster", null, "admin", "secret", false); + + assertNotNull(cluster); + assertEquals("mock-cluster", cluster.getDbClusterIdentifier()); + assertEquals("available", cluster.getStatus()); + assertEquals("localhost", cluster.getEndpoint()); + assertEquals(27017, cluster.getPort()); + assertTrue(cluster.getDbClusterArn().contains("mock-cluster")); + + verify(containerManager, never()).start(anyString(), anyString(), anyString(), anyString()); + } + + @Test + void describeClusterInMockMode() { + docDbService.createDbCluster("mock-cluster", null, "admin", "secret", false); + + DocDbCluster described = docDbService.getDbCluster("mock-cluster"); + assertEquals("mock-cluster", described.getDbClusterIdentifier()); + assertEquals("available", described.getStatus()); + } + + @Test + void createInstanceInMockMode() { + docDbService.createDbCluster("mock-cluster", null, "admin", "secret", false); + + DocDbInstance instance = docDbService.createDbInstance( + "mock-instance", "mock-cluster", "db.r5.large", null, false); + + assertNotNull(instance); + assertEquals("mock-instance", instance.getDbInstanceIdentifier()); + assertEquals("mock-cluster", instance.getDbClusterIdentifier()); + assertEquals("available", instance.getStatus()); + assertEquals("localhost", instance.getEndpoint()); + assertEquals(27017, instance.getPort()); + } + + @Test + void deleteClusterInMockModeSkipsContainerStop() { + docDbService.createDbCluster("mock-cluster", null, "admin", "secret", false); + + docDbService.deleteDbCluster("mock-cluster"); + + assertTrue(docDbService.listDbClusters(null).isEmpty()); + verify(containerManager, never()).stop(any()); + } +}