mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(ecs): create the Cloud Map services of a Service Connect service's endpoints (#9022)
A Service Connect service that offers endpoints now has them in the Cloud Map namespace it joined. CreateService and UpdateService create an HTTP Cloud Map service for each services[] entry, named by its discoveryName or else its portName, and one for a client configuration, aws-ecs-sc.client.<UUID>.<service name>, described "Managed by" the ECS service and tagged AmazonECSManaged=true. Each deployment reports them as serviceConnectResources. UpdateService keeps, creates and deletes them to match, turning Service Connect off or DeleteService deletes them all, and a circuit-breaker rollback brings them back in line. Discovery names are checked before anything is created, under a lock per namespace: one outside ECS's naming rule, one named twice, one another ECS service holds and one a Cloud Map service created outside ECS holds are refused with ECS's messages, ClientException on CreateService and InvalidParameterException on UpdateService. ECS only reuses or deletes Cloud Map services it made. Cloud Map's duplicate-name check moves into CloudMapService.findServiceByName, shared with the registrar.
This commit is contained in:
1 parent
3ae5b8b6ea
commit
29cd4a84ee
11 files changed
+860
-31
No files matched your search
@@ -173,6 +173,11 @@ public class CloudMapService implements StoredResourceArns {
|
||||
return requireNamespace(id);
|
||||
}
|
||||
|
||||
/** Whether a namespace is a DNS one, public or private, whose service names are DNS labels. */
|
||||
public static boolean isDnsNamespace(Namespace namespace) {
|
||||
return "DNS_PRIVATE".equals(namespace.getType()) || "DNS_PUBLIC".equals(namespace.getType());
|
||||
}
|
||||
|
||||
public List<Namespace> listNamespaces(String region) {
|
||||
List<Namespace> result = new ArrayList<>();
|
||||
for (Namespace n : scan(namespaceStore)) {
|
||||
@@ -235,14 +240,11 @@ public class CloudMapService implements StoredResourceArns {
|
||||
// DnsConfig may carry the namespace id when the top-level field is absent.
|
||||
resolvedNamespaceId = dnsConfigNode.path("NamespaceId").textValue();
|
||||
}
|
||||
Namespace namespace = resolvedNamespaceId == null ? null : requireNamespace(resolvedNamespaceId);
|
||||
boolean dnsNamespace = namespace != null && ("DNS_PRIVATE".equals(namespace.getType())
|
||||
|| "DNS_PUBLIC".equals(namespace.getType()));
|
||||
if (resolvedNamespaceId != null) {
|
||||
requireNamespace(resolvedNamespaceId);
|
||||
}
|
||||
final String nsId = resolvedNamespaceId;
|
||||
boolean exists = scan(serviceStore).stream()
|
||||
.anyMatch(s -> region.equals(s.getRegion()) && Objects.equals(nsId, s.getNamespaceId())
|
||||
&& (dnsNamespace ? name.equalsIgnoreCase(s.getName()) : name.equals(s.getName())));
|
||||
if (exists) {
|
||||
if (findServiceByName(name, nsId, region).isPresent()) {
|
||||
throw new AwsException("ServiceAlreadyExists",
|
||||
"A service named \"" + name + "\" already exists.", 400);
|
||||
}
|
||||
@@ -278,6 +280,19 @@ public class CloudMapService implements StoredResourceArns {
|
||||
return requireService(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The service named {@code name} in the namespace {@code namespaceId} of {@code region}, of
|
||||
* which there is at most one. A DNS namespace compares names without case, as DNS labels are.
|
||||
*/
|
||||
public Optional<Service> findServiceByName(String name, String namespaceId, String region) {
|
||||
Namespace namespace = namespaceId == null ? null : namespaceStore.get(namespaceId).orElse(null);
|
||||
boolean dnsNamespace = namespace != null && isDnsNamespace(namespace);
|
||||
return scan(serviceStore).stream()
|
||||
.filter(s -> region.equals(s.getRegion()) && Objects.equals(namespaceId, s.getNamespaceId())
|
||||
&& (dnsNamespace ? name.equalsIgnoreCase(s.getName()) : name.equals(s.getName())))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public List<Service> listServices(String region, String namespaceIdFilter) {
|
||||
List<Service> result = new ArrayList<>();
|
||||
for (Service s : scan(serviceStore)) {
|
||||
@@ -351,7 +366,7 @@ public class CloudMapService implements StoredResourceArns {
|
||||
}
|
||||
if (dnsRecordTtl(service, "SRV") >= 0 && service.getNamespaceId() != null) {
|
||||
Namespace namespace = requireNamespace(service.getNamespaceId());
|
||||
if ("DNS_PRIVATE".equals(namespace.getType()) || "DNS_PUBLIC".equals(namespace.getType())) {
|
||||
if (isDnsNamespace(namespace)) {
|
||||
try {
|
||||
DnsRecord.encodeName(instanceId + "." + service.getName() + "." + namespace.getName());
|
||||
} catch (IllegalArgumentException e) {
|
||||
@@ -745,7 +760,7 @@ public class CloudMapService implements StoredResourceArns {
|
||||
private List<Namespace> dnsNamespacesByLongestName() {
|
||||
return scan(namespaceStore).stream()
|
||||
.filter(n -> n.getName() != null && !n.getName().isBlank())
|
||||
.filter(n -> "DNS_PRIVATE".equals(n.getType()) || "DNS_PUBLIC".equals(n.getType()))
|
||||
.filter(CloudMapService::isDnsNamespace)
|
||||
.sorted(Comparator.comparingInt((Namespace n) -> n.getName().length()).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ import io.floci.aws.services.ecs.model.PortMapping;
|
||||
import io.floci.aws.services.ecs.model.ProtectedTask;
|
||||
import io.floci.aws.services.ecs.model.RuntimePlatform;
|
||||
import io.floci.aws.services.ecs.model.Secret;
|
||||
import io.floci.aws.services.ecs.model.ServiceConnectServiceResource;
|
||||
import io.floci.aws.services.ecs.model.ServiceDeployment;
|
||||
import io.floci.aws.services.ecs.model.ServiceEvent;
|
||||
import io.floci.aws.services.ecs.model.ServiceRevision;
|
||||
@@ -786,6 +787,14 @@ public class EcsResponseWriter {
|
||||
if (d.getServiceConnectConfiguration() != null) {
|
||||
n.set("serviceConnectConfiguration", objectMapper.valueToTree(d.getServiceConnectConfiguration()));
|
||||
}
|
||||
if (d.getServiceConnectResources() != null && !d.getServiceConnectResources().isEmpty()) {
|
||||
ArrayNode resources = n.putArray("serviceConnectResources");
|
||||
for (ServiceConnectServiceResource resource : d.getServiceConnectResources()) {
|
||||
resources.addObject()
|
||||
.put("discoveryName", resource.discoveryName())
|
||||
.put("discoveryArn", resource.discoveryArn());
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ import io.floci.aws.services.ecs.model.RegisterContainerInstanceRequest;
|
||||
import io.floci.aws.services.ecs.model.RegisterTaskDefinitionRequest;
|
||||
import io.floci.aws.services.ecs.model.RunTaskRequest;
|
||||
import io.floci.aws.services.ecs.model.RuntimePlatform;
|
||||
import io.floci.aws.services.ecs.model.ServiceConnectServiceResource;
|
||||
import io.floci.aws.services.ecs.model.ServiceDeployment;
|
||||
import io.floci.aws.services.ecs.model.ServiceEvent;
|
||||
import io.floci.aws.services.ecs.model.ServiceRevision;
|
||||
@@ -3133,7 +3134,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
svc.setAvailabilityZoneRebalancing(request.getAvailabilityZoneRebalancing() != null
|
||||
? request.getAvailabilityZoneRebalancing() : DEFAULT_AZ_REBALANCING_ON_CREATE);
|
||||
svc.setServiceConnectConfiguration(request.getServiceConnectConfiguration());
|
||||
svc.setServiceConnectNamespaceArn(serviceConnectNamespaceArn(svc, cluster, region));
|
||||
svc.setServiceConnectNamespaceArn(serviceConnectNamespaceArn(svc.getServiceConnectConfiguration(), cluster,
|
||||
region));
|
||||
svc.setDeploymentConfiguration(request.getDeploymentConfiguration());
|
||||
svc.setEnableExecuteCommand(request.isEnableExecuteCommand());
|
||||
svc.setEnableECSManagedTags(request.isEnableECSManagedTags());
|
||||
@@ -3154,8 +3156,21 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
svc.setTags(new LinkedHashMap<>(request.getTags()));
|
||||
}
|
||||
|
||||
// Last before the service is stored: a discovery name the namespace cannot take refuses
|
||||
// the request with nothing created.
|
||||
svc.setServiceConnectResources(syncServiceConnectResources(svc.getServiceArn(),
|
||||
svc.getServiceConnectConfiguration(), svc.getServiceConnectNamespaceArn(), List.of(), region,
|
||||
"ClientException"));
|
||||
if ("CODE_DEPLOY".equals(controller)) {
|
||||
createInitialTaskSet(svc, cluster, region);
|
||||
try {
|
||||
createInitialTaskSet(svc, cluster, region);
|
||||
} catch (RuntimeException e) {
|
||||
// The service isn't stored, so neither are the endpoints just made for it.
|
||||
if (discoveryRegistrar != null) {
|
||||
discoveryRegistrar.deleteServiceConnectServices(svc.getServiceConnectResources());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
services.put(key, svc);
|
||||
cluster.setActiveServicesCount(cluster.getActiveServicesCount() + 1);
|
||||
@@ -3258,14 +3273,25 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// launch fails without changing the service.
|
||||
TaskDefinition resolved = request.getTaskDefinition() == null ? null
|
||||
: resolveLaunchableTaskDefinition(request.getTaskDefinition(), region);
|
||||
if (request.getDesiredCount() != null && request.getDesiredCount() < 0) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"desiredCount cannot be a negative number.", 400);
|
||||
}
|
||||
// A Service Connect configuration's endpoints are taken last of the checks and before
|
||||
// anything is applied, as nothing after them can refuse the request: one whose discovery
|
||||
// names its namespace cannot take refuses it with the service unchanged.
|
||||
Map<String, Object> serviceConnectConfiguration = request.getServiceConnectConfiguration();
|
||||
String namespaceArn = serviceConnectConfiguration == null ? null
|
||||
: serviceConnectNamespaceArn(serviceConnectConfiguration, cluster, region);
|
||||
List<ServiceConnectServiceResource> serviceConnectResources = serviceConnectConfiguration == null
|
||||
? null
|
||||
: syncServiceConnectResources(svc.getServiceArn(), serviceConnectConfiguration, namespaceArn,
|
||||
serviceConnectResourcesOf(svc), region, "InvalidParameterException");
|
||||
// Settle the outgoing deployment against the service as it stands, before this request
|
||||
// changes its desired count or task definition: one whose tasks are up has finished,
|
||||
// whether or not anything read it. recordServiceDeployment stops it if it has not.
|
||||
currentServiceDeployment(svc);
|
||||
if (request.getDesiredCount() != null) {
|
||||
if (request.getDesiredCount() < 0) {
|
||||
throw new AwsException("InvalidParameterException", "desiredCount cannot be a negative number.", 400);
|
||||
}
|
||||
svc.setDesiredCount(request.getDesiredCount());
|
||||
}
|
||||
// The members whose change starts new tasks, as UpdateService documents them: the network
|
||||
@@ -3321,12 +3347,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// UpdateServiceRequest.serviceConnectConfiguration is documented as "This parameter
|
||||
// triggers a new service deployment", so a real change rolls the deployment the way a
|
||||
// task-definition change does. An omitted parameter is not a change and rolls nothing.
|
||||
Map<String, Object> serviceConnectConfiguration = request.getServiceConnectConfiguration();
|
||||
boolean serviceConnectChanged = serviceConnectConfiguration != null
|
||||
&& !serviceConnectConfiguration.equals(svc.getServiceConnectConfiguration());
|
||||
if (serviceConnectConfiguration != null) {
|
||||
svc.setServiceConnectConfiguration(serviceConnectConfiguration);
|
||||
svc.setServiceConnectNamespaceArn(serviceConnectNamespaceArn(svc, cluster, region));
|
||||
svc.setServiceConnectNamespaceArn(namespaceArn);
|
||||
svc.setServiceConnectResources(serviceConnectResources);
|
||||
}
|
||||
boolean taskDefChanged = false;
|
||||
String platformVersionBefore = resolvePlatformVersion(svc.getPlatformVersion());
|
||||
@@ -3527,6 +3553,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
svc.setStatus("INACTIVE");
|
||||
svc.setDesiredCount(0);
|
||||
// Under the service's monitor, which a rollback holds while it brings the endpoints back.
|
||||
synchronized (svc) {
|
||||
if (discoveryRegistrar != null) {
|
||||
discoveryRegistrar.deleteServiceConnectServices(serviceConnectResourcesOf(svc));
|
||||
}
|
||||
svc.setServiceConnectResources(new ArrayList<>());
|
||||
}
|
||||
cluster.setActiveServicesCount(Math.max(0, cluster.getActiveServicesCount() - 1));
|
||||
services.put(key, svc);
|
||||
persistCluster(region, cluster);
|
||||
@@ -3659,11 +3692,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the namespace the service's enabled Service Connect configuration joins, its own or its cluster's
|
||||
* default; null when it joins none.
|
||||
* The ARN of the namespace an enabled Service Connect configuration joins, its own or its cluster's default; null
|
||||
* when it joins none.
|
||||
*/
|
||||
private String serviceConnectNamespaceArn(EcsServiceModel svc, EcsCluster cluster, String region) {
|
||||
Map<String, Object> config = svc.getServiceConnectConfiguration();
|
||||
private String serviceConnectNamespaceArn(Map<String, Object> config, EcsCluster cluster, String region) {
|
||||
if (discoveryRegistrar == null || config == null || !Boolean.TRUE.equals(config.get("enabled"))) {
|
||||
return null;
|
||||
}
|
||||
@@ -3676,6 +3708,31 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
? null : discoveryRegistrar.namespaceArn(namespace.toString(), region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and deletes the Cloud Map services behind the Service Connect endpoints of the service
|
||||
* {@code serviceArn}, which {@code current} holds, to match {@code configuration} in the namespace it joined,
|
||||
* and returns them. A configuration ECS refuses is refused with {@code errorCode}: CreateService answers
|
||||
* {@code ClientException} and UpdateService {@code InvalidParameterException} (measured on AWS).
|
||||
*/
|
||||
private List<ServiceConnectServiceResource> syncServiceConnectResources(String serviceArn,
|
||||
Map<String, Object> configuration,
|
||||
String namespaceArn,
|
||||
List<ServiceConnectServiceResource> current,
|
||||
String region, String errorCode) {
|
||||
EcsServiceDiscoveryRegistrar.validateDiscoveryNames(configuration, errorCode);
|
||||
if (discoveryRegistrar == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return discoveryRegistrar.syncServiceConnectServices(current,
|
||||
EcsServiceDiscoveryRegistrar.discoveryNames(configuration, serviceArn), namespaceArn, region,
|
||||
serviceArn, errorCode);
|
||||
}
|
||||
|
||||
/** A service stored before the field existed reads back with none. */
|
||||
private static List<ServiceConnectServiceResource> serviceConnectResourcesOf(EcsServiceModel svc) {
|
||||
return svc.getServiceConnectResources() != null ? svc.getServiceConnectResources() : List.of();
|
||||
}
|
||||
|
||||
// ── Tags ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public synchronized void tagResource(String resourceArn, Map<String, String> tags) {
|
||||
@@ -4969,6 +5026,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
d.setPlatformFamily(svc.getPlatformFamily());
|
||||
d.setNetworkConfiguration(svc.getNetworkConfiguration());
|
||||
d.setServiceConnectConfiguration(svc.getServiceConnectConfiguration());
|
||||
d.setServiceConnectResources(serviceConnectResourcesOf(svc));
|
||||
// The deployment's own start time, not the service's: a task-definition change mints a
|
||||
// new deployment id, so reporting service creation here would contradict it. Older
|
||||
// persisted services predate the field and fall back to the service creation time.
|
||||
@@ -5385,8 +5443,23 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
svc.setServiceRegistries(revision.getServiceRegistries());
|
||||
svc.setNetworkConfiguration(revision.getNetworkConfiguration());
|
||||
svc.setServiceConnectConfiguration(revision.getServiceConnectConfiguration());
|
||||
svc.setServiceConnectNamespaceArn(serviceConnectNamespaceArn(svc, resolveClusterByArn(svc.getClusterArn()),
|
||||
serviceRegion(svc)));
|
||||
String region = serviceRegion(svc);
|
||||
svc.setServiceConnectNamespaceArn(serviceConnectNamespaceArn(svc.getServiceConnectConfiguration(),
|
||||
resolveClusterByArn(svc.getClusterArn()), region));
|
||||
if (!STATUS_INACTIVE.equals(svc.getStatus())) {
|
||||
try {
|
||||
svc.setServiceConnectResources(syncServiceConnectResources(svc.getServiceArn(),
|
||||
svc.getServiceConnectConfiguration(), svc.getServiceConnectNamespaceArn(),
|
||||
serviceConnectResourcesOf(svc), region, "InvalidParameterException"));
|
||||
} catch (AwsException e) {
|
||||
// A rollback cannot be refused: when a discovery name was taken meanwhile, the service
|
||||
// goes back without endpoints rather than keep the failed deployment's.
|
||||
LOG.warnv("Service {0} rolled back without its Service Connect endpoints: {1}",
|
||||
svc.getServiceArn(), e.getMessage());
|
||||
svc.setServiceConnectResources(syncServiceConnectResources(svc.getServiceArn(), null, null,
|
||||
serviceConnectResourcesOf(svc), region, "InvalidParameterException"));
|
||||
}
|
||||
}
|
||||
svc.setDeploymentId("ecs-svc/" + taskSetId);
|
||||
svc.setLastDeploymentAt(revision.getCreatedAt());
|
||||
svc.setLastCompletedDeploymentId(null);
|
||||
|
||||
@@ -2,12 +2,15 @@ package io.floci.aws.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.StripedLocks;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.cloudmap.CloudMapService;
|
||||
import io.floci.aws.services.cloudmap.model.Instance;
|
||||
import io.floci.aws.services.cloudmap.model.Namespace;
|
||||
import io.floci.aws.services.cloudmap.model.Service;
|
||||
import io.floci.aws.services.ecs.container.EcsContainerManager;
|
||||
import io.floci.aws.services.ecs.model.Container;
|
||||
import io.floci.aws.services.ecs.model.EcsRegisteredInstances;
|
||||
@@ -15,18 +18,23 @@ import io.floci.aws.services.ecs.model.EcsServiceModel;
|
||||
import io.floci.aws.services.ecs.model.EcsTask;
|
||||
import io.floci.aws.services.ecs.model.EcsTaskAddress;
|
||||
import io.floci.aws.services.ecs.model.NetworkBinding;
|
||||
import io.floci.aws.services.ecs.model.ServiceConnectServiceResource;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Bridges ECS services to Cloud Map: when an ECS service declares a {@code serviceRegistries}
|
||||
@@ -39,6 +47,9 @@ import java.util.Set;
|
||||
* <p>
|
||||
* {@code serviceRegistries} is stored as raw maps, since nothing else in ECS acts on it. The
|
||||
* three members read here are the ones AWS uses to place the instance.
|
||||
* <p>
|
||||
* It also creates and deletes the Cloud Map services behind a Service Connect configuration's
|
||||
* endpoints, in the namespace the ECS service joined.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EcsServiceDiscoveryRegistrar {
|
||||
@@ -49,6 +60,20 @@ public class EcsServiceDiscoveryRegistrar {
|
||||
private final EcsContainerManager containerManager;
|
||||
// taskArn → the instance registered for it, persisted so it can be released after a restart
|
||||
private final AccountAwareStorageBackend<EcsRegisteredInstances> ledger;
|
||||
// namespace ARN → held while a service's Service Connect discovery names are checked and taken
|
||||
private final StripedLocks serviceConnectNamespaceLocks = new StripedLocks(256);
|
||||
|
||||
/** The most characters a label of a Cloud Map service name holds. */
|
||||
private static final int MAX_LABEL = 63;
|
||||
/** The tag ECS puts on the Cloud Map services it creates for Service Connect (measured on AWS). */
|
||||
static final String ECS_MANAGED_TAG = "AmazonECSManaged";
|
||||
/** A discovery name ECS takes: up to 64 lowercase letters, numbers, underscores and hyphens, no hyphen first. */
|
||||
private static final Pattern DISCOVERY_NAME = Pattern.compile("[a-z0-9_][a-z0-9_-]{0,63}");
|
||||
/** ECS's answer for a discovery name outside {@link #DISCOVERY_NAME} (measured on AWS). */
|
||||
static final String INVALID_DISCOVERY_NAME = "The discovery name that you provided is invalid. This must be "
|
||||
+ "unique within the AWS Cloud Map namespace. Up to 64 characters are allowed. The characters can "
|
||||
+ "include lowercase letters, numbers, underscores (_), and hyphens (-). A hyphen can\u2019t be the "
|
||||
+ "first character.";
|
||||
|
||||
@Inject
|
||||
public EcsServiceDiscoveryRegistrar(CloudMapService cloudMapService, EcsContainerManager containerManager,
|
||||
@@ -216,14 +241,215 @@ public class EcsServiceDiscoveryRegistrar {
|
||||
|
||||
/** The ARN of the Region's Cloud Map namespace that a name or ARN gives; null when there is none. */
|
||||
public String namespaceArn(String nameOrArn, String region) {
|
||||
Namespace namespace = namespace(nameOrArn, region);
|
||||
return namespace == null ? null : namespace.getArn();
|
||||
}
|
||||
|
||||
/** The Region's Cloud Map namespace that a name or ARN gives; null when there is none. */
|
||||
private Namespace namespace(String nameOrArn, String region) {
|
||||
for (Namespace namespace : cloudMapService.listNamespaces(region)) {
|
||||
if (nameOrArn.equals(namespace.getName()) || nameOrArn.equals(namespace.getArn())) {
|
||||
return namespace.getArn();
|
||||
return namespace;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The names of the Cloud Map services a Service Connect configuration gives the service {@code serviceArn},
|
||||
* in its order: each {@code services[]} entry's {@code discoveryName}, or its {@code portName} when it has
|
||||
* none, and for a client configuration, with no entries, the one Cloud Map service ECS creates for the
|
||||
* client ({@link #clientDiscoveryName}). None for a configuration that leaves Service Connect off, and none for
|
||||
* an entry without a name.
|
||||
*/
|
||||
public static List<String> discoveryNames(Map<String, Object> configuration, String serviceArn) {
|
||||
if (configuration == null || !Boolean.TRUE.equals(configuration.get("enabled"))) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> names = new ArrayList<>();
|
||||
boolean client = !(configuration.get("services") instanceof List<?> listed) || listed.isEmpty();
|
||||
if (configuration.get("services") instanceof List<?> services) {
|
||||
for (Object entry : services) {
|
||||
if (entry instanceof Map<?, ?> service) {
|
||||
Object name = service.get("discoveryName") instanceof String discoveryName
|
||||
&& !discoveryName.isBlank() ? discoveryName : service.get("portName");
|
||||
if (name instanceof String named && !named.isBlank()) {
|
||||
names.add(named);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return client && serviceArn != null ? List.of(clientDiscoveryName(serviceArn)) : names;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cloud Map service ECS creates for a Service Connect client, which offers no endpoint:
|
||||
* {@code aws-ecs-sc.client.<UUID>.<service name>}, the service name cut to its first 63 characters, a Cloud
|
||||
* Map label's most, as measured on AWS. How AWS derives the UUID isn't documented (it is none of the
|
||||
* name-based UUIDs of the service's ARN or names); Floci derives one from the service's ARN, so the service
|
||||
* keeps it across updates, as on AWS.
|
||||
*/
|
||||
static String clientDiscoveryName(String serviceArn) {
|
||||
String serviceName = nameFromArn(serviceArn);
|
||||
return "aws-ecs-sc.client." + UUID.nameUUIDFromBytes(serviceArn.getBytes(StandardCharsets.UTF_8)) + "."
|
||||
+ serviceName.substring(0, Math.min(serviceName.length(), MAX_LABEL));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses, with {@code errorCode}, a Service Connect configuration ECS refuses before it looks in the
|
||||
* namespace, with ECS's messages (measured on AWS): a {@code discoveryName} outside the naming rule, or a
|
||||
* name its entries give more than once. CreateService answers {@code ClientException} and UpdateService
|
||||
* {@code InvalidParameterException}.
|
||||
*/
|
||||
public static void validateDiscoveryNames(Map<String, Object> configuration, String errorCode) {
|
||||
if (configuration == null || !Boolean.TRUE.equals(configuration.get("enabled"))
|
||||
|| !(configuration.get("services") instanceof List<?> services)) {
|
||||
return;
|
||||
}
|
||||
for (Object entry : services) {
|
||||
if (entry instanceof Map<?, ?> service && service.get("discoveryName") instanceof String name
|
||||
&& !DISCOVERY_NAME.matcher(name).matches()) {
|
||||
throw new AwsException(errorCode, INVALID_DISCOVERY_NAME, 400);
|
||||
}
|
||||
}
|
||||
refuseRepeatedNames(discoveryNames(configuration, null), false, errorCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses names a configuration gives more than once, with ECS's message (measured on AWS); compared without
|
||||
* case when {@code ignoreCase}, as a DNS namespace's Cloud Map compares them.
|
||||
*/
|
||||
private static void refuseRepeatedNames(List<String> names, boolean ignoreCase, String errorCode) {
|
||||
Set<String> seen = new HashSet<>();
|
||||
Set<String> twice = new LinkedHashSet<>();
|
||||
for (String name : names) {
|
||||
if (!seen.add(ignoreCase ? name.toLowerCase(Locale.ROOT) : name)) {
|
||||
twice.add(name);
|
||||
}
|
||||
}
|
||||
if (!twice.isEmpty()) {
|
||||
throw new AwsException(errorCode,
|
||||
"The following discoveryNames are defined more than once: " + List.copyOf(twice) + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses, with {@code errorCode}, discovery names {@code namespace} cannot take for a service holding
|
||||
* {@code current}: one a Cloud Map service in the namespace already has that is not among {@code current},
|
||||
* since "all discovery names must be unique within a namespace". Names compare as Cloud Map compares them,
|
||||
* without case in a DNS namespace.
|
||||
*/
|
||||
private void checkDiscoveryNames(List<ServiceConnectServiceResource> current, List<String> discoveryNames,
|
||||
Namespace namespace, String region, String errorCode) {
|
||||
Set<String> own = new HashSet<>();
|
||||
current.forEach(resource -> own.add(resource.discoveryArn()));
|
||||
for (String name : discoveryNames) {
|
||||
cloudMapService.findServiceByName(name, namespace.getId(), region)
|
||||
.filter(existing -> !own.contains(existing.getArn()))
|
||||
.ifPresent(existing -> {
|
||||
throw nameTaken(existing, namespace, errorCode);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ECS's answer for a discovery name the namespace already holds (measured on AWS): its own, naming the
|
||||
* namespace, when another ECS service's endpoint holds it, and otherwise Cloud Map's refusal of its
|
||||
* CreateService call, with the details the SDK adds to it.
|
||||
*/
|
||||
private static AwsException nameTaken(Service existing, Namespace namespace, String errorCode) {
|
||||
boolean ecsManaged = existing.getTags() != null && "true".equals(existing.getTags().get(ECS_MANAGED_TAG));
|
||||
return new AwsException(errorCode, ecsManaged ? "SC service is already used by " + namespace.getArn()
|
||||
: cloudMapServiceExists(), 400);
|
||||
}
|
||||
|
||||
private static String cloudMapServiceExists() {
|
||||
return "Service already exists. (Service: ServiceDiscovery, Status Code: 400, Request ID: "
|
||||
+ UUID.randomUUID() + ") (SDK Attempt Count: 1)";
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the Cloud Map services behind a service's Service Connect endpoints in line with
|
||||
* {@code discoveryNames}: a name {@code current} already holds keeps its Cloud Map service, a new
|
||||
* one gets a Cloud Map service created in the namespace, and one {@code current} holds that is no
|
||||
* longer named has its Cloud Map service deleted. The names are checked first, under a lock for
|
||||
* the namespace, so a refusal creates nothing and two ECS services cannot take one name at once; a
|
||||
* creation that still fails, as when a Cloud Map CreateService took the name in between, deletes
|
||||
* what this call created and leaves {@code current} as it was. A refusal carries {@code errorCode}. The
|
||||
* Cloud Map services are of type HTTP, with no DNS records: Service Connect "doesn't use or create DNS
|
||||
* hosted zones in Amazon Route 53". Each is described "Managed by" the ECS service {@code serviceArn} and
|
||||
* tagged {@code AmazonECSManaged}, as ECS creates them (measured on AWS).
|
||||
*
|
||||
* @return the resources for {@code discoveryNames}, in their order; none without a namespace
|
||||
*/
|
||||
public List<ServiceConnectServiceResource> syncServiceConnectServices(
|
||||
List<ServiceConnectServiceResource> current, List<String> discoveryNames, String namespaceArn,
|
||||
String region, String serviceArn, String errorCode) {
|
||||
Namespace namespace = namespaceArn == null ? null : namespace(namespaceArn, region);
|
||||
List<ServiceConnectServiceResource> resources = new ArrayList<>();
|
||||
if (namespace != null && !discoveryNames.isEmpty()) {
|
||||
synchronized (serviceConnectNamespaceLocks.lockFor(namespace.getArn())) {
|
||||
// A portName, which the naming rule doesn't hold to lowercase, can repeat a name in a case of its own.
|
||||
refuseRepeatedNames(discoveryNames, CloudMapService.isDnsNamespace(namespace), errorCode);
|
||||
checkDiscoveryNames(current, discoveryNames, namespace, region, errorCode);
|
||||
Set<String> own = new HashSet<>();
|
||||
current.forEach(resource -> own.add(resource.discoveryArn()));
|
||||
List<ServiceConnectServiceResource> created = new ArrayList<>();
|
||||
for (String name : discoveryNames) {
|
||||
Service existing = cloudMapService.findServiceByName(name, namespace.getId(), region)
|
||||
.orElse(null);
|
||||
if (existing != null && !own.contains(existing.getArn())) {
|
||||
// The check let through only a name that was free or this service's own: a Cloud Map
|
||||
// CreateService took it since, and that service isn't ECS's to take over or delete.
|
||||
deleteServiceConnectServices(created);
|
||||
throw nameTaken(existing, namespace, errorCode);
|
||||
}
|
||||
if (existing == null) {
|
||||
try {
|
||||
existing = cloudMapService.createService(name, namespace.getId(), null,
|
||||
"Managed by " + serviceArn, null, null, null, null,
|
||||
Map.of(ECS_MANAGED_TAG, "true"), region);
|
||||
} catch (AwsException e) {
|
||||
deleteServiceConnectServices(created);
|
||||
throw "ServiceAlreadyExists".equals(e.getErrorCode())
|
||||
? new AwsException(errorCode, cloudMapServiceExists(), 400) : e;
|
||||
}
|
||||
created.add(new ServiceConnectServiceResource(name, existing.getArn()));
|
||||
}
|
||||
resources.add(new ServiceConnectServiceResource(name, existing.getArn()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Set<String> kept = new HashSet<>();
|
||||
resources.forEach(resource -> kept.add(resource.discoveryArn()));
|
||||
deleteServiceConnectServices(current.stream()
|
||||
.filter(resource -> !kept.contains(resource.discoveryArn())).toList());
|
||||
return resources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the Cloud Map services behind Service Connect endpoints a service no longer offers.
|
||||
* One already gone is skipped; one Cloud Map refuses to delete, because instances were registered
|
||||
* in it through the Cloud Map API, is left in place, and its name stays taken.
|
||||
*/
|
||||
public void deleteServiceConnectServices(List<ServiceConnectServiceResource> resources) {
|
||||
for (ServiceConnectServiceResource resource : resources) {
|
||||
String id = serviceIdOf(resource.discoveryArn());
|
||||
if (id == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
cloudMapService.deleteService(id);
|
||||
} catch (AwsException e) {
|
||||
if ("ServiceNotFound".equals(e.getErrorCode())) {
|
||||
continue;
|
||||
}
|
||||
LOG.warnv("Could not delete Cloud Map service {0} of Service Connect endpoint {1}: {2}",
|
||||
id, resource.discoveryName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasRegistries(EcsServiceModel svc) {
|
||||
return !registries(svc).isEmpty();
|
||||
}
|
||||
@@ -370,16 +596,21 @@ public class EcsServiceDiscoveryRegistrar {
|
||||
if (registryArn == null || registryArn.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String serviceId = AwsArnUtils.resourceIfArnFor(registryArn, "servicediscovery")
|
||||
String serviceId = serviceIdOf(registryArn);
|
||||
if (serviceId == null) {
|
||||
LOG.warnv("Ignoring an ECS service registry whose registryArn names no Cloud Map service: {0}",
|
||||
registryArn);
|
||||
}
|
||||
return serviceId;
|
||||
}
|
||||
|
||||
/** The service id in a Cloud Map service ARN, {@code ...:service/srv-xxxxxxxx}; null for any other value. */
|
||||
private static String serviceIdOf(String serviceArn) {
|
||||
String serviceId = AwsArnUtils.resourceIfArnFor(serviceArn, "servicediscovery")
|
||||
.filter(resource -> resource.startsWith("service/"))
|
||||
.map(resource -> resource.substring("service/".length()))
|
||||
.orElse("");
|
||||
if (serviceId.isEmpty() || serviceId.contains("/")) {
|
||||
LOG.warnv("Ignoring an ECS service registry whose registryArn names no Cloud Map service: {0}",
|
||||
registryArn);
|
||||
return null;
|
||||
}
|
||||
return serviceId;
|
||||
return serviceId.isEmpty() || serviceId.contains("/") ? null : serviceId;
|
||||
}
|
||||
|
||||
/** ECS registers a task under its task id, so a replacement task supersedes its predecessor. */
|
||||
|
||||
@@ -37,6 +37,8 @@ public class Deployment {
|
||||
* so this is the single place a generated client can read it back from.
|
||||
*/
|
||||
private Map<String, Object> serviceConnectConfiguration;
|
||||
/** The Cloud Map services behind the configuration's endpoints. */
|
||||
private List<ServiceConnectServiceResource> serviceConnectResources;
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
@@ -78,4 +80,8 @@ public class Deployment {
|
||||
public void setServiceConnectConfiguration(Map<String, Object> serviceConnectConfiguration) {
|
||||
this.serviceConnectConfiguration = serviceConnectConfiguration;
|
||||
}
|
||||
public List<ServiceConnectServiceResource> getServiceConnectResources() { return serviceConnectResources; }
|
||||
public void setServiceConnectResources(List<ServiceConnectServiceResource> serviceConnectResources) {
|
||||
this.serviceConnectResources = serviceConnectResources;
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@ public class EcsServiceModel {
|
||||
* resolved when the configuration was set so a later change to the cluster default does not move the service.
|
||||
*/
|
||||
private String serviceConnectNamespaceArn;
|
||||
/** The Cloud Map services ECS created for the configuration's endpoints in that namespace, in its order. */
|
||||
private List<ServiceConnectServiceResource> serviceConnectResources = new ArrayList<>();
|
||||
private String platformVersion;
|
||||
private String platformFamily;
|
||||
private List<CapacityProviderStrategyItem> capacityProviderStrategy;
|
||||
@@ -158,6 +160,11 @@ public class EcsServiceModel {
|
||||
this.serviceConnectConfiguration = serviceConnectConfiguration;
|
||||
}
|
||||
|
||||
public List<ServiceConnectServiceResource> getServiceConnectResources() { return serviceConnectResources; }
|
||||
public void setServiceConnectResources(List<ServiceConnectServiceResource> serviceConnectResources) {
|
||||
this.serviceConnectResources = serviceConnectResources;
|
||||
}
|
||||
|
||||
public String getPlatformVersion() { return platformVersion; }
|
||||
public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; }
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package io.floci.aws.services.ecs.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* One endpoint of a service's Service Connect configuration: the Cloud Map service ECS created
|
||||
* for it in the namespace, named {@code discoveryName}, at {@code discoveryArn}. Reported on the
|
||||
* service's deployment as AWS's {@code ServiceConnectServiceResource}.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record ServiceConnectServiceResource(String discoveryName, String discoveryArn) {
|
||||
}
|
||||
Reference in new issue
Block a user