diff --git a/docs/services/ecs.md b/docs/services/ecs.md index 49b30e58fe..9261e14e99 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -522,6 +522,34 @@ a `nextToken`. A service joins the namespace its Service Connect configuration n cluster's default when it names none, at the time the configuration is set: a later change to the cluster default does not move it. +Each `services[]` entry of a Service Connect configuration is an endpoint, and Floci creates a +Cloud Map service for it in the namespace the service joined, named its `discoveryName` or, +without one, its `portName`, as AWS does. A client configuration, with no entries, gets one Cloud +Map service for the client, `aws-ecs-sc.client..`, as on AWS; Floci derives the +UUID from the service's ARN, since how AWS derives its own isn't documented. Each Cloud Map service +is of type `HTTP`, with no DNS records, since Service Connect does not use Route 53, is described as +`Managed by ` and is tagged `AmazonECSManaged=true`, as ECS creates them. The +deployments of `DescribeServices` report them as `serviceConnectResources` (`discoveryName`, and the +Cloud Map service's ARN as `discoveryArn`). An `UpdateService` keeps the Cloud Map service of an +endpoint it keeps, creates the new ones and deletes the ones it drops, and `DeleteService` deletes +them all, so the namespace can be deleted afterwards; AWS deletes them within a minute or so, Floci +in the call. A deployment rollback brings them in line with the configuration it restores, or, when +another service took one of its discovery names meanwhile, leaves the service without endpoints. + +A discovery name is up to 64 lowercase letters, numbers, underscores and hyphens, not beginning with +a hyphen, and unique in its namespace, compared as Cloud Map compares names (without case in a DNS +namespace). `CreateService` refuses a configuration that breaks this with `ClientException`, and +`UpdateService` with `InvalidParameterException`, each with ECS's message, and the request then +changes nothing: a name outside the rule; a name the configuration gives twice ("The following +discoveryNames are defined more than once: [...]"); a name another ECS service's endpoint holds ("SC +service is already used by" the namespace's ARN); or one a Cloud Map service created outside ECS +holds, refused with Cloud Map's "Service already exists.", which ECS passes on. The Cloud Map +services are created when `CreateService` or `UpdateService` sets the configuration, in the +namespace it joins then, so a configuration whose namespace Cloud Map does not hold at that point +gets none. Floci registers +no task in them and does not route the `clientAliases`: a task reaches another service's tasks +through `serviceRegistries` and DNS, not through Service Connect's names. + With persistent storage, services survive a restart but their tasks do not: task state is held in memory. The service scheduler starts at boot, so within a few seconds of startup every persisted service is brought back to its `desiredCount`, re-registering load balancer targets diff --git a/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java b/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java index 2091aba76a..6f9d5d095f 100644 --- a/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java +++ b/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java @@ -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 listNamespaces(String region) { List 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 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 listServices(String region, String namespaceIdFilter) { List 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 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(); } diff --git a/src/main/java/io/floci/aws/services/ecs/EcsResponseWriter.java b/src/main/java/io/floci/aws/services/ecs/EcsResponseWriter.java index 59469651f9..2a9006fc08 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsResponseWriter.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsResponseWriter.java @@ -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; } diff --git a/src/main/java/io/floci/aws/services/ecs/EcsService.java b/src/main/java/io/floci/aws/services/ecs/EcsService.java index d042dec285..93fcfad507 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsService.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsService.java @@ -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 serviceConnectConfiguration = request.getServiceConnectConfiguration(); + String namespaceArn = serviceConnectConfiguration == null ? null + : serviceConnectNamespaceArn(serviceConnectConfiguration, cluster, region); + List 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 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 config = svc.getServiceConnectConfiguration(); + private String serviceConnectNamespaceArn(Map 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 syncServiceConnectResources(String serviceArn, + Map configuration, + String namespaceArn, + List 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 serviceConnectResourcesOf(EcsServiceModel svc) { + return svc.getServiceConnectResources() != null ? svc.getServiceConnectResources() : List.of(); + } + // ── Tags ────────────────────────────────────────────────────────────────── public synchronized void tagResource(String resourceArn, Map 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); diff --git a/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java b/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java index 78df51636b..30d7a83149 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java @@ -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; *

* {@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. + *

+ * 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 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 discoveryNames(Map configuration, String serviceArn) { + if (configuration == null || !Boolean.TRUE.equals(configuration.get("enabled"))) { + return List.of(); + } + List 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..}, 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 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 names, boolean ignoreCase, String errorCode) { + Set seen = new HashSet<>(); + Set 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 current, List discoveryNames, + Namespace namespace, String region, String errorCode) { + Set 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 syncServiceConnectServices( + List current, List discoveryNames, String namespaceArn, + String region, String serviceArn, String errorCode) { + Namespace namespace = namespaceArn == null ? null : namespace(namespaceArn, region); + List 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 own = new HashSet<>(); + current.forEach(resource -> own.add(resource.discoveryArn())); + List 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 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 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. */ diff --git a/src/main/java/io/floci/aws/services/ecs/model/Deployment.java b/src/main/java/io/floci/aws/services/ecs/model/Deployment.java index 7f5a0c87e7..94353ded6c 100644 --- a/src/main/java/io/floci/aws/services/ecs/model/Deployment.java +++ b/src/main/java/io/floci/aws/services/ecs/model/Deployment.java @@ -37,6 +37,8 @@ public class Deployment { * so this is the single place a generated client can read it back from. */ private Map serviceConnectConfiguration; + /** The Cloud Map services behind the configuration's endpoints. */ + private List 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 serviceConnectConfiguration) { this.serviceConnectConfiguration = serviceConnectConfiguration; } + public List getServiceConnectResources() { return serviceConnectResources; } + public void setServiceConnectResources(List serviceConnectResources) { + this.serviceConnectResources = serviceConnectResources; + } } diff --git a/src/main/java/io/floci/aws/services/ecs/model/EcsServiceModel.java b/src/main/java/io/floci/aws/services/ecs/model/EcsServiceModel.java index 0cbf816935..225b0f551a 100644 --- a/src/main/java/io/floci/aws/services/ecs/model/EcsServiceModel.java +++ b/src/main/java/io/floci/aws/services/ecs/model/EcsServiceModel.java @@ -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 serviceConnectResources = new ArrayList<>(); private String platformVersion; private String platformFamily; private List capacityProviderStrategy; @@ -158,6 +160,11 @@ public class EcsServiceModel { this.serviceConnectConfiguration = serviceConnectConfiguration; } + public List getServiceConnectResources() { return serviceConnectResources; } + public void setServiceConnectResources(List serviceConnectResources) { + this.serviceConnectResources = serviceConnectResources; + } + public String getPlatformVersion() { return platformVersion; } public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } diff --git a/src/main/java/io/floci/aws/services/ecs/model/ServiceConnectServiceResource.java b/src/main/java/io/floci/aws/services/ecs/model/ServiceConnectServiceResource.java new file mode 100644 index 0000000000..cb9f266806 --- /dev/null +++ b/src/main/java/io/floci/aws/services/ecs/model/ServiceConnectServiceResource.java @@ -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) { +} diff --git a/src/test/java/io/floci/aws/services/ecs/EcsServiceConnectRegistrationIntegrationTest.java b/src/test/java/io/floci/aws/services/ecs/EcsServiceConnectRegistrationIntegrationTest.java new file mode 100644 index 0000000000..a1cd7f370b --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecs/EcsServiceConnectRegistrationIntegrationTest.java @@ -0,0 +1,363 @@ +package io.floci.aws.services.ecs; + +import io.floci.aws.testing.AwsSdkErrors; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.TestAccounts; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ecs.EcsClient; +import software.amazon.awssdk.services.ecs.model.ContainerDefinition; +import software.amazon.awssdk.services.ecs.model.Deployment; +import software.amazon.awssdk.services.ecs.model.PortMapping; +import software.amazon.awssdk.services.ecs.model.Service; +import software.amazon.awssdk.services.ecs.model.ServiceConnectConfiguration; +import software.amazon.awssdk.services.ecs.model.ServiceConnectService; +import software.amazon.awssdk.services.ecs.model.ServiceConnectServiceResource; +import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient; +import software.amazon.awssdk.services.servicediscovery.model.FilterCondition; +import software.amazon.awssdk.services.servicediscovery.model.NamespaceSummary; +import software.amazon.awssdk.services.servicediscovery.model.ServiceFilterName; +import software.amazon.awssdk.services.servicediscovery.model.ServiceSummary; +import software.amazon.awssdk.services.servicediscovery.model.Tag; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A Service Connect configuration's {@code services[]} entries are endpoints, and ECS creates a + * Cloud Map service for each in the service's namespace, named {@code discoveryName} or, without + * one, {@code portName}, and reports them as the deployment's {@code serviceConnectResources} + * (the ECS Developer Guide's "Configuring Service Connect with the AWS CLI"). A client + * configuration, with no entries, gets one Cloud Map service for the client. Each is described as managed by + * the ECS service and tagged {@code AmazonECSManaged}. Discovery names follow a naming rule and are unique in a + * namespace; CreateService refuses one with {@code ClientException} and UpdateService with + * {@code InvalidParameterException}, with ECS's messages. All of it as measured on AWS (us-east-1, 2026-11-19). + */ +@QuarkusTest +class EcsServiceConnectRegistrationIntegrationTest { + + private static final Region REGION = Region.US_EAST_1; + private static final String CLUSTER = "shop-cluster"; + private static final String FAMILY = "shop"; + /** + * AWS's text as measured, kept apart from the registrar's copy on purpose: the test checks Floci's answer + * against AWS's, which checking it against Floci's own constant would not. + */ + private static final String INVALID_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."; + /** Cloud Map's refusal of ECS's CreateService call, as ECS passes it on, its request id varying. */ + private static final String CLOUD_MAP_SERVICE_EXISTS = "Service already exists\\. \\(Service: ServiceDiscovery, " + + "Status Code: 400, Request ID: [0-9a-f-]{36}\\) \\(SDK Attempt Count: 1\\)"; + + /** Every test works in an account of its own, so a namespace holds only what the test created. */ + private final String account = TestAccounts.randomId(); + private final Deque cleanups = new ArrayDeque<>(); + private EcsClient ecs; + private ServiceDiscoveryClient cloudMap; + private NamespaceSummary namespace; + + @BeforeEach + void setUp() { + ecs = AwsTestClients.create(EcsClient.builder(), account, REGION); + cloudMap = AwsTestClients.create(ServiceDiscoveryClient.builder(), account, REGION); + cloudMap.createHttpNamespace(r -> r.name("shop")); + namespace = cloudMap.listNamespaces(r -> { }).namespaces().getFirst(); + cleanups.push(() -> cloudMap.deleteNamespace(r -> r.id(namespace.id()))); + ecs.createCluster(r -> r.clusterName(CLUSTER)); + cleanups.push(() -> ecs.deleteCluster(r -> r.cluster(CLUSTER))); + String taskDefinition = ecs.registerTaskDefinition(r -> r.family(FAMILY).containerDefinitions( + ContainerDefinition.builder().name("app").image("nginx").memory(128).portMappings( + PortMapping.builder().name("http").containerPort(8080).build(), + PortMapping.builder().name("admin").containerPort(9000).build()).build())) + .taskDefinition().taskDefinitionArn(); + cleanups.push(() -> ecs.deregisterTaskDefinition(r -> r.taskDefinition(taskDefinition))); + } + + @AfterEach + void cleanUp() { + try { + while (!cleanups.isEmpty()) { + try { + cleanups.pop().run(); + } catch (AwsServiceException e) { + // What a test deleted itself is gone already. + if (e.statusCode() != 404 && !e.awsErrorDetails().errorCode().contains("NotFound")) { + throw e; + } + } + } + } finally { + ecs.close(); + cloudMap.close(); + } + } + + @Test + void createServiceCreatesACloudMapServicePerEndpoint() { + Service created = createService("web-svc", endpoint("http", "web", 80), endpoint("admin", null, 9000)); + + Map inNamespace = cloudMapServices(); + assertEquals(List.of("admin", "web"), List.copyOf(inNamespace.keySet())); + inNamespace.values().forEach(service -> assertEquals("HTTP", service.typeAsString())); + List expected = List.of( + resource("web", inNamespace.get("web").arn()), + resource("admin", inNamespace.get("admin").arn())); + assertEquals(expected, created.deployments().getFirst().serviceConnectResources()); + assertEquals(expected, deployment("web-svc").serviceConnectResources()); + for (ServiceSummary service : inNamespace.values()) { + assertManagedBy(created.serviceArn(), service); + } + } + + /** A configuration that names no namespace joins its cluster's default, which then holds its endpoints. */ + @Test + void aConfigurationNamingNoNamespaceCreatesItsEndpointsInTheClusterDefault() { + ecs.createCluster(r -> r.clusterName("default-cluster") + .serviceConnectDefaults(defaults -> defaults.namespace(namespace.name()))); + cleanups.push(() -> ecs.deleteCluster(r -> r.cluster("default-cluster"))); + + Service created = ecs.createService(r -> r.cluster("default-cluster").serviceName("web-svc") + .taskDefinition(FAMILY).desiredCount(0).serviceConnectConfiguration(ServiceConnectConfiguration + .builder().enabled(true).services(endpoint("http", "web", 80)).build())).service(); + cleanups.push(() -> ecs.deleteService(r -> r.cluster("default-cluster").service("web-svc").force(true))); + + assertEquals(List.of("web"), List.copyOf(cloudMapServices().keySet())); + assertEquals(List.of(resource("web", cloudMapServices().get("web").arn())), + created.deployments().getFirst().serviceConnectResources()); + } + + @Test + void aNamespaceNamedByArnHoldsTheEndpoints() { + Service created = ecs.createService(r -> r.cluster(CLUSTER).serviceName("web-svc").taskDefinition(FAMILY) + .desiredCount(0).serviceConnectConfiguration(ServiceConnectConfiguration.builder().enabled(true) + .namespace(namespace.arn()).services(endpoint("http", "web", 80)).build())).service(); + cleanups.push(() -> ecs.deleteService(r -> r.cluster(CLUSTER).service("web-svc").force(true))); + + assertEquals(List.of("web"), List.copyOf(cloudMapServices().keySet())); + assertEquals(List.of(resource("web", cloudMapServices().get("web").arn())), + created.deployments().getFirst().serviceConnectResources()); + } + + /** A client, which offers no endpoint, gets one Cloud Map service, aws-ecs-sc.client... */ + @Test + void aClientServiceGetsOneCloudMapServiceForTheClient() { + Service created = createService("client-svc"); + + Map inNamespace = cloudMapServices(); + assertEquals(1, inNamespace.size()); + String name = inNamespace.keySet().iterator().next(); + assertTrue(name.matches("aws-ecs-sc\\.client\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + + "\\.client-svc"), name); + assertEquals(List.of(resource(name, inNamespace.get(name).arn())), + created.deployments().getFirst().serviceConnectResources()); + assertEquals("HTTP", inNamespace.get(name).typeAsString()); + assertManagedBy(created.serviceArn(), inNamespace.get(name)); + + update("client-svc", connect(endpoint("http", "web", 80))); + assertEquals(List.of("web"), List.copyOf(cloudMapServices().keySet()), "an endpoint replaces the client's"); + + // A Cloud Map label holds 63 characters, and AWS keeps the first 63 of a longer service name. + String longName = "c" + "x".repeat(69); + Service longClient = createService(longName); + String longClientName = longClient.deployments().getFirst().serviceConnectResources().getFirst() + .discoveryName(); + assertEquals(longName.substring(0, 63), longClientName.substring(longClientName.lastIndexOf('.') + 1)); + } + + @Test + void updateServiceCreatesTheNewEndpointsAndDeletesTheDroppedOnes() { + createService("web-svc", endpoint("http", "web", 80)); + String web = cloudMapServices().get("web").arn(); + + update("web-svc", connect(endpoint("http", "web", 80), endpoint("admin", null, 9000))); + String admin = cloudMapServices().get("admin").arn(); + assertEquals(List.of(resource("web", web), resource("admin", admin)), + deployment("web-svc").serviceConnectResources(), "the kept endpoint keeps its Cloud Map service"); + + update("web-svc", connect(endpoint("admin", null, 9000))); + assertEquals(List.of("admin"), List.copyOf(cloudMapServices().keySet())); + assertEquals(List.of(resource("admin", admin)), deployment("web-svc").serviceConnectResources()); + + update("web-svc", ServiceConnectConfiguration.builder().enabled(false).build()); + assertEquals(Map.of(), cloudMapServices()); + assertFalse(deployment("web-svc").hasServiceConnectResources()); + } + + @Test + void deleteServiceDeletesItsCloudMapServicesSoTheNamespaceCanBeDeleted() { + createService("web-svc", endpoint("http", "web", 80)); + assertEquals(List.of("web"), List.copyOf(cloudMapServices().keySet())); + + ecs.deleteService(r -> r.cluster(CLUSTER).service("web-svc").force(true)); + + assertEquals(Map.of(), cloudMapServices()); + cloudMap.deleteNamespace(r -> r.id(namespace.id())); + assertEquals(List.of(), cloudMap.listNamespaces(r -> { }).namespaces()); + } + + /** + * A discovery name another ECS service's endpoint holds is refused naming the namespace, one a Cloud Map + * service made outside ECS holds with Cloud Map's refusal, and one a configuration gives twice by naming + * it. CreateService answers {@code ClientException} and creates nothing; UpdateService answers + * {@code InvalidParameterException}, with the same messages, and changes nothing. + */ + @Test + void aDiscoveryNameTheNamespaceAlreadyHasIsRefused() { + String byHand = cloudMap.createService(r -> r.name("web").namespaceId(namespace.id())).service().arn(); + cleanups.push(() -> cloudMap.deleteService(r -> r.id(byHand.substring(byHand.lastIndexOf('/') + 1)))); + + assertTrue(AwsSdkErrors.assertAwsError("ClientException", 400, () -> ecs.createService(r -> r + .cluster(CLUSTER).serviceName("web-svc").taskDefinition(FAMILY).desiredCount(0) + .serviceConnectConfiguration(connect(endpoint("http", "web", 80))))).awsErrorDetails() + .errorMessage().matches(CLOUD_MAP_SERVICE_EXISTS)); + assertEquals(List.of(), ecs.listServices(r -> r.cluster(CLUSTER)).serviceArns(), "nothing was created"); + + createService("admin-svc", endpoint("admin", null, 9000)); + createService("api-svc", endpoint("http", "api", 80)); + assertRefused("ClientException", "SC service is already used by " + namespace.arn(), () -> ecs + .createService(r -> r.cluster(CLUSTER).serviceName("other-svc").taskDefinition(FAMILY) + .desiredCount(0).serviceConnectConfiguration(connect(endpoint("admin", null, 9001))))); + assertRefused("ClientException", "The following discoveryNames are defined more than once: [dup].", + () -> ecs.createService(r -> r.cluster(CLUSTER).serviceName("twice-svc").taskDefinition(FAMILY) + .desiredCount(0).serviceConnectConfiguration(connect(endpoint("http", "dup", 80), + endpoint("admin", "dup", 81))))); + + assertRefused("InvalidParameterException", "SC service is already used by " + namespace.arn(), () -> ecs + .updateService(r -> r.cluster(CLUSTER).service("admin-svc").desiredCount(3) + .serviceConnectConfiguration(connect(endpoint("http", "api", 80))))); + assertTrue(AwsSdkErrors.assertAwsError("InvalidParameterException", 400, () -> ecs.updateService(r -> r + .cluster(CLUSTER).service("admin-svc").desiredCount(3) + .serviceConnectConfiguration(connect(endpoint("http", "web", 80))))).awsErrorDetails() + .errorMessage().matches(CLOUD_MAP_SERVICE_EXISTS)); + assertRefused("InvalidParameterException", "The following discoveryNames are defined more than once: [dup].", + () -> ecs.updateService(r -> r.cluster(CLUSTER).service("admin-svc").serviceConnectConfiguration( + connect(endpoint("http", "dup", 80), endpoint("admin", "dup", 81))))); + Service unchanged = ecs.describeServices(r -> r.cluster(CLUSTER).services("admin-svc")).services().getFirst(); + assertEquals(0, unchanged.desiredCount(), "a refused update changes nothing"); + assertEquals(List.of(resource("admin", cloudMapServices().get("admin").arn())), + unchanged.deployments().getFirst().serviceConnectResources()); + assertEquals(List.of("admin", "api", "web"), List.copyOf(cloudMapServices().keySet())); + } + + /** + * A discovery name is up to 64 lowercase letters, numbers, underscores and hyphens, not beginning with a + * hyphen; any other is refused before the namespace is looked at, by CreateService and by UpdateService. + */ + @Test + void aDiscoveryNameOutsideTheNamingRuleIsRefused() { + for (String name : List.of("API", "-api", "a".repeat(65))) { + assertRefused("ClientException", INVALID_NAME, () -> ecs.createService(r -> r.cluster(CLUSTER) + .serviceName("bad-svc").taskDefinition(FAMILY).desiredCount(0) + .serviceConnectConfiguration(connect(endpoint("http", name, 80))))); + } + assertEquals(List.of(), ecs.listServices(r -> r.cluster(CLUSTER)).serviceArns(), "nothing was created"); + assertEquals(Map.of(), cloudMapServices()); + + createService("web-svc", endpoint("http", "api_v2", 80)); + assertEquals(List.of("api_v2"), List.copyOf(cloudMapServices().keySet())); + assertRefused("InvalidParameterException", INVALID_NAME, () -> ecs.updateService(r -> r.cluster(CLUSTER) + .service("web-svc").serviceConnectConfiguration(connect(endpoint("http", "API", 80))))); + assertEquals(List.of("api_v2"), List.copyOf(cloudMapServices().keySet())); + } + + /** + * A DNS namespace's Cloud Map service names are DNS labels, so Cloud Map holds {@code Web} and {@code web} + * as one name, and a Cloud Map service made outside ECS as {@code Web} keeps an endpoint from {@code web}. + */ + @Test + void aDnsNamespaceComparesDiscoveryNamesAsCloudMapDoes() { + cloudMap.createPublicDnsNamespace(r -> r.name("shop.example")); + String dnsNamespace = cloudMap.listNamespaces(r -> { }).namespaces().stream() + .filter(candidate -> "shop.example".equals(candidate.name())) + .findFirst().orElseThrow().id(); + cleanups.push(() -> cloudMap.deleteNamespace(r -> r.id(dnsNamespace))); + String byHand = cloudMap.createService(r -> r.name("Web").namespaceId(dnsNamespace)).service().arn(); + cleanups.push(() -> cloudMap.deleteService(r -> r.id(byHand.substring(byHand.lastIndexOf('/') + 1)))); + + assertTrue(AwsSdkErrors.assertAwsError("ClientException", 400, () -> ecs.createService(r -> r + .cluster(CLUSTER).serviceName("case-svc").taskDefinition(FAMILY).desiredCount(0) + .serviceConnectConfiguration(ServiceConnectConfiguration.builder().enabled(true) + .namespace("shop.example").services(endpoint("http", "web", 80)).build()))) + .awsErrorDetails().errorMessage().matches(CLOUD_MAP_SERVICE_EXISTS)); + assertEquals(List.of("Web"), List.copyOf(cloudMapServices(dnsNamespace).keySet())); + + // A portName isn't held to lowercase, so it can repeat a discoveryName in a case of its own. + assertRefused("ClientException", "The following discoveryNames are defined more than once: [Admin].", + () -> ecs.createService(r -> r.cluster(CLUSTER).serviceName("twice-svc").taskDefinition(FAMILY) + .desiredCount(0).serviceConnectConfiguration(ServiceConnectConfiguration.builder() + .enabled(true).namespace("shop.example") + .services(endpoint("http", "admin", 80), endpoint("Admin", null, 81)).build()))); + assertEquals(List.of("Web"), List.copyOf(cloudMapServices(dnsNamespace).keySet())); + } + + private Service createService(String name, ServiceConnectService... endpoints) { + Service created = ecs.createService(r -> r.cluster(CLUSTER).serviceName(name).taskDefinition(FAMILY) + .desiredCount(0).serviceConnectConfiguration(connect(endpoints))).service(); + cleanups.push(() -> ecs.deleteService(r -> r.cluster(CLUSTER).service(name).force(true))); + return created; + } + + private void update(String name, ServiceConnectConfiguration configuration) { + ecs.updateService(r -> r.cluster(CLUSTER).service(name).serviceConnectConfiguration(configuration)); + } + + private Deployment deployment(String name) { + return ecs.describeServices(r -> r.cluster(CLUSTER).services(name)).services().getFirst() + .deployments().getFirst(); + } + + /** The namespace's Cloud Map services by name. */ + private Map cloudMapServices() { + return cloudMapServices(namespace.id()); + } + + private Map cloudMapServices(String namespaceId) { + Map byName = new TreeMap<>(); + cloudMap.listServicesPaginator(r -> r.filters(f -> f.name(ServiceFilterName.NAMESPACE_ID) + .condition(FilterCondition.EQ).values(namespaceId))) + .stream().flatMap(page -> page.services().stream()) + .forEach(service -> byName.put(service.name(), service)); + return byName; + } + + private ServiceConnectConfiguration connect(ServiceConnectService... endpoints) { + return ServiceConnectConfiguration.builder().enabled(true).namespace(namespace.name()) + .services(endpoints).build(); + } + + private static ServiceConnectService endpoint(String portName, String discoveryName, int port) { + return ServiceConnectService.builder().portName(portName).discoveryName(discoveryName) + .clientAliases(alias -> alias.port(port)).build(); + } + + private static ServiceConnectServiceResource resource(String discoveryName, String discoveryArn) { + return ServiceConnectServiceResource.builder().discoveryName(discoveryName).discoveryArn(discoveryArn).build(); + } + + private static void assertRefused(String code, String message, Executable call) { + assertEquals(message, AwsSdkErrors.assertAwsError(code, 400, call).awsErrorDetails().errorMessage()); + } + + /** Describes the Cloud Map service as ECS does the ones it creates, and checks its tag. */ + private void assertManagedBy(String serviceArn, ServiceSummary service) { + String id = service.arn().substring(service.arn().lastIndexOf('/') + 1); + assertEquals("Managed by " + serviceArn, cloudMap.getService(r -> r.id(id)).service().description()); + assertEquals(Map.of("AmazonECSManaged", "true"), cloudMap.listTagsForResource(r -> r.resourceARN( + service.arn())).tags().stream().collect(Collectors.toMap(Tag::key, Tag::value))); + } +} diff --git a/src/test/java/io/floci/aws/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java b/src/test/java/io/floci/aws/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java index d6a0a34d5f..e096864fac 100644 --- a/src/test/java/io/floci/aws/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java +++ b/src/test/java/io/floci/aws/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java @@ -15,6 +15,7 @@ import io.floci.aws.services.ecs.model.Deployment; import io.floci.aws.services.ecs.model.EcsServiceModel; import io.floci.aws.services.ecs.model.EcsTask; import io.floci.aws.services.ecs.model.LaunchType; +import io.floci.aws.services.ecs.model.ServiceConnectServiceResource; import io.floci.aws.services.ecs.model.ServiceDeployment; import io.floci.aws.services.ecs.model.ServiceRevision; import io.floci.aws.services.ecs.model.TaskDefinition; @@ -61,6 +62,8 @@ class EcsServiceDeploymentCircuitBreakerTest { private boolean healthy; /** When set, the next launch is stopped by a user while its image is still pulling. */ private boolean stopDuringPull; + /** The Cloud Map side a service is built with; none unless a test sets one first. */ + private EcsServiceDiscoveryRegistrar discoveryRegistrar; private EcsService service; @Test @@ -351,6 +354,80 @@ class EcsServiceDeploymentCircuitBreakerTest { argThat(reason -> reason.contains(successfulDeploymentId)), eq(REGION)); } + /** + * A rollback restores the Service Connect configuration of the revision it returns to, and with + * it the namespace ListServicesByNamespace lists the service under and the Cloud Map services + * behind its endpoints. When another service took a discovery name meanwhile, the rollback goes + * through without endpoints and drops the failed deployment's. + */ + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void rollbackRestoresTheServiceConnectEndpoints(boolean namesStillFree) { + discoveryRegistrar = mock(EcsServiceDiscoveryRegistrar.class); + String first = cloudMapNamespaceArn("first"); + String second = cloudMapNamespaceArn("second"); + when(discoveryRegistrar.namespaceArn("first", REGION)).thenReturn(first); + when(discoveryRegistrar.namespaceArn("second", REGION)).thenReturn(second); + List web = List.of(new ServiceConnectServiceResource("web", + "arn:aws:servicediscovery:" + REGION + ":000000000000:service/srv-web")); + List admin = List.of(new ServiceConnectServiceResource("admin", + "arn:aws:servicediscovery:" + REGION + ":000000000000:service/srv-admin")); + if (namesStillFree) { + when(discoveryRegistrar.syncServiceConnectServices(any(), eq(List.of("web")), eq(first), + eq(REGION), any(), any())).thenReturn(web); + } else { + when(discoveryRegistrar.syncServiceConnectServices(any(), eq(List.of("web")), eq(first), + eq(REGION), any(), any())).thenReturn(web).thenThrow(new AwsException( + "InvalidParameterException", "SC service is already used by " + first, 400)); + } + when(discoveryRegistrar.syncServiceConnectServices(any(), eq(List.of("admin")), eq(second), + eq(REGION), any(), any())).thenReturn(admin); + EcsService service = newService(); + healthy = true; + service.createCluster("cb-connect-cluster", REGION); + registerTaskDef(service, "cb-connect-fam", "app:1"); + CreateServiceRequest request = new CreateServiceRequest(); + request.setCluster("cb-connect-cluster"); + request.setServiceName("cb-connect"); + request.setTaskDefinition("cb-connect-fam"); + request.setDesiredCount(1); + request.setLaunchType(LaunchType.FARGATE); + request.setDeploymentConfiguration(Map.of("deploymentCircuitBreaker", breaker(true, true))); + request.setServiceConnectConfiguration(Map.of("enabled", true, "namespace", "first", + "services", List.of(Map.of("portName", "web")))); + String serviceArn = service.createService(request, REGION).getServiceArn(); + service.reconcileServices(); + service.reconcileServices(); + + healthy = false; + TaskDefinition broken = registerTaskDef(service, "cb-connect-fam", "app:broken"); + String failedId = service.updateService("cb-connect-cluster", "cb-connect", + "cb-connect-fam:" + broken.getRevision(), null, null, null, false, + Map.of("enabled", true, "namespace", "second", "services", List.of(Map.of("portName", "admin"))), + REGION).getDeploymentId(); + assertEquals(List.of(serviceArn), service.listServicesByNamespace("second", null, null, REGION).arns()); + assertEquals(List.of(), service.listServicesByNamespace("first", null, null, REGION).arns()); + assertEquals(admin, liveDeployment(service, "cb-connect").getServiceConnectResources()); + for (int i = 0; i < 3; i++) { + service.reconcileServices(); + } + + assertEquals("ROLLBACK_IN_PROGRESS", deploymentOf(service, "cb-connect", failedId).getStatus()); + assertEquals(List.of(serviceArn), service.listServicesByNamespace("first", null, null, REGION).arns()); + assertEquals(List.of(), service.listServicesByNamespace("second", null, null, REGION).arns()); + if (namesStillFree) { + assertEquals(web, liveDeployment(service, "cb-connect").getServiceConnectResources()); + } else { + assertEquals(List.of(), liveDeployment(service, "cb-connect").getServiceConnectResources()); + verify(discoveryRegistrar).syncServiceConnectServices(admin, List.of(), null, REGION, serviceArn, + "InvalidParameterException"); + } + } + + private static String cloudMapNamespaceArn(String name) { + return "arn:aws:servicediscovery:" + REGION + ":" + EcsServiceFixtures.ACCOUNT + ":namespace/ns-" + name; + } + @Test void rollbackKeepsTheCurrentDesiredCountAfterAScaleChange() { EcsService service = newService(); @@ -817,6 +894,7 @@ class EcsServiceDeploymentCircuitBreakerTest { .storageFactory(storage) .cloudWatchMetricsService(metricsService) .eventPublisher(eventPublisher) + .discoveryRegistrar(discoveryRegistrar) .dockerMode() .build(); return service; diff --git a/src/test/java/io/floci/aws/services/ecs/EcsServiceFixtures.java b/src/test/java/io/floci/aws/services/ecs/EcsServiceFixtures.java index f0580c3b8a..0013bec497 100644 --- a/src/test/java/io/floci/aws/services/ecs/EcsServiceFixtures.java +++ b/src/test/java/io/floci/aws/services/ecs/EcsServiceFixtures.java @@ -44,6 +44,7 @@ final class EcsServiceFixtures { private EcsEventPublisher eventPublisher; private StorageFactory storageFactory; private CloudWatchMetricsService cloudWatchMetricsService; + private EcsServiceDiscoveryRegistrar discoveryRegistrar; private Clock clock = Clock.systemUTC(); private boolean dockerMode; @@ -76,6 +77,12 @@ final class EcsServiceFixtures { return this; } + /** The Cloud Map side; none unless the test gives one. */ + Builder discoveryRegistrar(EcsServiceDiscoveryRegistrar discoveryRegistrar) { + this.discoveryRegistrar = discoveryRegistrar; + return this; + } + Builder clock(Clock clock) { this.clock = clock; return this; @@ -94,7 +101,7 @@ final class EcsServiceFixtures { EcsService service = new EcsService(new RegionResolver(REGION, ACCOUNT), containerManager, config, loadBalancerRegistrar, storageFactory != null ? storageFactory : new InMemoryStorageFactory(ACCOUNT), eventPublisher, - new EcsExecSessionRegistry(), null, cloudWatchMetricsService, clock); + new EcsExecSessionRegistry(), discoveryRegistrar, cloudWatchMetricsService, clock); service.initializeStorage(); return service; }