mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(opensearch): report VPC domains under Endpoints.vpc and emulate VPC endpoints (#7351)
This commit is contained in:
1 parent
055036508e
commit
d74a084a61
11 files changed
+1063
-11
No files matched your search
@@ -553,6 +553,15 @@ public class IamActionRegistry {
|
||||
rule("ses", "POST", "^/v2/email/update-configuration-sets/?$", "ses:UpdateConfigurationSet"),
|
||||
rule("ses", "POST", "^/v2/email/vdm/recommendations/?$", "ses:ListRecommendations"),
|
||||
|
||||
// ── OpenSearch Service VPC endpoints ───────────────────────────────────
|
||||
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/?$", "es:CreateVpcEndpoint"),
|
||||
rule("es", "GET", "^/2021-01-01/opensearch/vpcEndpoints/?$", "es:ListVpcEndpoints"),
|
||||
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/describe/?$", "es:DescribeVpcEndpoints"),
|
||||
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/update/?$", "es:UpdateVpcEndpoint"),
|
||||
rule("es", "DELETE", "^/2021-01-01/opensearch/vpcEndpoints/[^/]+/?$", "es:DeleteVpcEndpoint"),
|
||||
rule("es", "GET", "^/2021-01-01/opensearch/domain/[^/]+/vpcEndpoints/?$",
|
||||
"es:ListVpcEndpointsForDomain"),
|
||||
|
||||
// ── Resource Groups ─────────────────────────────────────────────────────
|
||||
rule("resource-groups", "POST", "^/_rg/groups/?$", "resource-groups:CreateGroup"),
|
||||
rule("resource-groups", "POST", "^/_rg/get-group/?$", "resource-groups:GetGroup"),
|
||||
|
||||
+137
-3
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.opensearch.model.DomainEndpointOption
|
||||
import io.github.hectorvent.floci.services.opensearch.model.EbsOptions;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.EncryptionAtRestOptions;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.NodeToNodeEncryptionOptions;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.OpenSearchVpcEndpoint;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.VpcOptions;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
@@ -37,17 +38,24 @@ public class OpenSearchController {
|
||||
private static final Logger LOG = Logger.getLogger(OpenSearchController.class);
|
||||
|
||||
private final OpenSearchService service;
|
||||
private final OpenSearchVpcEndpointService vpcEndpoints;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public OpenSearchController(OpenSearchService service, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
public OpenSearchController(OpenSearchService service, OpenSearchVpcEndpointService vpcEndpoints,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.vpcEndpoints = vpcEndpoints;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/** For {@link ElasticsearchController}, which delegates the domain operations only. */
|
||||
OpenSearchController(OpenSearchService service, RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this(service, null, regionResolver, objectMapper);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/opensearch/domain")
|
||||
public Response createDomain(@Context HttpHeaders headers, String body) {
|
||||
@@ -484,6 +492,125 @@ public class OpenSearchController {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// ── VPC endpoints ────────────────────────────────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/opensearch/vpcEndpoints")
|
||||
public Response createVpcEndpoint(@Context HttpHeaders headers, String body) {
|
||||
JsonNode req = readBody(body);
|
||||
OpenSearchVpcEndpoint endpoint = vpcEndpoints.create(req.path("DomainArn").asText(null),
|
||||
parseVpcOptions(req.path("VpcOptions")), egressEnabled(req), req.path("ClientToken").asText(null),
|
||||
regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("VpcEndpoint", toVpcEndpointNode(endpoint, "CREATING"));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/opensearch/vpcEndpoints/describe")
|
||||
public Response describeVpcEndpoints(@Context HttpHeaders headers, String body) {
|
||||
JsonNode req = readBody(body);
|
||||
List<String> ids = null;
|
||||
if (req.path("VpcEndpointIds").isArray()) {
|
||||
ids = new ArrayList<>();
|
||||
for (JsonNode id : req.path("VpcEndpointIds")) {
|
||||
ids.add(id.asText());
|
||||
}
|
||||
}
|
||||
OpenSearchVpcEndpointService.DescribeResult result =
|
||||
vpcEndpoints.describe(ids, regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode found = response.putArray("VpcEndpoints");
|
||||
result.endpoints().forEach(endpoint -> found.add(toVpcEndpointNode(endpoint, endpoint.getStatus())));
|
||||
ArrayNode errors = response.putArray("VpcEndpointErrors");
|
||||
for (OpenSearchVpcEndpointService.EndpointError error : result.errors()) {
|
||||
errors.addObject()
|
||||
.put("VpcEndpointId", error.vpcEndpointId())
|
||||
.put("ErrorCode", error.errorCode())
|
||||
.put("ErrorMessage", error.errorMessage());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/opensearch/vpcEndpoints/update")
|
||||
public Response updateVpcEndpoint(@Context HttpHeaders headers, String body) {
|
||||
JsonNode req = readBody(body);
|
||||
OpenSearchVpcEndpoint endpoint = vpcEndpoints.update(req.path("VpcEndpointId").asText(null),
|
||||
parseVpcOptions(req.path("VpcOptions")), egressEnabled(req), regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("VpcEndpoint", toVpcEndpointNode(endpoint, "UPDATING"));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/opensearch/vpcEndpoints/{vpcEndpointId}")
|
||||
public Response deleteVpcEndpoint(@Context HttpHeaders headers,
|
||||
@PathParam("vpcEndpointId") String vpcEndpointId) {
|
||||
OpenSearchVpcEndpoint endpoint = vpcEndpoints.delete(vpcEndpointId, regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("VpcEndpointSummary", toVpcEndpointSummaryNode(endpoint, "DELETING"));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/** One page holds every endpoint, so no {@code NextToken} is returned. */
|
||||
@GET
|
||||
@Path("/opensearch/vpcEndpoints")
|
||||
public Response listVpcEndpoints(@Context HttpHeaders headers) {
|
||||
return vpcEndpointSummaries(vpcEndpoints.list(regionResolver.resolveRegion(headers)));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/opensearch/domain/{domainName}/vpcEndpoints")
|
||||
public Response listVpcEndpointsForDomain(@Context HttpHeaders headers,
|
||||
@PathParam("domainName") String domainName) {
|
||||
return vpcEndpointSummaries(vpcEndpoints.listForDomain(domainName, regionResolver.resolveRegion(headers)));
|
||||
}
|
||||
|
||||
private Response vpcEndpointSummaries(List<OpenSearchVpcEndpoint> endpoints) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode list = response.putArray("VpcEndpointSummaryList");
|
||||
endpoints.forEach(endpoint -> list.add(toVpcEndpointSummaryNode(endpoint, endpoint.getStatus())));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode toVpcEndpointNode(OpenSearchVpcEndpoint endpoint, String status) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("VpcEndpointId", endpoint.getVpcEndpointId());
|
||||
node.put("VpcEndpointOwner", endpoint.getVpcEndpointOwner());
|
||||
node.put("DomainArn", endpoint.getDomainArn());
|
||||
ObjectNode options = toVpcOptionsNode(endpoint.getVpcOptions());
|
||||
if (endpoint.getEgressEnabled() != null) {
|
||||
options.put("EgressEnabled", endpoint.getEgressEnabled());
|
||||
}
|
||||
node.set("VpcOptions", options);
|
||||
node.put("Status", status);
|
||||
vpcEndpoints.endpointAddress(endpoint).ifPresent(address -> node.put("Endpoint", address));
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toVpcEndpointSummaryNode(OpenSearchVpcEndpoint endpoint, String status) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("VpcEndpointId", endpoint.getVpcEndpointId());
|
||||
node.put("VpcEndpointOwner", endpoint.getVpcEndpointOwner());
|
||||
node.put("DomainArn", endpoint.getDomainArn());
|
||||
node.put("Status", status);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static Boolean egressEnabled(JsonNode req) {
|
||||
JsonNode egress = req.path("VpcOptions").path("EgressEnabled");
|
||||
return egress.isBoolean() ? egress.asBoolean() : null;
|
||||
}
|
||||
|
||||
private JsonNode readBody(String body) {
|
||||
try {
|
||||
return body == null || body.isBlank() ? objectMapper.createObjectNode() : objectMapper.readTree(body);
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("ValidationException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private ObjectNode toDomainStatusNode(Domain domain) {
|
||||
@@ -495,7 +622,14 @@ public class OpenSearchController {
|
||||
node.put("Created", !domain.isProcessing());
|
||||
node.put("Processing", domain.isProcessing());
|
||||
node.put("Deleted", domain.isDeleted());
|
||||
node.put("Endpoint", domain.getEndpoint() != null ? domain.getEndpoint() : "");
|
||||
String endpoint = domain.getEndpoint() != null ? domain.getEndpoint() : "";
|
||||
if (domain.getVpcOptions() == null) {
|
||||
node.put("Endpoint", endpoint);
|
||||
} else if (!endpoint.isEmpty()) {
|
||||
// AWS reports a domain in a VPC under Endpoints.vpc and leaves Endpoint out; the Terraform
|
||||
// AWS provider refuses a VPC domain that carries an Endpoint.
|
||||
node.putObject("Endpoints").put("vpc", endpoint);
|
||||
}
|
||||
if (domain.getAccessPolicies() != null) {
|
||||
node.put("AccessPolicies", domain.getAccessPolicies());
|
||||
}
|
||||
|
||||
+23
-7
@@ -161,12 +161,12 @@ public class OpenSearchService implements ResourceProvider {
|
||||
|
||||
if (config.services().opensearch().mock()) {
|
||||
domain.setProcessing(false);
|
||||
domain.setEndpoint(synthesizedEndpoint(domainName, region));
|
||||
domain.setEndpoint(synthesizedEndpoint(domain, region));
|
||||
} else {
|
||||
domain.setProcessing(true);
|
||||
if (!domainManager.tryStartDomain(domain)) {
|
||||
domain.setProcessing(false);
|
||||
domain.setEndpoint(synthesizedEndpoint(domainName, region));
|
||||
domain.setEndpoint(synthesizedEndpoint(domain, region));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,15 +181,17 @@ public class OpenSearchService implements ResourceProvider {
|
||||
* {@link OpenSearchDomainManager#tryStartDomain} returns false rather than rethrowing.
|
||||
*
|
||||
* <p>It reports an AWS-shaped endpoint in place of a blank one,
|
||||
* {@code search-<domain>-<suffix>.<region>.es.<dnsSuffix>}, taking the DNS suffix from the
|
||||
* region's partition rather than assuming the commercial one, with the name suffix derived from the
|
||||
* domain name so it survives a restart. A domain reporting {@code Processing false} alongside
|
||||
* {@code search-<domain>-<suffix>.<region>.es.<dnsSuffix>}, or {@code vpc-<domain>-...} for a domain in a
|
||||
* VPC, taking the DNS suffix from the region's partition rather than assuming the commercial one, with the
|
||||
* name suffix derived from the domain name so it survives a restart. A domain reporting {@code Processing false} alongside
|
||||
* {@code Endpoint ""} describes a state AWS never returns, and a client that reads the endpoint
|
||||
* to address the domain gets an empty string to connect to.
|
||||
*/
|
||||
private static String synthesizedEndpoint(String domainName, String region) {
|
||||
private static String synthesizedEndpoint(Domain domain, String region) {
|
||||
String domainName = domain.getDomainName();
|
||||
String suffix = Integer.toHexString(domainName.hashCode() & 0x7fffffff);
|
||||
return "search-" + domainName + "-" + suffix + "." + region + ".es."
|
||||
String prefix = domain.getVpcOptions() != null ? "vpc-" : "search-";
|
||||
return prefix + domainName + "-" + suffix + "." + region + ".es."
|
||||
+ AwsRegions.dnsSuffixFor(region);
|
||||
}
|
||||
|
||||
@@ -199,6 +201,20 @@ public class OpenSearchService implements ResourceProvider {
|
||||
"Domain not found: " + domainName, 409));
|
||||
}
|
||||
|
||||
/** The domain called {@code domainName} in the caller's account and {@code region}, empty when there is none. */
|
||||
public Optional<Domain> findDomain(String domainName, String region) {
|
||||
return findDomain(regionResolver.getAccountId(), region, domainName);
|
||||
}
|
||||
|
||||
/** The domain an ARN names in the caller's account, empty when there is none. */
|
||||
public Optional<Domain> findDomainByArn(String arn) {
|
||||
try {
|
||||
return Optional.of(findByArn(arn));
|
||||
} catch (AwsException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public List<Domain> describeDomains(List<String> domainNames, String region) {
|
||||
return domainNames.stream()
|
||||
.map(name -> describeDomain(name, region))
|
||||
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
package io.github.hectorvent.floci.services.opensearch;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.Domain;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.OpenSearchVpcEndpoint;
|
||||
import io.github.hectorvent.floci.services.opensearch.model.VpcOptions;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* OpenSearch Service-managed VPC endpoints, scoped to an account and a region like the domains
|
||||
* they lead to. An endpoint is stored {@code ACTIVE}: the create, update and delete responses carry
|
||||
* the transitional status AWS answers with, and the next read already sees the settled one.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class OpenSearchVpcEndpointService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(OpenSearchVpcEndpointService.class);
|
||||
|
||||
static final String ENDPOINT_NOT_FOUND = "ENDPOINT_NOT_FOUND";
|
||||
// Both captured from DescribeVpcEndpoints against AWS for an id that does not exist.
|
||||
static final String ENDPOINT_NOT_FOUND_MESSAGE = "Endpoint does not exist";
|
||||
private static final String ID_PATTERN = "^aos-[a-zA-Z0-9]*$";
|
||||
private static final Pattern ID = Pattern.compile(ID_PATTERN);
|
||||
private static final int ID_MIN = 5;
|
||||
private static final int ID_MAX = 256;
|
||||
|
||||
private final AccountAwareStorageBackend<OpenSearchVpcEndpoint> endpoints;
|
||||
private final OpenSearchService domains;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
public OpenSearchVpcEndpointService(StorageFactory storageFactory, OpenSearchService domains,
|
||||
RegionResolver regionResolver, Ec2Service ec2Service) {
|
||||
this(storageFactory.create("opensearch", "opensearch-vpc-endpoints.json",
|
||||
new TypeReference<Map<String, OpenSearchVpcEndpoint>>() {}), domains, regionResolver, ec2Service);
|
||||
}
|
||||
|
||||
OpenSearchVpcEndpointService(AccountAwareStorageBackend<OpenSearchVpcEndpoint> endpoints,
|
||||
OpenSearchService domains, RegionResolver regionResolver, Ec2Service ec2Service) {
|
||||
this.endpoints = endpoints;
|
||||
this.domains = domains;
|
||||
this.regionResolver = regionResolver;
|
||||
this.ec2Service = ec2Service;
|
||||
}
|
||||
|
||||
/** One {@code VpcEndpointErrors} entry. */
|
||||
public record EndpointError(String vpcEndpointId, String errorCode, String errorMessage) {}
|
||||
|
||||
/** The endpoints found and an error for each id that names none, as {@code DescribeVpcEndpoints} answers. */
|
||||
public record DescribeResult(List<OpenSearchVpcEndpoint> endpoints, List<EndpointError> errors) {}
|
||||
|
||||
/**
|
||||
* Creates an endpoint for the domain the ARN names. A retry carrying the same {@code ClientToken}
|
||||
* for the same domain answers the endpoint the first call created.
|
||||
*/
|
||||
public synchronized OpenSearchVpcEndpoint create(String domainArn, VpcOptions requested, Boolean egressEnabled,
|
||||
String clientToken, String region) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (domainArn == null || domainArn.isBlank()) {
|
||||
violations.add(SmithyValidationErrors.notNull("domainArn"));
|
||||
}
|
||||
if (requested == null) {
|
||||
violations.add(SmithyValidationErrors.notNull("vpcOptions"));
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
// The endpoint is kept in the request's Region, so a domain of another Region is refused as
|
||||
// unknown: neither Region's ListVpcEndpointsForDomain could otherwise find the endpoint.
|
||||
Domain domain = domains.findDomainByArn(domainArn)
|
||||
.filter(found -> region.equals(AwsArnUtils.parse(found.getArn()).region()))
|
||||
.orElseThrow(() -> new AwsException("ValidationException",
|
||||
"Domain not found for ARN: " + domainArn, 400));
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
Optional<OpenSearchVpcEndpoint> earlier = inRegion(region).stream()
|
||||
.filter(endpoint -> clientToken.equals(endpoint.getClientToken())
|
||||
&& domain.getArn().equals(endpoint.getDomainArn()))
|
||||
.findFirst();
|
||||
if (earlier.isPresent()) {
|
||||
return earlier.get();
|
||||
}
|
||||
}
|
||||
|
||||
OpenSearchVpcEndpoint endpoint = new OpenSearchVpcEndpoint();
|
||||
endpoint.setVpcEndpointId("aos-" + newIdSuffix());
|
||||
endpoint.setVpcEndpointOwner(regionResolver.getAccountId());
|
||||
endpoint.setDomainArn(domain.getArn());
|
||||
endpoint.setVpcOptions(resolved(requested, region));
|
||||
endpoint.setEgressEnabled(egressEnabled);
|
||||
endpoint.setClientToken(clientToken);
|
||||
endpoint.setStatus("ACTIVE");
|
||||
endpoints.put(storageKey(region, endpoint.getVpcEndpointId()), endpoint);
|
||||
LOG.infov("Created OpenSearch VPC endpoint {0} for {1}", endpoint.getVpcEndpointId(), domain.getArn());
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public DescribeResult describe(List<String> vpcEndpointIds, String region) {
|
||||
if (vpcEndpointIds == null) {
|
||||
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("vpcEndpointIds"));
|
||||
}
|
||||
// AWS checks the list as a whole, quoting all of it, as captured for one malformed id.
|
||||
if (vpcEndpointIds.stream().anyMatch(id -> !validId(id))) {
|
||||
throw SmithyValidationErrors.validationException("Value '" + vpcEndpointIds
|
||||
+ "' at 'vpcEndpointIds' failed to satisfy constraint: Member must satisfy constraint: "
|
||||
+ SmithyValidationErrors.constraintSet(ID_MIN, ID_MAX, ID_PATTERN, null));
|
||||
}
|
||||
List<OpenSearchVpcEndpoint> found = new ArrayList<>();
|
||||
List<EndpointError> errors = new ArrayList<>();
|
||||
for (String id : new LinkedHashSet<>(vpcEndpointIds)) {
|
||||
Optional<OpenSearchVpcEndpoint> endpoint = endpoints.get(storageKey(region, id));
|
||||
if (endpoint.isPresent()) {
|
||||
found.add(endpoint.get());
|
||||
} else {
|
||||
errors.add(new EndpointError(id, ENDPOINT_NOT_FOUND, ENDPOINT_NOT_FOUND_MESSAGE));
|
||||
}
|
||||
}
|
||||
return new DescribeResult(found, errors);
|
||||
}
|
||||
|
||||
/** Replaces the subnets, the security groups and the egress setting the request names. */
|
||||
public synchronized OpenSearchVpcEndpoint update(String vpcEndpointId, VpcOptions requested,
|
||||
Boolean egressEnabled, String region) {
|
||||
List<String> violations = new ArrayList<>(idViolations(vpcEndpointId));
|
||||
if (requested == null) {
|
||||
violations.add(SmithyValidationErrors.notNull("vpcOptions"));
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
OpenSearchVpcEndpoint endpoint = require(vpcEndpointId, region);
|
||||
endpoint.setVpcOptions(resolved(requested, region));
|
||||
if (egressEnabled != null) {
|
||||
endpoint.setEgressEnabled(egressEnabled);
|
||||
}
|
||||
endpoints.put(storageKey(region, vpcEndpointId), endpoint);
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public synchronized OpenSearchVpcEndpoint delete(String vpcEndpointId, String region) {
|
||||
List<String> violations = idViolations(vpcEndpointId);
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
OpenSearchVpcEndpoint endpoint = require(vpcEndpointId, region);
|
||||
endpoints.delete(storageKey(region, vpcEndpointId));
|
||||
LOG.infov("Deleted OpenSearch VPC endpoint {0}", vpcEndpointId);
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/** Every endpoint in the caller's account and region, in id order. */
|
||||
public List<OpenSearchVpcEndpoint> list(String region) {
|
||||
return inRegion(region);
|
||||
}
|
||||
|
||||
/**
|
||||
* The endpoints of the domain called {@code domainName}. A name no domain carries lists nothing
|
||||
* rather than failing, as AWS was captured answering.
|
||||
*/
|
||||
public List<OpenSearchVpcEndpoint> listForDomain(String domainName, String region) {
|
||||
Optional<Domain> domain = domains.findDomain(domainName, region);
|
||||
if (domain.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
String domainArn = domain.get().getArn();
|
||||
return inRegion(region).stream()
|
||||
.filter(endpoint -> domainArn.equals(endpoint.getDomainArn()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The address a client reaches the endpoint's domain at, which in Floci is the domain's own. */
|
||||
public Optional<String> endpointAddress(OpenSearchVpcEndpoint endpoint) {
|
||||
return domains.findDomainByArn(endpoint.getDomainArn())
|
||||
.map(Domain::getEndpoint)
|
||||
.filter(address -> !address.isEmpty());
|
||||
}
|
||||
|
||||
private OpenSearchVpcEndpoint require(String vpcEndpointId, String region) {
|
||||
return endpoints.get(storageKey(region, vpcEndpointId))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", ENDPOINT_NOT_FOUND_MESSAGE, 409));
|
||||
}
|
||||
|
||||
private List<OpenSearchVpcEndpoint> inRegion(String region) {
|
||||
return endpoints.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.sorted(Comparator.comparing(OpenSearchVpcEndpoint::getVpcEndpointId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The requested subnets and security groups, with the VPC and zones EC2 knows the subnets by. A
|
||||
* subnet EC2 does not know is kept as given and left unresolved. Without security groups the
|
||||
* endpoint takes the VPC's default one, as AWS does, when EC2 knows the VPC and still has it.
|
||||
*/
|
||||
private VpcOptions resolved(VpcOptions requested, String region) {
|
||||
VpcOptions options = new VpcOptions();
|
||||
options.setSubnetIds(new ArrayList<>(requested.getSubnetIds()));
|
||||
options.setSecurityGroupIds(new ArrayList<>(requested.getSecurityGroupIds()));
|
||||
if (ec2Service != null && !requested.getSubnetIds().isEmpty()) {
|
||||
Map<String, Subnet> known = new HashMap<>();
|
||||
ec2Service.describeSubnets(region, requested.getSubnetIds(), Map.of())
|
||||
.forEach(subnet -> known.put(subnet.getSubnetId(), subnet));
|
||||
// In the order the subnets were requested.
|
||||
Set<String> zones = new LinkedHashSet<>();
|
||||
for (String subnetId : requested.getSubnetIds()) {
|
||||
Subnet subnet = known.get(subnetId);
|
||||
if (subnet != null) {
|
||||
zones.add(subnet.getAvailabilityZone());
|
||||
if (options.getVpcId() == null) {
|
||||
options.setVpcId(subnet.getVpcId());
|
||||
}
|
||||
}
|
||||
}
|
||||
options.setAvailabilityZones(new ArrayList<>(zones));
|
||||
if (options.getSecurityGroupIds().isEmpty() && options.getVpcId() != null) {
|
||||
ec2Service.defaultSecurityGroupOf(region, options.getVpcId())
|
||||
.ifPresent(group -> options.setSecurityGroupIds(new ArrayList<>(List.of(group.getGroupId()))));
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private static List<String> idViolations(String vpcEndpointId) {
|
||||
if (vpcEndpointId == null || vpcEndpointId.isEmpty()) {
|
||||
return List.of(SmithyValidationErrors.notNull("vpcEndpointId"));
|
||||
}
|
||||
List<String> violations = new ArrayList<>();
|
||||
String length = SmithyValidationErrors.lengthOutOfRange("vpcEndpointId", vpcEndpointId, ID_MIN, ID_MAX);
|
||||
if (length != null) {
|
||||
violations.add(length);
|
||||
}
|
||||
if (!ID.matcher(vpcEndpointId).matches()) {
|
||||
violations.add(SmithyValidationErrors.pattern("vpcEndpointId", vpcEndpointId, ID_PATTERN));
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
private static boolean validId(String id) {
|
||||
return id != null && id.length() >= ID_MIN && id.length() <= ID_MAX && ID.matcher(id).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* Twelve hexadecimal digits, the form AWS endpoint ids take. An id is no secret, and a random
|
||||
* held in a static field would be fixed into the native image at build time.
|
||||
*/
|
||||
private static String newIdSuffix() {
|
||||
byte[] bytes = new byte[6];
|
||||
ThreadLocalRandom.current().nextBytes(bytes);
|
||||
return HexFormat.of().formatHex(bytes);
|
||||
}
|
||||
|
||||
private static String storageKey(String region, String vpcEndpointId) {
|
||||
return region + "::" + vpcEndpointId;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* An OpenSearch Service-managed VPC endpoint ({@code CreateVpcEndpoint}): a way into a VPC domain
|
||||
* from another VPC. Floci keeps the record; no network interface is created.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class OpenSearchVpcEndpoint {
|
||||
|
||||
@JsonProperty("VpcEndpointId")
|
||||
private String vpcEndpointId;
|
||||
|
||||
@JsonProperty("VpcEndpointOwner")
|
||||
private String vpcEndpointOwner;
|
||||
|
||||
@JsonProperty("DomainArn")
|
||||
private String domainArn;
|
||||
|
||||
/** Subnets and security groups as requested, with the VPC and zones EC2 knows them by. */
|
||||
@JsonProperty("VpcOptions")
|
||||
private VpcOptions vpcOptions = new VpcOptions();
|
||||
|
||||
@JsonProperty("EgressEnabled")
|
||||
private Boolean egressEnabled;
|
||||
|
||||
@JsonProperty("Status")
|
||||
private String status;
|
||||
|
||||
/** Scopes a retried {@code CreateVpcEndpoint} to the endpoint it already created. */
|
||||
@JsonProperty("ClientToken")
|
||||
private String clientToken;
|
||||
|
||||
public String getVpcEndpointId() { return vpcEndpointId; }
|
||||
public void setVpcEndpointId(String vpcEndpointId) { this.vpcEndpointId = vpcEndpointId; }
|
||||
|
||||
public String getVpcEndpointOwner() { return vpcEndpointOwner; }
|
||||
public void setVpcEndpointOwner(String vpcEndpointOwner) { this.vpcEndpointOwner = vpcEndpointOwner; }
|
||||
|
||||
public String getDomainArn() { return domainArn; }
|
||||
public void setDomainArn(String domainArn) { this.domainArn = domainArn; }
|
||||
|
||||
public VpcOptions getVpcOptions() { return vpcOptions; }
|
||||
public void setVpcOptions(VpcOptions vpcOptions) { this.vpcOptions = vpcOptions; }
|
||||
|
||||
public Boolean getEgressEnabled() { return egressEnabled; }
|
||||
public void setEgressEnabled(Boolean egressEnabled) { this.egressEnabled = egressEnabled; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getClientToken() { return clientToken; }
|
||||
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
|
||||
}
|
||||
Reference in new issue
Block a user