feat: add opensearch service emulation (#85) (#132)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-03-31 00:48:41 -04:00
1 parent bb4f000914
commit 68b8ed883a
17 files changed
+1683 -3

No files matched your search

@@ -72,6 +72,7 @@ public interface EmulatorConfig {
CloudWatchMetricsStorageConfig cloudwatchmetrics();
SecretsManagerStorageConfig secretsmanager();
AcmStorageConfig acm();
OpenSearchStorageConfig opensearch();
}
interface SsmStorageConfig {
@@ -138,6 +139,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface OpenSearchStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface WalConfig {
@WithDefault("30000")
long compactionIntervalMs();
@@ -178,6 +186,7 @@ public interface EmulatorConfig {
CloudFormationServiceConfig cloudformation();
AcmServiceConfig acm();
SesServiceConfig ses();
OpenSearchServiceConfig opensearch();
}
interface SsmServiceConfig {
@@ -337,6 +346,25 @@ public interface EmulatorConfig {
boolean enabled();
}
interface OpenSearchServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("mock")
String mode();
@WithDefault("opensearchproject/opensearch:2")
String defaultImage();
@WithDefault("9400")
int proxyBasePort();
@WithDefault("9499")
int proxyMaxPort();
Optional<String> dockerNetwork();
}
interface LambdaServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -47,6 +47,7 @@ public class ServiceRegistry {
case "cloudformation" -> config.services().cloudformation().enabled();
case "acm" -> config.services().acm().enabled();
case "email" -> config.services().ses().enabled();
case "es" -> config.services().opensearch().enabled();
default -> true;
};
}
@@ -75,6 +76,7 @@ public class ServiceRegistry {
if (config.services().cloudformation().enabled()) enabled.add("cloudformation");
if (config.services().acm().enabled()) enabled.add("acm");
if (config.services().ses().enabled()) enabled.add("email");
if (config.services().opensearch().enabled()) enabled.add("es");
return enabled;
}
@@ -109,6 +109,7 @@ public class StorageFactory {
case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().mode().orElse(globalMode);
case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().mode().orElse(globalMode);
case "secretsmanager" -> config.storage().services().secretsmanager().mode().orElse(globalMode);
case "opensearch" -> config.storage().services().opensearch().mode().orElse(globalMode);
default -> globalMode;
};
}
@@ -122,6 +123,7 @@ public class StorageFactory {
case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().flushIntervalMs();
case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().flushIntervalMs();
case "secretsmanager" -> config.storage().services().secretsmanager().flushIntervalMs();
case "opensearch" -> config.storage().services().opensearch().flushIntervalMs();
default -> 5000L;
};
}
@@ -0,0 +1,556 @@
package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.opensearch.model.ClusterConfig;
import io.github.hectorvent.floci.services.opensearch.model.Domain;
import io.github.hectorvent.floci.services.opensearch.model.EbsOptions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("/2021-01-01")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class OpenSearchController {
private static final Logger LOG = Logger.getLogger(OpenSearchController.class);
private static final List<String> SUPPORTED_VERSIONS = List.of(
"OpenSearch_2.13", "OpenSearch_2.11", "OpenSearch_2.9", "OpenSearch_2.7",
"OpenSearch_2.5", "OpenSearch_2.3", "OpenSearch_1.3", "OpenSearch_1.2",
"Elasticsearch_7.10", "Elasticsearch_7.9", "Elasticsearch_7.8"
);
private static final List<String> INSTANCE_TYPES = List.of(
"t3.small.search", "t3.medium.search",
"m5.large.search", "m5.xlarge.search", "m5.2xlarge.search",
"r5.large.search", "r5.xlarge.search", "r5.2xlarge.search",
"c5.large.search", "c5.xlarge.search", "c5.2xlarge.search"
);
private final OpenSearchService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public OpenSearchController(OpenSearchService service, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/opensearch/domain")
public Response createDomain(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode req = objectMapper.readTree(body);
String domainName = req.path("DomainName").asText(null);
String engineVersion = req.path("EngineVersion").asText(null);
ClusterConfig clusterConfig = parseClusterConfig(req.path("ClusterConfig"));
EbsOptions ebsOptions = parseEbsOptions(req.path("EBSOptions"));
Map<String, String> tags = parseTags(req.path("TagList"));
Domain domain = service.createDomain(domainName, engineVersion, clusterConfig,
ebsOptions, tags, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("DomainStatus", toDomainStatusNode(domain));
return Response.ok(response).build();
} catch (AwsException e) {
throw e;
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@GET
@Path("/opensearch/domain/{domainName}")
public Response describeDomain(@Context HttpHeaders headers,
@PathParam("domainName") String domainName) {
Domain domain = service.describeDomain(domainName);
ObjectNode response = objectMapper.createObjectNode();
response.set("DomainStatus", toDomainStatusNode(domain));
return Response.ok(response).build();
}
@POST
@Path("/opensearch/domain-info")
public Response describeDomains(@Context HttpHeaders headers, String body) {
try {
JsonNode req = objectMapper.readTree(body);
List<String> names = new ArrayList<>();
req.path("DomainNames").forEach(n -> names.add(n.asText()));
List<Domain> domains = service.describeDomains(names);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode list = response.putArray("DomainStatusList");
domains.forEach(d -> list.add(toDomainStatusNode(d)));
return Response.ok(response).build();
} catch (AwsException e) {
throw e;
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@GET
@Path("/domain")
public Response listDomainNames(@Context HttpHeaders headers,
@QueryParam("engineType") String engineType) {
List<Domain> domains = service.listDomainNames(engineType);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode list = response.putArray("DomainNames");
for (Domain d : domains) {
ObjectNode entry = objectMapper.createObjectNode();
entry.put("DomainName", d.getDomainName());
String ev = d.getEngineVersion();
entry.put("EngineType", (ev != null && ev.startsWith("Elasticsearch")) ? "Elasticsearch" : "OpenSearch");
list.add(entry);
}
return Response.ok(response).build();
}
@GET
@Path("/opensearch/domain/{domainName}/config")
public Response describeDomainConfig(@Context HttpHeaders headers,
@PathParam("domainName") String domainName) {
Domain domain = service.describeDomain(domainName);
long epochSeconds = domain.getCreatedAt() != null ? domain.getCreatedAt().getEpochSecond() : 0;
ObjectNode response = objectMapper.createObjectNode();
ObjectNode domainConfig = response.putObject("DomainConfig");
ObjectNode clusterSection = domainConfig.putObject("ClusterConfig");
clusterSection.set("Options", toClusterConfigNode(domain.getClusterConfig()));
clusterSection.set("Status", configStatusNode(epochSeconds));
ObjectNode ebsSection = domainConfig.putObject("EBSOptions");
ebsSection.set("Options", toEbsOptionsNode(domain.getEbsOptions()));
ebsSection.set("Status", configStatusNode(epochSeconds));
ObjectNode versionSection = domainConfig.putObject("EngineVersion");
versionSection.put("Options", domain.getEngineVersion());
versionSection.set("Status", configStatusNode(epochSeconds));
return Response.ok(response).build();
}
@POST
@Path("/opensearch/domain/{domainName}/config")
public Response updateDomainConfig(@Context HttpHeaders headers,
@PathParam("domainName") String domainName,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode req = objectMapper.readTree(body);
String engineVersion = req.path("EngineVersion").asText(null);
ClusterConfig clusterConfig = parseClusterConfig(req.path("ClusterConfig"));
EbsOptions ebsOptions = parseEbsOptions(req.path("EBSOptions"));
Domain domain = service.updateDomainConfig(domainName, engineVersion, clusterConfig,
ebsOptions, region);
long epochSeconds = domain.getCreatedAt() != null ? domain.getCreatedAt().getEpochSecond() : 0;
ObjectNode response = objectMapper.createObjectNode();
ObjectNode domainConfig = response.putObject("DomainConfig");
ObjectNode clusterSection = domainConfig.putObject("ClusterConfig");
clusterSection.set("Options", toClusterConfigNode(domain.getClusterConfig()));
clusterSection.set("Status", configStatusNode(epochSeconds));
ObjectNode ebsSection = domainConfig.putObject("EBSOptions");
ebsSection.set("Options", toEbsOptionsNode(domain.getEbsOptions()));
ebsSection.set("Status", configStatusNode(epochSeconds));
ObjectNode versionSection = domainConfig.putObject("EngineVersion");
versionSection.put("Options", domain.getEngineVersion());
versionSection.set("Status", configStatusNode(epochSeconds));
return Response.ok(response).build();
} catch (AwsException e) {
throw e;
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@DELETE
@Path("/opensearch/domain/{domainName}")
public Response deleteDomain(@Context HttpHeaders headers,
@PathParam("domainName") String domainName) {
Domain domain = service.deleteDomain(domainName);
ObjectNode response = objectMapper.createObjectNode();
response.set("DomainStatus", toDomainStatusNode(domain));
return Response.ok(response).build();
}
// ── Tags ─────────────────────────────────────────────────────────────────
@POST
@Path("/tags")
public Response addTags(@Context HttpHeaders headers, String body) {
try {
JsonNode req = objectMapper.readTree(body);
String arn = req.path("ARN").asText(null);
if (arn == null || arn.isBlank()) {
throw new AwsException("ValidationException", "ARN is required.", 400);
}
Map<String, String> tags = parseTags(req.path("TagList"));
service.addTags(arn, tags);
return Response.ok("{}").build();
} catch (AwsException e) {
throw e;
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@GET
@Path("/tags/")
public Response listTags(@Context HttpHeaders headers, @QueryParam("arn") String arn) {
if (arn == null || arn.isBlank()) {
throw new AwsException("ValidationException", "ARN query parameter is required.", 400);
}
Map<String, String> tags = service.listTags(arn);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode tagList = response.putArray("TagList");
tags.forEach((k, v) -> {
ObjectNode tag = objectMapper.createObjectNode();
tag.put("Key", k);
tag.put("Value", v);
tagList.add(tag);
});
return Response.ok(response).build();
}
@POST
@Path("/tags-removal")
public Response removeTags(@Context HttpHeaders headers, String body) {
try {
JsonNode req = objectMapper.readTree(body);
String arn = req.path("ARN").asText(null);
if (arn == null || arn.isBlank()) {
throw new AwsException("ValidationException", "ARN is required.", 400);
}
List<String> tagKeys = new ArrayList<>();
req.path("TagKeys").forEach(n -> tagKeys.add(n.asText()));
service.removeTags(arn, tagKeys);
return Response.ok("{}").build();
} catch (AwsException e) {
throw e;
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@GET
@Path("/opensearch/versions")
public Response listVersions(@Context HttpHeaders headers) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode versions = response.putArray("Versions");
SUPPORTED_VERSIONS.forEach(versions::add);
return Response.ok(response).build();
}
@GET
@Path("/opensearch/compatibleVersions")
public Response getCompatibleVersions(@Context HttpHeaders headers,
@QueryParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode compatibleVersions = response.putArray("CompatibleVersions");
ObjectNode entry = objectMapper.createObjectNode();
entry.put("SourceVersion", "OpenSearch_2.9");
ArrayNode targets = entry.putArray("TargetVersions");
targets.add("OpenSearch_2.11");
targets.add("OpenSearch_2.13");
compatibleVersions.add(entry);
return Response.ok(response).build();
}
@GET
@Path("/opensearch/instanceTypeDetails/{engineVersion}")
public Response listInstanceTypeDetails(@Context HttpHeaders headers,
@PathParam("engineVersion") String engineVersion) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode details = response.putArray("InstanceTypeDetails");
for (String instanceType : INSTANCE_TYPES) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("InstanceType", instanceType);
detail.put("EncryptionEnabled", true);
detail.put("CognitoEnabled", false);
detail.put("AppLogsEnabled", true);
detail.put("AdvancedSecurityEnabled", false);
ArrayNode roles = detail.putArray("InstanceRole");
roles.add("Data");
details.add(detail);
}
return Response.ok(response).build();
}
@GET
@Path("/opensearch/instanceTypeLimits/{engineVersion}/{instanceType}")
public Response describeInstanceTypeLimits(@Context HttpHeaders headers,
@PathParam("engineVersion") String engineVersion,
@PathParam("instanceType") String instanceType) {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode limitsByRole = response.putObject("LimitsByRole");
ObjectNode dataRole = limitsByRole.putObject("data");
ArrayNode storageTypes = dataRole.putArray("StorageTypes");
ObjectNode storageType = objectMapper.createObjectNode();
storageType.put("StorageTypeName", "ebs");
storageType.put("StorageSubTypeName", "standard");
ArrayNode storageTypeLimits = storageType.putArray("StorageTypeLimits");
ObjectNode minLimit = objectMapper.createObjectNode();
minLimit.put("LimitName", "MinimumVolumeSize");
minLimit.putArray("LimitValues").add("10");
storageTypeLimits.add(minLimit);
ObjectNode maxLimit = objectMapper.createObjectNode();
maxLimit.put("LimitName", "MaximumVolumeSize");
maxLimit.putArray("LimitValues").add("3584");
storageTypeLimits.add(maxLimit);
storageTypes.add(storageType);
ObjectNode instanceLimits = dataRole.putObject("InstanceLimits");
ObjectNode instanceCountLimits = instanceLimits.putObject("InstanceCountLimits");
instanceCountLimits.put("MinimumInstanceCount", 1);
instanceCountLimits.put("MaximumInstanceCount", 20);
dataRole.putArray("AdditionalLimits");
return Response.ok(response).build();
}
@GET
@Path("/opensearch/domain/{domainName}/progress")
public Response describeDomainChangeProgress(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.putObject("ChangeProgressStatus");
return Response.ok(response).build();
}
@GET
@Path("/opensearch/domain/{domainName}/autoTunes")
public Response describeDomainAutoTunes(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("AutoTunes");
return Response.ok(response).build();
}
@GET
@Path("/opensearch/domain/{domainName}/dryRun")
public Response describeDryRunProgress(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.putObject("DryRunProgressStatus");
return Response.ok(response).build();
}
@GET
@Path("/opensearch/domain/{domainName}/health")
public Response describeDomainHealth(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.put("ClusterHealth", "Green");
return Response.ok(response).build();
}
@GET
@Path("/opensearch/upgradeDomain/{domainName}/history")
public Response getUpgradeHistory(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("UpgradeHistories");
return Response.ok(response).build();
}
@GET
@Path("/opensearch/upgradeDomain/{domainName}/status")
public Response getUpgradeStatus(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.put("UpgradeStep", "UPGRADE");
response.put("StepStatus", "SUCCEEDED");
response.put("UpgradeName", "");
return Response.ok(response).build();
}
@POST
@Path("/opensearch/upgradeDomain")
public Response upgradeDomain(String body) {
try {
JsonNode req = objectMapper.readTree(body);
String domainName = req.path("DomainName").asText(null);
String targetVersion = req.path("TargetVersion").asText(null);
Domain domain = service.upgradeDomain(domainName, targetVersion);
ObjectNode response = objectMapper.createObjectNode();
response.put("DomainName", domain.getDomainName());
response.put("TargetVersion", domain.getEngineVersion());
response.put("PerformCheckOnly", false);
return Response.ok(response).build();
} catch (AwsException e) {
throw e;
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@POST
@Path("/opensearch/domain/{domainName}/config/cancel")
public Response cancelDomainConfigChange(@PathParam("domainName") String domainName) {
ObjectNode response = objectMapper.createObjectNode();
response.put("DryRun", false);
response.putArray("CancelledChangeIds");
return Response.ok(response).build();
}
@POST
@Path("/opensearch/serviceSoftwareUpdate/start")
public Response startServiceSoftwareUpdate(String body) {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode options = response.putObject("ServiceSoftwareOptions");
options.put("UpdateAvailable", false);
options.put("Cancellable", false);
options.put("UpdateStatus", "COMPLETED");
options.put("Description", "There is no software update available for this domain.");
options.put("AutomatedUpdateDate", 0);
options.put("OptionalDeployment", false);
return Response.ok(response).build();
}
@POST
@Path("/opensearch/serviceSoftwareUpdate/cancel")
public Response cancelServiceSoftwareUpdate(String body) {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode options = response.putObject("ServiceSoftwareOptions");
options.put("UpdateAvailable", false);
options.put("Cancellable", false);
options.put("UpdateStatus", "COMPLETED");
options.put("Description", "There is no software update available for this domain.");
options.put("AutomatedUpdateDate", 0);
options.put("OptionalDeployment", false);
return Response.ok(response).build();
}
// ── Helpers ───────────────────────────────────────────────────────────────
private ObjectNode toDomainStatusNode(Domain domain) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ARN", domain.getArn());
node.put("DomainId", domain.getDomainId());
node.put("DomainName", domain.getDomainName());
node.put("EngineVersion", domain.getEngineVersion());
node.put("Processing", domain.isProcessing());
node.put("Deleted", domain.isDeleted());
node.put("Endpoint", domain.getEndpoint() != null ? domain.getEndpoint() : "");
node.set("ClusterConfig", toClusterConfigNode(domain.getClusterConfig()));
node.set("EBSOptions", toEbsOptionsNode(domain.getEbsOptions()));
return node;
}
private ObjectNode toClusterConfigNode(ClusterConfig cc) {
ObjectNode node = objectMapper.createObjectNode();
if (cc == null) {
node.put("InstanceType", "m5.large.search");
node.put("InstanceCount", 1);
node.put("DedicatedMasterEnabled", false);
node.put("ZoneAwarenessEnabled", false);
} else {
node.put("InstanceType", cc.getInstanceType());
node.put("InstanceCount", cc.getInstanceCount());
node.put("DedicatedMasterEnabled", cc.isDedicatedMasterEnabled());
node.put("ZoneAwarenessEnabled", cc.isZoneAwarenessEnabled());
}
return node;
}
private ObjectNode toEbsOptionsNode(EbsOptions ebs) {
ObjectNode node = objectMapper.createObjectNode();
if (ebs == null) {
node.put("EBSEnabled", true);
node.put("VolumeType", "gp2");
node.put("VolumeSize", 10);
} else {
node.put("EBSEnabled", ebs.isEbsEnabled());
node.put("VolumeType", ebs.getVolumeType());
node.put("VolumeSize", ebs.getVolumeSize());
}
return node;
}
private ObjectNode configStatusNode(long epochSeconds) {
ObjectNode status = objectMapper.createObjectNode();
status.put("CreationDate", epochSeconds);
status.put("UpdateDate", epochSeconds);
status.put("State", "Active");
return status;
}
private ClusterConfig parseClusterConfig(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
}
ClusterConfig cc = new ClusterConfig();
if (node.has("InstanceType")) {
cc.setInstanceType(node.get("InstanceType").asText());
}
if (node.has("InstanceCount")) {
cc.setInstanceCount(node.get("InstanceCount").asInt());
}
if (node.has("DedicatedMasterEnabled")) {
cc.setDedicatedMasterEnabled(node.get("DedicatedMasterEnabled").asBoolean());
}
if (node.has("ZoneAwarenessEnabled")) {
cc.setZoneAwarenessEnabled(node.get("ZoneAwarenessEnabled").asBoolean());
}
return cc;
}
private EbsOptions parseEbsOptions(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
}
EbsOptions ebs = new EbsOptions();
if (node.has("EBSEnabled")) {
ebs.setEbsEnabled(node.get("EBSEnabled").asBoolean());
}
if (node.has("VolumeType")) {
ebs.setVolumeType(node.get("VolumeType").asText());
}
if (node.has("VolumeSize")) {
ebs.setVolumeSize(node.get("VolumeSize").asInt());
}
return ebs;
}
private Map<String, String> parseTags(JsonNode node) {
Map<String, String> tags = new HashMap<>();
if (node == null || node.isMissingNode() || node.isNull()) {
return tags;
}
node.forEach(tag -> {
String key = tag.path("Key").asText(null);
String value = tag.path("Value").asText(null);
if (key != null && value != null) {
tags.put(key, value);
}
});
return tags;
}
}
@@ -0,0 +1,190 @@
package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.opensearch.model.ClusterConfig;
import io.github.hectorvent.floci.services.opensearch.model.Domain;
import io.github.hectorvent.floci.services.opensearch.model.EbsOptions;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class OpenSearchService {
private static final Logger LOG = Logger.getLogger(OpenSearchService.class);
private static final String DEFAULT_ENGINE_VERSION = "OpenSearch_2.11";
private final StorageBackend<String, Domain> domainStore;
private final EmulatorConfig config;
@Inject
public OpenSearchService(StorageFactory storageFactory, EmulatorConfig config) {
this.domainStore = storageFactory.create("opensearch", "opensearch-domains.json",
new TypeReference<Map<String, Domain>>() {});
this.config = config;
}
OpenSearchService(StorageBackend<String, Domain> domainStore, EmulatorConfig config) {
this.domainStore = domainStore;
this.config = config;
}
public Domain createDomain(String domainName, String engineVersion, ClusterConfig clusterConfig,
EbsOptions ebsOptions, Map<String, String> tags, String region) {
validateDomainName(domainName);
if (domainStore.get(domainName).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException",
"Domain with name " + domainName + " already exists.", 409);
}
String accountId = config.defaultAccountId();
Domain domain = new Domain();
domain.setDomainName(domainName);
domain.setDomainId(accountId + "/" + domainName);
domain.setArn("arn:aws:es:" + region + ":" + accountId + ":domain/" + domainName);
domain.setEngineVersion(engineVersion != null ? engineVersion : DEFAULT_ENGINE_VERSION);
domain.setProcessing(false);
domain.setDeleted(false);
domain.setEndpoint("");
domain.setCreatedAt(Instant.now());
if (clusterConfig != null) {
domain.setClusterConfig(clusterConfig);
}
if (ebsOptions != null) {
domain.setEbsOptions(ebsOptions);
}
if (tags != null) {
domain.setTags(tags);
}
domainStore.put(domainName, domain);
LOG.infov("Created OpenSearch domain: {0}", domainName);
return domain;
}
public Domain describeDomain(String domainName) {
return domainStore.get(domainName)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Domain not found: " + domainName, 409));
}
public List<Domain> describeDomains(List<String> domainNames) {
return domainNames.stream()
.map(name -> domainStore.get(name)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Domain not found: " + name, 409)))
.toList();
}
public List<Domain> listDomainNames(String engineType) {
return domainStore.scan(k -> true).stream()
.filter(d -> !d.isDeleted())
.filter(d -> engineType == null || engineType.isBlank()
|| matchesEngineType(d.getEngineVersion(), engineType))
.toList();
}
public Domain updateDomainConfig(String domainName, String engineVersion,
ClusterConfig clusterConfig, EbsOptions ebsOptions,
String region) {
Domain domain = describeDomain(domainName);
if (engineVersion != null && !engineVersion.isBlank()) {
domain.setEngineVersion(engineVersion);
}
if (clusterConfig != null) {
ClusterConfig existing = domain.getClusterConfig();
if (clusterConfig.getInstanceType() != null) {
existing.setInstanceType(clusterConfig.getInstanceType());
}
if (clusterConfig.getInstanceCount() > 0) {
existing.setInstanceCount(clusterConfig.getInstanceCount());
}
existing.setDedicatedMasterEnabled(clusterConfig.isDedicatedMasterEnabled());
existing.setZoneAwarenessEnabled(clusterConfig.isZoneAwarenessEnabled());
}
if (ebsOptions != null) {
EbsOptions existing = domain.getEbsOptions();
existing.setEbsEnabled(ebsOptions.isEbsEnabled());
if (ebsOptions.getVolumeType() != null) {
existing.setVolumeType(ebsOptions.getVolumeType());
}
if (ebsOptions.getVolumeSize() > 0) {
existing.setVolumeSize(ebsOptions.getVolumeSize());
}
}
domainStore.put(domainName, domain);
return domain;
}
public Domain deleteDomain(String domainName) {
Domain domain = describeDomain(domainName);
domain.setDeleted(true);
domainStore.delete(domainName);
LOG.infov("Deleted OpenSearch domain: {0}", domainName);
return domain;
}
public void addTags(String arn, Map<String, String> tags) {
Domain domain = findByArn(arn);
domain.getTags().putAll(tags);
domainStore.put(domain.getDomainName(), domain);
}
public Map<String, String> listTags(String arn) {
return findByArn(arn).getTags();
}
public void removeTags(String arn, List<String> tagKeys) {
Domain domain = findByArn(arn);
tagKeys.forEach(domain.getTags()::remove);
domainStore.put(domain.getDomainName(), domain);
}
public Domain upgradeDomain(String domainName, String targetVersion) {
Domain domain = describeDomain(domainName);
if (targetVersion != null && !targetVersion.isBlank()) {
domain.setEngineVersion(targetVersion);
domainStore.put(domainName, domain);
}
return domain;
}
private Domain findByArn(String arn) {
return domainStore.scan(k -> true).stream()
.filter(d -> arn.equals(d.getArn()))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Domain not found for ARN: " + arn, 409));
}
private void validateDomainName(String name) {
if (name == null || name.length() < 3 || name.length() > 28) {
throw new AwsException("ValidationException",
"Domain name must be between 3 and 28 characters.", 400);
}
if (!name.matches("[a-z][a-z0-9\\-]*")) {
throw new AwsException("ValidationException",
"Domain name must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens.", 400);
}
}
private boolean matchesEngineType(String engineVersion, String engineType) {
if ("Elasticsearch".equalsIgnoreCase(engineType)) {
return engineVersion != null && engineVersion.startsWith("Elasticsearch");
}
return engineVersion == null || engineVersion.startsWith("OpenSearch");
}
}
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.services.opensearch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ClusterConfig {
@JsonProperty("InstanceType")
private String instanceType = "m5.large.search";
@JsonProperty("InstanceCount")
private int instanceCount = 1;
@JsonProperty("DedicatedMasterEnabled")
private boolean dedicatedMasterEnabled = false;
@JsonProperty("ZoneAwarenessEnabled")
private boolean zoneAwarenessEnabled = false;
public ClusterConfig() {}
public String getInstanceType() {
return instanceType;
}
public void setInstanceType(String instanceType) {
this.instanceType = instanceType;
}
public int getInstanceCount() {
return instanceCount;
}
public void setInstanceCount(int instanceCount) {
this.instanceCount = instanceCount;
}
public boolean isDedicatedMasterEnabled() {
return dedicatedMasterEnabled;
}
public void setDedicatedMasterEnabled(boolean dedicatedMasterEnabled) {
this.dedicatedMasterEnabled = dedicatedMasterEnabled;
}
public boolean isZoneAwarenessEnabled() {
return zoneAwarenessEnabled;
}
public void setZoneAwarenessEnabled(boolean zoneAwarenessEnabled) {
this.zoneAwarenessEnabled = zoneAwarenessEnabled;
}
}
@@ -0,0 +1,137 @@
package io.github.hectorvent.floci.services.opensearch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Domain {
@JsonProperty("DomainName")
private String domainName;
@JsonProperty("DomainId")
private String domainId;
@JsonProperty("ARN")
private String arn;
@JsonProperty("EngineVersion")
private String engineVersion = "OpenSearch_2.11";
@JsonProperty("Processing")
private boolean processing = false;
@JsonProperty("Deleted")
private boolean deleted = false;
@JsonProperty("ClusterConfig")
private ClusterConfig clusterConfig = new ClusterConfig();
@JsonProperty("EBSOptions")
private EbsOptions ebsOptions = new EbsOptions();
@JsonProperty("Endpoint")
private String endpoint = "";
@JsonProperty("Tags")
private Map<String, String> tags = new HashMap<>();
@JsonProperty("CreatedAt")
private Instant createdAt;
public Domain() {}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public boolean isProcessing() {
return processing;
}
public void setProcessing(boolean processing) {
this.processing = processing;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public ClusterConfig getClusterConfig() {
return clusterConfig;
}
public void setClusterConfig(ClusterConfig clusterConfig) {
this.clusterConfig = clusterConfig;
}
public EbsOptions getEbsOptions() {
return ebsOptions;
}
public void setEbsOptions(EbsOptions ebsOptions) {
this.ebsOptions = ebsOptions;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? new HashMap<>(tags) : new HashMap<>();
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
}
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.services.opensearch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class EbsOptions {
@JsonProperty("EBSEnabled")
private boolean ebsEnabled = true;
@JsonProperty("VolumeType")
private String volumeType = "gp2";
@JsonProperty("VolumeSize")
private int volumeSize = 10;
public EbsOptions() {}
public boolean isEbsEnabled() {
return ebsEnabled;
}
public void setEbsEnabled(boolean ebsEnabled) {
this.ebsEnabled = ebsEnabled;
}
public String getVolumeType() {
return volumeType;
}
public void setVolumeType(String volumeType) {
this.volumeType = volumeType;
}
public int getVolumeSize() {
return volumeSize;
}
public void setVolumeSize(int volumeSize) {
this.volumeSize = volumeSize;
}
}