diff --git a/docs/services/ecs.md b/docs/services/ecs.md index a1de816cda..7f3726e36e 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -513,11 +513,14 @@ Deliberate limits: | `DeleteService` | Delete a service (supports `force`) | | `DescribeServices` | Describe one or more services (includes `deployments`, see below) | | `ListServices` | List service ARNs in a cluster | -| `ListServicesByNamespace` | List services filtered by Cloud Map namespace | +| `ListServicesByNamespace` | List the Region's services whose Service Connect configuration joined a Cloud Map namespace, given by name or ARN (a service with no namespace of its own joins its cluster's default); pages with `maxResults` and `nextToken` | `ListServices` filters on `launchType` and `schedulingStrategy` as well as `cluster`, and pages -with `maxResults` and `nextToken`. Unlike every other ECS listing, which pages a hundred at a -time, a request that names no `maxResults` gets ten ARNs and a `nextToken`. +with `maxResults` and `nextToken`. Like `ListServicesByNamespace`, and unlike every other ECS +listing, which pages a hundred at a time, a request that names no `maxResults` gets ten ARNs and +a `nextToken`. A service joins the namespace its Service Connect configuration names, or its +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. 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 diff --git a/src/main/java/io/floci/aws/services/ecs/EcsJsonHandler.java b/src/main/java/io/floci/aws/services/ecs/EcsJsonHandler.java index 1aaf168b59..db0c4cc582 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsJsonHandler.java @@ -749,13 +749,18 @@ public class EcsJsonHandler { } private Response handleListServicesByNamespace(JsonNode req, String region) { - String namespace = req.path("namespace").asText(); - List arns = service.listServicesByNamespace(namespace, region); + String namespace = req.hasNonNull("namespace") ? req.path("namespace").asText() : null; + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + EcsService.ListPage page = service.listServicesByNamespace(namespace, maxResults, nextToken, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arns.forEach(arr::add); + page.arns().forEach(arr::add); resp.set("serviceArns", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } 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 6b4c5be77c..fb3d4a6c30 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsService.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsService.java @@ -2905,7 +2905,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab /** * @param defaultPageSize the page size when the request names none, which is not the same for - * every listing: ListServices answers with ten, the rest with a hundred. + * every listing: ListServices and ListServicesByNamespace answer with ten, + * the rest with a hundred. */ private static ListPage paginate(List arns, Integer maxResults, String nextToken, int defaultPageSize) { @@ -2926,11 +2927,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab if (nextToken == null || nextToken.isBlank()) { return 0; } + int offset; try { - return Integer.parseInt(Base64Url.decode(nextToken)); + offset = Integer.parseInt(Base64Url.decode(nextToken)); } catch (IllegalArgumentException e) { throw new AwsException("InvalidParameterException", "The nextToken is not valid.", 400); } + if (offset < 0) { + throw new AwsException("InvalidParameterException", "The nextToken is not valid.", 400); + } + return offset; } // ── Task Protection ─────────────────────────────────────────────────────── @@ -3127,6 +3133,7 @@ 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.setDeploymentConfiguration(request.getDeploymentConfiguration()); svc.setEnableExecuteCommand(request.isEnableExecuteCommand()); svc.setEnableECSManagedTags(request.isEnableECSManagedTags()); @@ -3319,6 +3326,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab && !serviceConnectConfiguration.equals(svc.getServiceConnectConfiguration()); if (serviceConnectConfiguration != null) { svc.setServiceConnectConfiguration(serviceConnectConfiguration); + svc.setServiceConnectNamespaceArn(serviceConnectNamespaceArn(svc, cluster, region)); } boolean taskDefChanged = false; String platformVersionBefore = resolvePlatformVersion(svc.getPlatformVersion()); @@ -3615,12 +3623,57 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return paginate(arns, maxResults, nextToken, DEFAULT_SERVICE_PAGE_SIZE); } - public List listServicesByNamespace(String namespace, String region) { - return services.values().stream() - .filter(s -> namespace.equals(s.getNamespace())) - .filter(s -> !"INACTIVE".equals(s.getStatus())) + /** + * Lists the Region's services whose Service Connect configuration joined the namespace a name or ARN gives, its + * own or, when it names none, its cluster's default. Pages ten at a time when the request names no + * {@code maxResults}, as ListServices does. + */ + public ListPage listServicesByNamespace(String namespace, Integer maxResults, String nextToken, String region) { + if (namespace == null || namespace.isBlank()) { + throw new AwsException("InvalidParameterException", "namespace can not be blank.", 400); + } + if (AwsArnUtils.looksLikeArn(namespace) && !isNamespaceArn(namespace)) { + throw new AwsException("InvalidParameterException", "Namespace is not a valid namespace ARN.", 400); + } + String namespaceArn = discoveryRegistrar == null ? null : discoveryRegistrar.namespaceArn(namespace, region); + if (namespaceArn == null) { + throw new AwsException("NamespaceNotFoundException", "Failed to retrieve namespace for " + namespace, 400); + } + List arns = services.entrySet().stream() + .filter(e -> e.getKey().startsWith(region + "::")) + .map(Map.Entry::getValue) + .filter(svc -> !"INACTIVE".equals(svc.getStatus())) + .filter(svc -> namespaceArn.equals(svc.getServiceConnectNamespaceArn())) .map(EcsServiceModel::getServiceArn) .toList(); + return paginate(arns, maxResults, nextToken, DEFAULT_SERVICE_PAGE_SIZE); + } + + private static boolean isNamespaceArn(String value) { + try { + AwsArnUtils.Arn arn = AwsArnUtils.parse(value); + return "servicediscovery".equals(arn.service()) && arn.resource().startsWith("namespace/"); + } catch (IllegalArgumentException e) { + return false; + } + } + + /** + * 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. + */ + private String serviceConnectNamespaceArn(EcsServiceModel svc, EcsCluster cluster, String region) { + Map config = svc.getServiceConnectConfiguration(); + if (discoveryRegistrar == null || config == null || !Boolean.TRUE.equals(config.get("enabled"))) { + return null; + } + Object namespace = config.get("namespace"); + if (namespace == null || namespace.toString().isBlank()) { + Map defaults = cluster == null ? null : cluster.getServiceConnectDefaults(); + namespace = defaults == null ? null : defaults.get("namespace"); + } + return namespace == null || namespace.toString().isBlank() + ? null : discoveryRegistrar.namespaceArn(namespace.toString(), region); } // ── Tags ────────────────────────────────────────────────────────────────── @@ -5332,6 +5385,8 @@ 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))); 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 7d05874064..78df51636b 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java @@ -7,6 +7,7 @@ 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.ecs.container.EcsContainerManager; import io.floci.aws.services.ecs.model.Container; import io.floci.aws.services.ecs.model.EcsRegisteredInstances; @@ -213,6 +214,16 @@ 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) { + for (Namespace namespace : cloudMapService.listNamespaces(region)) { + if (nameOrArn.equals(namespace.getName()) || nameOrArn.equals(namespace.getArn())) { + return namespace.getArn(); + } + } + return null; + } + public boolean hasRegistries(EcsServiceModel svc) { return !registries(svc).isEmpty(); } 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 0d7e2e4bb8..0cbf816935 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 @@ -47,6 +47,11 @@ public class EcsServiceModel { * it; the Service shape itself has no member for it. */ private Map serviceConnectConfiguration; + /** + * The ARN of the Cloud Map namespace the Service Connect configuration joined, its own or its cluster's default, + * resolved when the configuration was set so a later change to the cluster default does not move the service. + */ + private String serviceConnectNamespaceArn; private String platformVersion; private String platformFamily; private List capacityProviderStrategy; @@ -118,6 +123,9 @@ public class EcsServiceModel { public String getFailedDeploymentId() { return failedDeploymentId; } public void setFailedDeploymentId(String failedDeploymentId) { this.failedDeploymentId = failedDeploymentId; } + public String getServiceConnectNamespaceArn() { return serviceConnectNamespaceArn; } + public void setServiceConnectNamespaceArn(String arn) { this.serviceConnectNamespaceArn = arn; } + public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } diff --git a/src/test/java/io/floci/aws/services/ecs/EcsListServicesByNamespaceIntegrationTest.java b/src/test/java/io/floci/aws/services/ecs/EcsListServicesByNamespaceIntegrationTest.java new file mode 100644 index 0000000000..9fdb93eaf3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecs/EcsListServicesByNamespaceIntegrationTest.java @@ -0,0 +1,145 @@ +package io.floci.aws.services.ecs; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ecs.EcsClient; +import software.amazon.awssdk.services.ecs.model.EcsException; +import software.amazon.awssdk.services.ecs.model.ListServicesByNamespaceResponse; +import software.amazon.awssdk.services.ecs.model.ServiceConnectConfiguration; +import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient; +import software.amazon.awssdk.services.servicediscovery.model.NamespaceSummary; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** {@code ListServicesByNamespace} lists the services whose Service Connect configuration joined the namespace. */ +@QuarkusTest +class EcsListServicesByNamespaceIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + + @Test + void theServicesThatJoinedANamespaceAreListedByItsNameOrArnOnePageAtATime() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String namespace = "orders-" + suffix; + String cluster = "ns-cluster-" + suffix; + String defaultsCluster = "ns-defaults-" + suffix; + try (EcsClient ecs = AwsTestClients.create(EcsClient.builder(), ACCOUNT, Region.US_EAST_1); + ServiceDiscoveryClient cloudMap = AwsTestClients.create(ServiceDiscoveryClient.builder(), ACCOUNT, + Region.US_EAST_1)) { + cloudMap.createHttpNamespace(r -> r.name(namespace)); + String namespaceArn = namespaceArn(cloudMap, namespace); + ecs.createCluster(r -> r.clusterName(cluster)); + ecs.createCluster(r -> r.clusterName(defaultsCluster).serviceConnectDefaults(d -> d.namespace(namespace))); + ecs.registerTaskDefinition(r -> r.family("ns-web-" + suffix) + .containerDefinitions(c -> c.name("web").image("nginx").memory(128))); + String byName = createService(ecs, cluster, "by-name", suffix, + ServiceConnectConfiguration.builder().enabled(true).namespace(namespace).build()); + String byArn = createService(ecs, cluster, "by-arn", suffix, + ServiceConnectConfiguration.builder().enabled(true).namespace(namespaceArn).build()); + String byDefault = createService(ecs, defaultsCluster, "by-default", suffix, + ServiceConnectConfiguration.builder().enabled(true).build()); + createService(ecs, cluster, "disabled", suffix, + ServiceConnectConfiguration.builder().enabled(false).namespace(namespace).build()); + createService(ecs, cluster, "plain", suffix, null); + + List expected = List.of(byName, byArn, byDefault); + assertEquals(expected.stream().sorted().toList(), listAll(ecs, namespace).stream().sorted().toList()); + assertEquals(expected.stream().sorted().toList(), listAll(ecs, namespaceArn).stream().sorted().toList()); + } + } + + @Test + void aMissingBlankOrMalformedNamespaceIsRefused() { + try (EcsClient ecs = AwsTestClients.create(EcsClient.builder(), ACCOUNT, Region.US_EAST_1)) { + EcsException missing = assertThrows(EcsException.class, + () -> ecs.listServicesByNamespace(r -> r.namespace("does-not-exist"))); + assertEquals("NamespaceNotFoundException", missing.awsErrorDetails().errorCode()); + assertEquals("Failed to retrieve namespace for does-not-exist", missing.awsErrorDetails().errorMessage()); + + EcsException blank = assertThrows(EcsException.class, + () -> ecs.listServicesByNamespace(r -> r.namespace(" "))); + assertEquals("InvalidParameterException", blank.awsErrorDetails().errorCode()); + assertEquals("namespace can not be blank.", blank.awsErrorDetails().errorMessage()); + + EcsException notNamespace = assertThrows(EcsException.class, () -> ecs.listServicesByNamespace( + r -> r.namespace("arn:aws:ecs:us-east-1:" + ACCOUNT + ":cluster/default"))); + assertEquals("InvalidParameterException", notNamespace.awsErrorDetails().errorCode()); + assertEquals("Namespace is not a valid namespace ARN.", notNamespace.awsErrorDetails().errorMessage()); + } + } + + @Test + void aServiceKeepsTheNamespaceItJoinedWhenItsClusterDefaultChanges() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String joined = "joined-" + suffix; + String later = "later-" + suffix; + String cluster = "ns-moved-" + suffix; + try (EcsClient ecs = AwsTestClients.create(EcsClient.builder(), ACCOUNT, Region.US_EAST_1); + ServiceDiscoveryClient cloudMap = AwsTestClients.create(ServiceDiscoveryClient.builder(), ACCOUNT, + Region.US_EAST_1)) { + cloudMap.createHttpNamespace(r -> r.name(joined)); + cloudMap.createHttpNamespace(r -> r.name(later)); + ecs.createCluster(r -> r.clusterName(cluster).serviceConnectDefaults(d -> d.namespace(joined))); + ecs.registerTaskDefinition(r -> r.family("ns-web-" + suffix) + .containerDefinitions(c -> c.name("web").image("nginx").memory(128))); + String service = createService(ecs, cluster, "inherits", suffix, + ServiceConnectConfiguration.builder().enabled(true).build()); + + ecs.updateCluster(r -> r.cluster(cluster).serviceConnectDefaults(d -> d.namespace(later))); + + assertEquals(List.of(service), listAll(ecs, joined)); + assertEquals(List.of(), listAll(ecs, later)); + } + } + + @Test + void aPageTokenForANegativeOffsetIsRefused() { + String negative = Base64.getUrlEncoder().withoutPadding().encodeToString("-1".getBytes(StandardCharsets.UTF_8)); + String namespace = "token-" + UUID.randomUUID().toString().substring(0, 8); + try (EcsClient ecs = AwsTestClients.create(EcsClient.builder(), ACCOUNT, Region.US_EAST_1); + ServiceDiscoveryClient cloudMap = AwsTestClients.create(ServiceDiscoveryClient.builder(), ACCOUNT, + Region.US_EAST_1)) { + cloudMap.createHttpNamespace(r -> r.name(namespace)); + + EcsException invalid = assertThrows(EcsException.class, + () -> ecs.listServicesByNamespace(r -> r.namespace(namespace).nextToken(negative))); + + assertEquals("InvalidParameterException", invalid.awsErrorDetails().errorCode()); + } + } + + private static List listAll(EcsClient ecs, String namespace) { + List arns = new ArrayList<>(); + String token = null; + do { + String next = token; + ListServicesByNamespaceResponse page = ecs.listServicesByNamespace( + r -> r.namespace(namespace).maxResults(1).nextToken(next)); + assertEquals(true, page.serviceArns().size() <= 1, page.toString()); + arns.addAll(page.serviceArns()); + token = page.nextToken(); + } while (token != null); + return arns; + } + + private static String createService(EcsClient ecs, String cluster, String name, String suffix, + ServiceConnectConfiguration serviceConnect) { + return ecs.createService(r -> r.cluster(cluster).serviceName(name + "-" + suffix) + .taskDefinition("ns-web-" + suffix).desiredCount(0) + .serviceConnectConfiguration(serviceConnect)).service().serviceArn(); + } + + private static String namespaceArn(ServiceDiscoveryClient cloudMap, String name) { + return cloudMap.listNamespaces(r -> r.maxResults(100)).namespaces().stream() + .filter(n -> name.equals(n.name())).map(NamespaceSummary::arn).findFirst().orElseThrow(); + } +}