Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudmap): resolve DNS namespaces and register ECS tasks in them (#4122)
Abhigya04878b8c57aa
diff --git a/docs/services/cloudmap.md b/docs/services/cloudmap.mdindex 4cf7f2d1c7..0294a7aa10 100644--- a/docs/services/cloudmap.md+++ b/docs/services/cloudmap.md@@ -12,10 +12,33 @@ Asynchronous operations (`CreateHttpNamespace`, `CreatePublicDnsNamespace`,`CreatePrivateDnsNamespace`, `DeleteNamespace`, `RegisterInstance`,`DeregisterInstance`) apply their effect synchronously and return an operationid. The operation reaches `SUCCESS` immediately by default, so a follow-up-`GetOperation` call returns a completed operation without polling. No real DNS-records or Route 53 hosted zones are created — public and private DNS-namespaces are assigned a synthetic `HostedZoneId` so SDK and CLI clients can-exercise the full Cloud Map control flow locally.+`GetOperation` call returns a completed operation without polling. No Route 53+hosted zones are created: public and private DNS namespaces are assigned a+synthetic `HostedZoneId` so SDK and CLI clients can exercise the full Cloud Map+control flow locally.++### DNS resolution++A DNS namespace is answerable, not just storable. Floci's embedded DNS server+resolves `<service>.<namespace>` to the `AWS_INSTANCE_IPV4` of the instances+registered under that service, one A record each, so a container that uses Floci+as its resolver reaches its peers by name. Instances registered directly through+`RegisterInstance` and instances an ECS service registers through its+`serviceRegistries` resolve the same way.++Which instances answer follows Route 53: the healthy ones while any instance is+healthy, and all of them when none is, so a service whose instances have all gone+unhealthy still resolves rather than disappearing from DNS. At most eight records+go back either way, as Route 53 answers a service discovery query.+Names inside a DNS namespace stay local when no instance has a usable address:+the resolver answers negatively instead of forwarding them to upstream DNS.++Three limits are worth knowing. `HTTP` namespaces do not resolve, matching AWS,+where they are reachable only through `DiscoverInstances`. Only A records are+served, so a name that AWS would answer with an `SRV` record answers with the+address alone. And the embedded DNS server only runs when Floci itself runs+inside Docker, so name resolution is available to containers, not to processes on+the host.## Supported Operations@@ -115,6 +138,8 @@ print(found["Instances"])## Out of Scope-- Real DNS resolution or Route 53 hosted zone / record set creation.+- Route 53 hosted zone / record set creation.+- SRV, AAAA and CNAME records: `AWS_INSTANCE_PORT` is stored and returned, but only A records are served.- Route 53 health checks backing `HealthCheckConfig` (custom health status is stored, not actively probed).-- Cross-region namespace and service discovery.+- `AWS_INIT_HEALTH_STATUS` and `AWS_EC2_INSTANCE_ID` on `RegisterInstance`. Every instance registers `HEALTHY`, which is AWS's own initial status when `AWS_INIT_HEALTH_STATUS` is absent, so only a caller that explicitly asks for `UNHEALTHY` sees a difference.+- Cross-region namespace and service discovery. A DNS query carries no region, so a name resolves through whichever namespace copy holds instances.diff --git a/docs/services/ecs.md b/docs/services/ecs.mdindex 2020810733..3b5558c611 100644--- a/docs/services/ecs.md+++ b/docs/services/ecs.md@@ -460,6 +460,37 @@ Known differences from AWS:- `SubmitTaskStateChange` / `SubmitContainerStateChange` remain ACK-only; Floci drivesthe task lifecycle itself rather than via agent submissions.+#### Service discovery++A service that declares `serviceRegistries` has each of its running tasks registered as a+Cloud Map instance of the named service, and deregistered when the task stops. The instance+carries `AWS_INSTANCE_IPV4` (the task's ENI address on an awsvpc task, otherwise the+container's address on the Docker network) and `AWS_INSTANCE_PORT` (the entry's `port`, or+the host port its `containerPort` was published on), alongside the metadata attributes AWS+records: `AVAILABILITY_ZONE`, `REGION`, `ECS_SERVICE_NAME`, `ECS_CLUSTER_NAME` and+`ECS_TASK_DEFINITION_FAMILY`. The task id is the instance id, as on AWS, so a replacement+task supersedes its predecessor.++Combined with [Cloud Map answering DNS](cloudmap.md#dns-resolution) for its namespaces, that+is what makes `<cloud-map-service>.<namespace>` resolve to a running task from another+container. Registration is best effort: a registry entry Floci cannot place is logged and+skipped rather than failing the task. `UpdateService` moves running task registrations to+replacement registries; stopping a task removes the registrations it actually created.++Known differences from AWS:++- AWS supports only `SRV` records for a `bridge` or `host` network mode task, since the+ reachable port is the published host port rather than the container port. Floci serves+ only A records, so such a task registers its address and its published host port and+ resolves by address; the port is readable through `DiscoverInstances` rather than DNS.+- `EC2_INSTANCE_ID` is not recorded. Every Floci task runs as a container rather than on a+ registered EC2 host, which is the Fargate case on AWS, where the attribute is also absent.+- An instance's health status never moves. AWS registers a task `UNHEALTHY` and promotes it to+ `HEALTHY` once the container health check passes, for a service discovery service that+ declares `HealthCheckCustomConfig`. Floci feeds no container health into Cloud Map, so a task+ registers `HEALTHY`, which is Cloud Map's own default for a `RegisterInstance` that names no+ `AWS_INIT_HEALTH_STATUS`, and stays there until it is deregistered.+#### Unknown servicesA service reference that does not resolve is returned in `failures` withdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.javanew file mode 100644index 0000000000..019826970f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.java@@ -0,0 +1,22 @@+package io.github.hectorvent.floci.core.common.dns;++import java.util.List;+import java.util.Optional;++/**+ * A source of A records that {@link EmbeddedDnsServer} consults before forwarding a query+ * upstream. Implemented by services that own a private DNS zone, so the DNS server stays+ * independent of them: it discovers implementations through CDI rather than importing one.+ *+ * <p>An implementation answers only for names inside a zone it owns. An empty optional leaves+ * the query to the next source or the upstream resolvers; a present empty list means the name+ * is owned but has no A records. It runs outside any request context.+ */+public interface DnsRecordSource {++ /**+ * Resolves a query name to IPv4 addresses. An empty optional means this source does not own+ * the name. The name arrives without a trailing dot and in the case the client sent.+ */+ Optional<List<String>> resolveIpv4(String name);+}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.javaindex 881d652062..2abb2ace7b 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java@@ -8,6 +8,7 @@ import io.vertx.core.buffer.Buffer;import io.vertx.core.datagram.DatagramSocket;import io.vertx.core.datagram.DatagramSocketOptions;import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.inject.Instance;import jakarta.inject.Inject;import org.jboss.logging.Logger;@@ -34,6 +35,9 @@ import java.util.regex.Pattern;* Docker network IP so virtual-hosted S3 URLs (my-bucket.floci:4566) work from* inside Lambda containers without requiring wildcard Docker aliases.*+ * Also answers for any name a {@link DnsRecordSource} owns, which is how a service that holds+ * a private DNS zone (Cloud Map) gets real records rather than only API responses.+ ** All other queries are forwarded to the upstream resolvers read from /etc/resolv.conf* (Docker's embedded DNS at 127.0.0.11), falling back to the configured public resolvers* (floci.dns.container-fallback-servers) so public hostnames still resolve when the@@ -71,14 +75,24 @@ public class EmbeddedDnsServer {private volatile String serverIp;private final SequencedSet<String> suffixes = new LinkedHashSet<>();private volatile List<String> upstreamDnsServers = List.of();+ // Held as the Iterable a CDI Instance already is, so iterating resolves the beans lazily on+ // the packet path rather than at startup, where a source's storage must not be touched yet.+ private final Iterable<DnsRecordSource> recordSources;EmbeddedDnsServer(List<String> suffixes) {+ this(suffixes, List.of());+ }++ EmbeddedDnsServer(List<String> suffixes, Iterable<DnsRecordSource> recordSources) {this.suffixes.addAll(BUILTIN_SUFFIXES);this.suffixes.addAll(suffixes);+ this.recordSources = recordSources;}@Inject- public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx) {+ public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx,+ Instance<DnsRecordSource> recordSources) {+ this.recordSources = recordSources;if (!containerDetector.isRunningInContainer()) {return;}@@ -135,13 +149,20 @@ public class EmbeddedDnsServer {buf.getShort(); // qclassint questionEnd = buf.position();- Optional<String> resolvedAddress = qtype == 1 ? resolveARecord(qname, myIp) : Optional.empty();- if (resolvedAddress.isPresent()) {- byte[] response = buildAResponse(data, txId, questionOffset, questionEnd, resolvedAddress.get());- socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {});- } else {- forwardAsync(vertx, socket, data, senderHost, senderPort);- }+ vertx.<Optional<List<String>>>executeBlocking(() -> resolveARecordWithOwnership(qname, myIp), false)+ .onSuccess(answer -> {+ if (answer.isEmpty()) {+ forwardAsync(vertx, socket, data, senderHost, senderPort);+ return;+ }+ List<String> addresses = answer.orElseThrow();+ byte[] response = qtype == 1 && !addresses.isEmpty()+ ? buildAResponse(data, txId, questionOffset, questionEnd, addresses)+ : buildEmptyResponse(data, txId, questionOffset, questionEnd,+ addresses.isEmpty() ? 3 : 0);+ socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {});+ })+ .onFailure(e -> LOG.warnv("DNS record lookup failed for {0}: {1}", qname, e.getMessage()));} catch (Exception e) {LOG.debugv("DNS packet error: {0}", e.getMessage());}@@ -163,11 +184,52 @@ public class EmbeddedDnsServer {return false;}- Optional<String> resolveARecord(String name, String myIp) {+ List<String> resolveARecord(String name, String myIp) {+ return resolveARecordWithOwnership(name, myIp).orElse(List.of());+ }++ Optional<List<String>> resolveARecordWithOwnership(String name, String myIp) {if (matchesSuffix(name)) {- return Optional.of(myIp);+ return Optional.of(List.of(myIp));+ }+ Optional<String> ec2PrivateDnsName = resolveEc2PrivateDnsName(name);+ return ec2PrivateDnsName.<List<String>>map(List::of)+ .map(Optional::of).orElseGet(() -> resolveFromRecordSources(name));+ }++ /**+ * Answers from a service that owns a private DNS zone, Cloud Map being the one that does+ * today. A source that throws must not take the DNS server down with it: the query falls+ * through to the upstream resolvers, which is what happened before any source existed.+ */+ private Optional<List<String>> resolveFromRecordSources(String name) {+ if (recordSources == null) {+ return Optional.empty();+ }+ for (DnsRecordSource source : recordSources) {+ try {+ Optional<List<String>> addresses = source.resolveIpv4(name);+ if (addresses != null && addresses.isPresent()) {+ return addresses;+ }+ } catch (Exception e) {+ LOG.debugv("DNS record source {0} failed to resolve {1}: {2}",+ source.getClass().getSimpleName(), name, e.getMessage());+ }}- return resolveEc2PrivateDnsName(name);+ return Optional.empty();+ }++ byte[] buildEmptyResponse(byte[] query, short txId, int questionOffset, int questionEnd, int responseCode) {+ ByteBuffer response = ByteBuffer.allocate(12 + questionEnd - questionOffset);+ response.putShort(txId);+ response.putShort((short) (0x8580 | responseCode));+ response.putShort((short) 1);+ response.putShort((short) 0);+ response.putShort((short) 0);+ response.putShort((short) 0);+ response.put(query, questionOffset, questionEnd - questionOffset);+ return response.array();}Optional<String> resolveEc2PrivateDnsName(String name) {@@ -222,31 +284,34 @@ public class EmbeddedDnsServer {return sb.toString();}- byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, String ip) {+ byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, List<String> ips) {int questionLength = questionEnd - questionOffset;- // header(12) + question + answer(name-ptr(2) + type(2) + class(2) + ttl(4) + rdlen(2) + rdata(4))- ByteBuffer resp = ByteBuffer.allocate(12 + questionLength + 16);+ // header(12) + question + per answer(name-ptr(2) + type(2) + class(2) + ttl(4) + rdlen(2) + rdata(4))+ ByteBuffer resp = ByteBuffer.allocate(12 + questionLength + 16 * ips.size());// headerresp.putShort(txId);- resp.putShort((short) 0x8180); // QR=1, AA=1, RD=1, RCODE=0- resp.putShort((short) 1); // qdcount- resp.putShort((short) 1); // ancount- resp.putShort((short) 0); // nscount- resp.putShort((short) 0); // arcount+ resp.putShort((short) 0x8180); // QR=1, AA=1, RD=1, RCODE=0+ resp.putShort((short) 1); // qdcount+ resp.putShort((short) ips.size()); // ancount+ resp.putShort((short) 0); // nscount+ resp.putShort((short) 0); // arcount// question (copied verbatim from query)resp.put(query, questionOffset, questionLength);- // answer- resp.putShort((short) 0xC00C); // name pointer to offset 12 (start of question name)- resp.putShort((short) 1); // type A- resp.putShort((short) 1); // class IN- resp.putInt(TTL);- resp.putShort((short) 4); // rdlength-- for (String octet : ip.split("\\.")) {- resp.put((byte) Integer.parseInt(octet));+ // answers. A name with several registered addresses gets one A record each, which is+ // what a Cloud Map service backed by more than one instance resolves to on AWS.+ for (String ip : ips) {+ resp.putShort((short) 0xC00C); // name pointer to offset 12 (start of question name)+ resp.putShort((short) 1); // type A+ resp.putShort((short) 1); // class IN+ resp.putInt(TTL);+ resp.putShort((short) 4); // rdlength++ for (String octet : ip.split("\\.")) {+ resp.put((byte) Integer.parseInt(octet));+ }}return resp.array();diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.javanew file mode 100644index 0000000000..323f457bfd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.java@@ -0,0 +1,33 @@+package io.github.hectorvent.floci.services.cloudmap;++import io.github.hectorvent.floci.core.common.dns.DnsRecordSource;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.List;+import java.util.Optional;++/**+ * Backs a Cloud Map DNS namespace with real DNS answers.+ *+ * <p>Cloud Map's control plane accepts namespaces, services and instances and reads them back+ * correctly, but nothing answered DNS for {@code <service>.<namespace>}, so a container that+ * registered fine still failed to resolve its peers. Registering this with the embedded DNS+ * server closes that gap for every caller of the embedded resolver, including containers Floci+ * did not launch and instances registered directly through RegisterInstance.+ */+@ApplicationScoped+public class CloudMapDnsRecordSource implements DnsRecordSource {++ private final CloudMapService cloudMapService;++ @Inject+ public CloudMapDnsRecordSource(CloudMapService cloudMapService) {+ this.cloudMapService = cloudMapService;+ }++ @Override+ public Optional<List<String>> resolveIpv4(String name) {+ return cloudMapService.resolveDnsNameIfOwned(name);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.javaindex b5ace7e0ba..faa9af1427 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java@@ -19,6 +19,7 @@ import org.jboss.logging.Logger;import java.security.SecureRandom;import java.time.Instant;import java.util.ArrayList;+import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;@@ -39,6 +40,8 @@ public class CloudMapService {private static final Logger LOG = Logger.getLogger(CloudMapService.class);private static final String ALNUM = "abcdefghijklmnopqrstuvwxyz0123456789";+ /** Route 53 answers a service discovery query with at most eight records. */+ private static final int MAX_DNS_ANSWERS = 8;private final SecureRandom random = new SecureRandom();@@ -351,6 +354,117 @@ public class CloudMapService {};}+ /**+ * Resolves {@code <service>.<namespace>} to the IPv4 addresses registered under it, so the+ * embedded DNS server can answer for a DNS namespace. The DNS server forwards names outside+ * every DNS namespace upstream, while a name inside a namespace remains owned even when no+ * usable A records exist.+ *+ * <p>Only DNS namespaces answer. An HTTP namespace is discoverable through DiscoverInstances+ * and has no DNS records on AWS, so giving it any here would invent behaviour callers cannot+ * rely on outside Floci.+ *+ * <p>Unlike {@link #discoverInstances}, this takes no region: a DNS query carries none. The+ * longest matching namespace name wins, and a namespace name registered in more than one+ * region resolves through whichever copy holds instances.+ *+ * <p>A DNS query carries no credential either, so this reads the default account's+ * partition. A namespace registered under a non-default account is discoverable through+ * the API but does not resolve by name.+ *+ * <p>Health and answer size follow Route 53: healthy instances answer while any exist, all+ * of them answer when none is healthy, and at most {@link #MAX_DNS_ANSWERS} records go back+ * either way.+ */+ public List<String> resolveDnsName(String queryName) {+ return resolveDnsNameIfOwned(queryName).orElse(List.of());+ }++ /** Keeps zone ownership distinct from the list of A records. */+ public Optional<List<String>> resolveDnsNameIfOwned(String queryName) {+ if (queryName == null || queryName.isBlank()) {+ return Optional.empty();+ }+ String name = queryName.toLowerCase();+ if (name.endsWith(".")) {+ name = name.substring(0, name.length() - 1);+ }++ List<String> addresses = new ArrayList<>();+ String matchedNamespaceName = null;+ for (Namespace namespace : dnsNamespacesByLongestName()) {+ String namespaceName = namespace.getName().toLowerCase();+ String suffix = "." + namespaceName;+ boolean apex = name.equals(namespaceName);+ if (!apex && !name.endsWith(suffix)) {+ continue;+ }+ if (matchedNamespaceName != null && !matchedNamespaceName.equals(namespaceName)) {+ break;+ }+ matchedNamespaceName = namespaceName;+ if (apex) {+ continue;+ }+ String serviceName = name.substring(0, name.length() - suffix.length());+ for (Service service : scan(serviceStore)) {+ if (!namespace.getId().equals(service.getNamespaceId())+ || !serviceName.equalsIgnoreCase(service.getName())) {+ continue;+ }+ for (Instance instance : applyHealthFilter(scanInstances(service.getId()), "HEALTHY_OR_ELSE_ALL")) {+ String ipv4 = instance.getAttributes().get("AWS_INSTANCE_IPV4");+ if (isIpv4(ipv4)) {+ addresses.add(ipv4);+ }+ }+ }+ if (!addresses.isEmpty()) {+ return Optional.of(addresses.size() > MAX_DNS_ANSWERS+ ? addresses.subList(0, MAX_DNS_ANSWERS) : addresses);+ }+ }+ return matchedNamespaceName != null ? Optional.of(List.of()) : Optional.empty();+ }++ /**+ * Whether the attribute is a dotted-quad the DNS server can put in an A record's rdata.+ * AWS rejects anything else at {@code RegisterInstance}; Floci stores it, so a name whose+ * only instance carries a bad value receives a negative response rather than an invalid A+ * record or an answer from an unrelated upstream resolver.+ */+ private static boolean isIpv4(String value) {+ if (value == null || value.isBlank()) {+ return false;+ }+ String[] octets = value.split("\\.", -1);+ if (octets.length != 4) {+ return false;+ }+ for (String octet : octets) {+ if (octet.isEmpty() || octet.length() > 3) {+ return false;+ }+ for (int i = 0; i < octet.length(); i++) {+ if (!Character.isDigit(octet.charAt(i))) {+ return false;+ }+ }+ if (Integer.parseInt(octet) > 255) {+ return false;+ }+ }+ return true;+ }++ 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()))+ .sorted(Comparator.comparingInt((Namespace n) -> n.getName().length()).reversed())+ .toList();+ }+private Service resolveService(String namespaceName, String serviceName, String region) {Namespace ns = scan(namespaceStore).stream().filter(n -> region.equals(n.getRegion()) && namespaceName.equals(n.getName()))diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.javaindex 28772815ad..6242c7d266 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java@@ -108,6 +108,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabprivate final StorageFactory storageFactory;private final EcsEventPublisher eventPublisher;private final EcsExecSessionRegistry execSessions;+ // Null for a service assembled without CDI, which then registers nothing in Cloud Map:+ // what every such caller already expects.+ private final EcsServiceDiscoveryRegistrar discoveryRegistrar;private final boolean dockerMode;private final String baseUrl;// Replaced by afterReset() after a state reset, whose container teardown shuts this scheduler down.@@ -191,7 +194,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabpublic EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,StorageFactory storageFactory, EcsEventPublisher eventPublisher,- EcsExecSessionRegistry execSessions) {+ EcsExecSessionRegistry execSessions,+ EcsServiceDiscoveryRegistrar discoveryRegistrar) {this.regionResolver = regionResolver;this.containerManager = containerManager;this.dockerMode = !config.services().ecs().mock();@@ -200,6 +204,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabthis.storageFactory = storageFactory;this.eventPublisher = eventPublisher;this.execSessions = execSessions;+ this.discoveryRegistrar = discoveryRegistrar;}/** With an exec session registry of its own, for callers that assemble the service without CDI. */@@ -207,7 +212,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, ResettabEmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,StorageFactory storageFactory, EcsEventPublisher eventPublisher) {this(regionResolver, containerManager, config, lbRegistrar, storageFactory, eventPublisher,- new EcsExecSessionRegistry());+ new EcsExecSessionRegistry(), null);}@PostConstruct@@ -1299,6 +1304,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, ResettabstopRequested = TaskStatus.STOPPED.name().equals(task.getDesiredStatus());if (!stopRequested) {registerTaskWithLoadBalancers(task, cluster, region);+ registerTaskForServiceDiscovery(task, cluster, region);}if (eventPublisher != null) {eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region);@@ -1685,6 +1691,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabtask.setStopCode(stopCode);task.bumpVersion();deregisterTaskFromLoadBalancers(task, region);+ deregisterTaskFromServiceDiscovery(task, region);}Map<String, Integer> exitCodes = Map.of();@@ -1758,6 +1765,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab}}+ /** Registers a freshly-started task in Cloud Map if its service declared service registries. */+ private void registerTaskForServiceDiscovery(EcsTask task, EcsCluster cluster, String region) {+ if (discoveryRegistrar == null) {+ return;+ }+ EcsServiceModel svc = owningService(task, cluster);+ if (svc != null && discoveryRegistrar.hasRegistries(svc)) {+ discoveryRegistrar.registerTask(task, svc, region);+ }+ }+/*** Resolves the service that actually launched {@code task}, or {@code null} for a* caller-driven task. Keyed off the reconciler-stamped {@code owningServiceArn} rather than@@ -1791,6 +1809,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab}}+ /** Deregisters a stopping task from the Cloud Map services it actually joined. */+ private void deregisterTaskFromServiceDiscovery(EcsTask task, String region) {+ if (discoveryRegistrar == null || !dockerMode || task.getServiceDiscoveryServiceIds().isEmpty()) {+ return;+ }+ discoveryRegistrar.deregisterTask(task, region);+ }+// ── ECS Exec ──────────────────────────────────────────────────────────────/** The resolved target of an {@code ExecuteCommand}, with the session the client connects to. */@@ -2342,8 +2368,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabsvc.setLoadBalancers(request.getLoadBalancers());}if (request.getServiceRegistries() != null) {- rollingChange |= !request.getServiceRegistries().equals(svc.getServiceRegistries());+ boolean registriesChanged = !request.getServiceRegistries().equals(svc.getServiceRegistries());+ rollingChange |= registriesChanged;svc.setServiceRegistries(request.getServiceRegistries());+ if (registriesChanged) {+ reconcileServiceDiscoveryRegistries(svc, cluster, region);+ }}if (request.getUnparsed() != null) {svc.setUnparsed(mergedUnparsed(svc.getUnparsed(), request.getUnparsed()));@@ -2386,6 +2416,24 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabreturn svc;}+ private void reconcileServiceDiscoveryRegistries(EcsServiceModel svc, EcsCluster cluster, String region) {+ if (!dockerMode || discoveryRegistrar == null) {+ return;+ }+ for (EcsTask task : tasks.values()) {+ if (!ownedBy(task, svc, cluster)) {+ continue;+ }+ synchronized (task) {+ if (!TaskStatus.RUNNING.name().equals(task.getLastStatus())) {+ continue;+ }+ discoveryRegistrar.deregisterTask(task, region);+ discoveryRegistrar.registerTask(task, svc, region);+ }+ }+ }+/*** Folds an update's passthrough members into the ones the service already carries. UpdateService* replaces only the members a request names, so a service created with {@codediff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryRegistrar.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryRegistrar.javanew file mode 100644index 0000000000..50f13ff7d0--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryRegistrar.java@@ -0,0 +1,227 @@+package io.github.hectorvent.floci.services.ecs;++import io.github.hectorvent.floci.services.cloudmap.CloudMapService;+import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;+import io.github.hectorvent.floci.services.ecs.model.Container;+import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;+import io.github.hectorvent.floci.services.ecs.model.EcsTask;+import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * Bridges ECS services to Cloud Map: when an ECS service declares a {@code serviceRegistries}+ * block, this registrar registers each running task as an instance of the named Cloud Map+ * service, and deregisters it when the task stops. Together with Cloud Map answering DNS for+ * its namespaces, that is what makes {@code <cloud-map-service>.<namespace>} resolve to a task.+ * <p>+ * One-way dependency ECS to Cloud Map, mirroring {@link EcsLoadBalancerRegistrar}. Cloud Map+ * never calls back into ECS, so there is no cycle.+ * <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.+ */+@ApplicationScoped+public class EcsServiceDiscoveryRegistrar {++ private static final Logger LOG = Logger.getLogger(EcsServiceDiscoveryRegistrar.class);++ private final CloudMapService cloudMapService;+ private final EcsContainerManager containerManager;++ @Inject+ public EcsServiceDiscoveryRegistrar(CloudMapService cloudMapService, EcsContainerManager containerManager) {+ this.cloudMapService = cloudMapService;+ this.containerManager = containerManager;+ }++ /** Registers the task as a Cloud Map instance of every service registry the ECS service declares. */+ public void registerTask(EcsTask task, EcsServiceModel svc, String region) {+ String instanceId = instanceId(task);+ Set<String> registered = new LinkedHashSet<>();+ for (Map<String, Object> registry : registries(svc)) {+ String cloudMapServiceId = cloudMapServiceId(registry);+ if (cloudMapServiceId == null) {+ continue;+ }+ Map<String, String> attributes = instanceAttributes(task, svc, registry, region);+ if (attributes.isEmpty()) {+ LOG.warnv("ECS task {0} has no address to register into Cloud Map service {1}",+ task.getTaskArn(), cloudMapServiceId);+ continue;+ }+ try {+ cloudMapService.registerInstance(cloudMapServiceId, instanceId, null, attributes, region);+ registered.add(cloudMapServiceId);+ LOG.infov("Registered ECS task {0} as a Cloud Map instance of {1} at {2}",+ task.getTaskArn(), cloudMapServiceId, attributes.get("AWS_INSTANCE_IPV4"));+ } catch (Exception e) {+ LOG.warnv("Could not register ECS task {0} into Cloud Map service {1}: {2}",+ task.getTaskArn(), cloudMapServiceId, e.getMessage());+ }+ }+ task.setServiceDiscoveryServiceIds(List.copyOf(registered));+ }++ /** Deregisters the task from the Cloud Map services it actually registered in. */+ public void deregisterTask(EcsTask task, String region) {+ String instanceId = instanceId(task);+ for (String cloudMapServiceId : task.getServiceDiscoveryServiceIds()) {+ try {+ cloudMapService.deregisterInstance(cloudMapServiceId, instanceId, region);+ LOG.infov("Deregistered ECS task {0} from Cloud Map service {1}",+ task.getTaskArn(), cloudMapServiceId);+ } catch (Exception e) {+ // An instance that never registered, or one a previous stop already removed, is+ // the ordinary case here rather than a failure worth failing the stop over.+ LOG.debugv("Could not deregister ECS task {0} from Cloud Map service {1}: {2}",+ task.getTaskArn(), cloudMapServiceId, e.getMessage());+ }+ }+ task.setServiceDiscoveryServiceIds(List.of());+ }++ public boolean hasRegistries(EcsServiceModel svc) {+ return !registries(svc).isEmpty();+ }++ private List<Map<String, Object>> registries(EcsServiceModel svc) {+ List<Map<String, Object>> registries = svc.getServiceRegistries();+ return registries != null ? registries : List.of();+ }++ /**+ * Builds the instance attributes AWS records for an ECS-registered instance. The address is+ * the task's own ENI address in awsvpc mode, and otherwise the container's address on the+ * Docker network, which is the one another container on that network can reach.+ *+ * <p>The metadata attributes alongside it are the ones the ECS service discovery+ * documentation lists, so a caller can filter a {@code DiscoverInstances} response by them+ * the way it would on AWS. {@code EC2_INSTANCE_ID} is not among them: Floci runs every task+ * as a container rather than on a registered EC2 host, so there is no instance id to name.+ */+ private Map<String, String> instanceAttributes(EcsTask task, EcsServiceModel svc,+ Map<String, Object> registry, String region) {+ Container container = containerFor(task, string(registry, "containerName"));+ String address = task.getPrivateIpAddress();+ if ((address == null || address.isBlank()) && container != null) {+ address = containerManager.resolveContainerHost(container);+ }+ if (address == null || address.isBlank()) {+ return Map.of();+ }++ Map<String, String> attributes = new LinkedHashMap<>();+ attributes.put("AWS_INSTANCE_IPV4", address);+ Integer port = instancePort(container, registry);+ if (port != null) {+ attributes.put("AWS_INSTANCE_PORT", String.valueOf(port));+ }+ putIfPresent(attributes, "AVAILABILITY_ZONE", task.getAvailabilityZone());+ putIfPresent(attributes, "REGION", region);+ putIfPresent(attributes, "ECS_SERVICE_NAME", svc.getServiceName());+ putIfPresent(attributes, "ECS_CLUSTER_NAME", nameFromArn(task.getClusterArn()));+ putIfPresent(attributes, "ECS_TASK_DEFINITION_FAMILY", familyFromArn(task.getTaskDefinitionArn()));+ return attributes;+ }++ private static void putIfPresent(Map<String, String> attributes, String key, String value) {+ if (value != null && !value.isBlank()) {+ attributes.put(key, value);+ }+ }++ /** The trailing name of an ARN, which for a cluster ARN is the cluster name. */+ private static String nameFromArn(String arn) {+ if (arn == null) {+ return null;+ }+ int lastSlash = arn.lastIndexOf('/');+ return lastSlash >= 0 ? arn.substring(lastSlash + 1) : arn;+ }++ /** The family out of {@code .../task-definition/<family>:<revision>}, without the revision. */+ private static String familyFromArn(String taskDefinitionArn) {+ String name = nameFromArn(taskDefinitionArn);+ if (name == null) {+ return null;+ }+ int colon = name.lastIndexOf(':');+ return colon > 0 ? name.substring(0, colon) : name;+ }++ private Container containerFor(EcsTask task, String containerName) {+ if (task.getContainers() == null || task.getContainers().isEmpty()) {+ return null;+ }+ return task.getContainers().stream()+ .filter(c -> containerName == null || containerName.equals(c.getName()))+ .findFirst()+ .orElse(null);+ }++ /**+ * The port an SRV record would carry. An explicit {@code port} wins, as it does on AWS;+ * otherwise the host port the selected container's {@code containerPort} was published on,+ * so a bridge-mode task advertises the port that is reachable rather than the one inside the+ * container. A {@code containerPort} with no matching binding falls back to itself, which is+ * the awsvpc case where the two are always equal.+ */+ private Integer instancePort(Container container, Map<String, Object> registry) {+ Integer port = integer(registry, "port");+ if (port != null) {+ return port;+ }+ Integer containerPort = integer(registry, "containerPort");+ if (container == null || containerPort == null || container.getNetworkBindings() == null) {+ return containerPort;+ }+ return container.getNetworkBindings().stream()+ .filter(b -> containerPort == b.containerPort())+ .map(NetworkBinding::hostPort)+ .findFirst()+ .orElse(containerPort);+ }++ /**+ * The Cloud Map service id inside a registry ARN+ * ({@code arn:<partition>:servicediscovery:<region>:<account>:service/srv-xxxxxxxx}). Returns+ * {@code null} for an entry that names no service, which leaves it unregistered rather than+ * failing the task the caller asked for.+ */+ private String cloudMapServiceId(Map<String, Object> registry) {+ String registryArn = string(registry, "registryArn");+ if (registryArn == null || registryArn.isBlank()) {+ return null;+ }+ int lastSlash = registryArn.lastIndexOf('/');+ if (lastSlash < 0 || lastSlash == registryArn.length() - 1) {+ LOG.warnv("Ignoring an ECS service registry whose registryArn names no Cloud Map service: {0}",+ registryArn);+ return null;+ }+ return registryArn.substring(lastSlash + 1);+ }++ /** ECS registers a task under its task id, so a replacement task supersedes its predecessor. */+ private String instanceId(EcsTask task) {+ String arn = task.getTaskArn();+ int lastSlash = arn.lastIndexOf('/');+ return lastSlash >= 0 ? arn.substring(lastSlash + 1) : arn;+ }++ private static String string(Map<String, Object> registry, String key) {+ return registry.get(key) instanceof String value ? value : null;+ }++ private static Integer integer(Map<String, Object> registry, String key) {+ return registry.get(key) instanceof Number value ? value.intValue() : null;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.javaindex 7b03251288..cc4612ec83 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.ecs.model;+import io.github.hectorvent.floci.services.ecs.EcsServiceDiscoveryRegistrar;import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;@@ -50,7 +51,10 @@ public class EcsServiceModel {private String roleArn;/** {@code deploymentConfiguration}, kept raw: Floci reports it but runs no rollout against it. */private Map<String, Object> deploymentConfiguration;- /** {@code serviceRegistries}, kept raw: Cloud Map registration is not emulated. */+ /**+ * {@code serviceRegistries}, kept raw. {@link EcsServiceDiscoveryRegistrar}+ * reads the three members AWS uses to place the instance; nothing else in ECS acts on it.+ */private List<Map<String, Object>> serviceRegistries;/** Members Floci does not act on, kept verbatim so DescribeServices round-trips. */private Map<String, Object> unparsed;diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.javaindex c5422330e1..66586670f2 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java@@ -21,6 +21,8 @@ public class EcsTask {* caller-supplied label and therefore cannot be trusted to establish ownership.*/private String owningServiceArn;+ /** Cloud Map service ids this task actually registered in, independent of later service updates. */+ private List<String> serviceDiscoveryServiceIds = List.of();private LaunchType launchType;private String lastStatus;private String desiredStatus;@@ -81,6 +83,7 @@ public class EcsTask {this.taskDefinitionArn = other.taskDefinitionArn;this.group = other.group;this.owningServiceArn = other.owningServiceArn;+ this.serviceDiscoveryServiceIds = other.serviceDiscoveryServiceIds;this.launchType = other.launchType;this.lastStatus = other.lastStatus;this.desiredStatus = other.desiredStatus;@@ -138,6 +141,11 @@ public class EcsTask {public String getOwningServiceArn() { return owningServiceArn; }public void setOwningServiceArn(String owningServiceArn) { this.owningServiceArn = owningServiceArn; }+ public List<String> getServiceDiscoveryServiceIds() { return serviceDiscoveryServiceIds; }+ public void setServiceDiscoveryServiceIds(List<String> serviceDiscoveryServiceIds) {+ this.serviceDiscoveryServiceIds = serviceDiscoveryServiceIds;+ }+public LaunchType getLaunchType() { return launchType; }public void setLaunchType(LaunchType launchType) { this.launchType = launchType; }diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.javaindex a4595c3c9a..00683e9d9d 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java@@ -8,6 +8,7 @@ import java.net.DatagramSocket;import java.net.InetAddress;import java.nio.ByteBuffer;import java.util.List;+import java.util.Optional;import static org.junit.jupiter.api.Assertions.*;@@ -100,7 +101,85 @@ class EmbeddedDnsServerTest {void resolveARecord_prefersEc2PrivateDnsAddressOverFlociWildcard() {assertEquals("172.16.128.9",- dns.resolveARecord("ip-172-16-128-9.ec2.internal", "172.16.128.5").orElseThrow());+ dns.resolveARecord("ip-172-16-128-9.ec2.internal", "172.16.128.5").getFirst());+ }++ // ── resolveARecord: DnsRecordSource ───────────────────────────────────────++ @Test+ void resolveARecord_answersFromARecordSource() {+ EmbeddedDnsServer withSource = new EmbeddedDnsServer(+ List.of("localhost.floci.io"),+ List.of(source("valkey.sapphire.internal", List.of("172.31.0.6"))));++ assertEquals(List.of("172.31.0.6"),+ withSource.resolveARecord("valkey.sapphire.internal", "172.31.0.2"));+ }++ @Test+ void resolveARecord_returnsEveryAddressARecordSourceOwns() {+ EmbeddedDnsServer withSource = new EmbeddedDnsServer(+ List.of("localhost.floci.io"),+ List.of(source("api.sapphire.internal", List.of("172.31.0.6", "172.31.0.7"))));++ assertEquals(List.of("172.31.0.6", "172.31.0.7"),+ withSource.resolveARecord("api.sapphire.internal", "172.31.0.2"));+ }++ @Test+ void resolveARecord_forwardsWhenNoRecordSourceOwnsTheName() {+ EmbeddedDnsServer withSource = new EmbeddedDnsServer(+ List.of("localhost.floci.io"),+ List.of(source("valkey.sapphire.internal", List.of("172.31.0.6"))));++ assertTrue(withSource.resolveARecord("example.com", "172.31.0.2").isEmpty());+ assertTrue(withSource.resolveARecordWithOwnership("example.com", "172.31.0.2").isEmpty());+ }++ @Test+ void ownedNameWithNoAddressesDoesNotFallThrough() {+ EmbeddedDnsServer withSource = new EmbeddedDnsServer(+ List.of(), List.of(source("empty.sapphire.internal", List.of())));++ assertEquals(Optional.of(List.of()),+ withSource.resolveARecordWithOwnership("empty.sapphire.internal", "172.31.0.2"));+ }++ @Test+ void emptyOwnedNameProducesAuthoritativeNegativeResponse() {+ byte[] query = buildQuery("empty.sapphire.internal", (short) 0x1234);+ byte[] response = dns.buildEmptyResponse(query, (short) 0x1234, 12, query.length, 3);+ ByteBuffer header = ByteBuffer.wrap(response);++ assertEquals((short) 0x1234, header.getShort(0));+ assertEquals(3, header.getShort(2) & 0x000F);+ assertTrue((header.getShort(2) & 0x0400) != 0, "the answer must be authoritative");+ assertEquals(0, header.getShort(6));+ }++ @Test+ void resolveARecord_keepsAnsweringWhenARecordSourceThrows() {+ DnsRecordSource failing = name -> { throw new IllegalStateException("storage is down"); };+ EmbeddedDnsServer withSource = new EmbeddedDnsServer(+ List.of("localhost.floci.io"),+ List.of(failing, source("valkey.sapphire.internal", List.of("172.31.0.6"))));++ assertEquals(List.of("172.31.0.6"),+ withSource.resolveARecord("valkey.sapphire.internal", "172.31.0.2"));+ }++ @Test+ void resolveARecord_prefersTheFlociWildcardOverARecordSource() {+ EmbeddedDnsServer withSource = new EmbeddedDnsServer(+ List.of("localhost.floci.io"),+ List.of(source("bucket.localhost.floci.io", List.of("172.31.0.6"))));++ assertEquals(List.of("172.31.0.2"),+ withSource.resolveARecord("bucket.localhost.floci.io", "172.31.0.2"));+ }++ private static DnsRecordSource source(String owned, List<String> addresses) {+ return name -> owned.equals(name) ? Optional.of(addresses) : Optional.empty();}// ── matchesSuffix — built-in emulator domains ─────────────────────────────@@ -188,7 +267,7 @@ class EmbeddedDnsServerTest {@Testvoid buildAResponse_hasCorrectTransactionId() {byte[] query = buildQuery("my-bucket.localhost.floci.io", (short) 0x1234);- byte[] response = dns.buildAResponse(query, (short) 0x1234, 12, query.length, "172.19.0.2");+ byte[] response = dns.buildAResponse(query, (short) 0x1234, 12, query.length, List.of("172.19.0.2"));short txId = ByteBuffer.wrap(response).getShort(0);assertEquals((short) 0x1234, txId);}@@ -196,15 +275,33 @@ class EmbeddedDnsServerTest {@Testvoid buildAResponse_flagsIndicateResponse() {byte[] query = buildQuery("bucket.localhost.floci.io", (short) 1);- byte[] response = dns.buildAResponse(query, (short) 1, 12, query.length, "10.0.0.1");+ byte[] response = dns.buildAResponse(query, (short) 1, 12, query.length, List.of("10.0.0.1"));short flags = ByteBuffer.wrap(response).getShort(2);assertTrue((flags & 0x8000) != 0, "QR bit must be set");}+ @Test+ void buildAResponse_answerCountMatchesTheAddressCount() {+ byte[] query = buildQuery("api.sapphire.internal", (short) 9);+ byte[] response = dns.buildAResponse(query, (short) 9, 12, query.length,+ List.of("172.31.0.6", "172.31.0.7"));+ int questionLength = query.length - 12;+ ByteBuffer resp = ByteBuffer.wrap(response);++ assertEquals(2, resp.getShort(6));+ assertEquals(12 + questionLength + 32, response.length);+ // second answer: name-ptr(2) + type(2) + class(2) + ttl(4) + rdlen(2) = 12 bytes of header+ resp.position(12 + questionLength + 16 + 12);+ assertEquals((byte) 172, resp.get());+ assertEquals((byte) 31, resp.get());+ assertEquals((byte) 0, resp.get());+ assertEquals((byte) 7, resp.get());+ }+@Testvoid buildAResponse_answerCountIsOne() {byte[] query = buildQuery("bucket.localhost.floci.io", (short) 2);- byte[] response = dns.buildAResponse(query, (short) 2, 12, query.length, "10.0.0.1");+ byte[] response = dns.buildAResponse(query, (short) 2, 12, query.length, List.of("10.0.0.1"));short ancount = ByteBuffer.wrap(response).getShort(6);assertEquals(1, ancount);}@@ -212,7 +309,7 @@ class EmbeddedDnsServerTest {@Testvoid buildAResponse_ipAddressIsCorrect() {byte[] query = buildQuery("bucket.localhost.floci.io", (short) 3);- byte[] response = dns.buildAResponse(query, (short) 3, 12, query.length, "172.19.0.42");+ byte[] response = dns.buildAResponse(query, (short) 3, 12, query.length, List.of("172.19.0.42"));// IP starts at offset: 12 (header) + questionLength + 2+2+2+4+2 = questionLength + 24int questionLength = query.length - 12;ByteBuffer resp = ByteBuffer.wrap(response);diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.javanew file mode 100644index 0000000000..c630531034--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.java@@ -0,0 +1,164 @@+package io.github.hectorvent.floci.services.cloudmap;++import io.github.hectorvent.floci.services.cloudmap.model.Operation;+import io.github.hectorvent.floci.services.cloudmap.model.Service;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Cloud Map's control plane always accepted namespaces, services and instances, but nothing+ * answered DNS for {@code <service>.<namespace>}, so a caller that registered successfully+ * still could not resolve its peers. These cover the lookup the embedded DNS server runs.+ */+@QuarkusTest+class CloudMapDnsResolutionTest {++ private static final String REGION = "us-east-1";++ @Inject+ CloudMapService cloudMapService;++ @Test+ void resolvesARegisteredInstanceInAPrivateDnsNamespace() {+ String namespace = uniqueNamespace();+ Service service = createService(privateDnsNamespace(namespace), "valkey");+ registerInstance(service.getId(), "task-1", "172.31.0.6");++ assertEquals(List.of("172.31.0.6"), cloudMapService.resolveDnsName("valkey." + namespace));+ }++ @Test+ void resolvesEveryHealthyInstanceOfAService() {+ String namespace = uniqueNamespace();+ Service service = createService(privateDnsNamespace(namespace), "api");+ registerInstance(service.getId(), "task-1", "172.31.0.6");+ registerInstance(service.getId(), "task-2", "172.31.0.7");++ assertEquals(2, cloudMapService.resolveDnsName("api." + namespace).size());+ assertTrue(cloudMapService.resolveDnsName("api." + namespace).contains("172.31.0.7"));+ }++ @Test+ void answersWithAtMostEightRecords() {+ // Route 53 answers a service discovery query with up to eight records, however many+ // instances are registered behind the name.+ String namespace = uniqueNamespace();+ Service service = createService(privateDnsNamespace(namespace), "fleet");+ for (int i = 1; i <= 11; i++) {+ registerInstance(service.getId(), "task-" + i, "172.31.0." + i);+ }++ assertEquals(8, cloudMapService.resolveDnsName("fleet." + namespace).size());+ }++ @Test+ void resolutionIsCaseInsensitiveAndToleratesATrailingDot() {+ String namespace = uniqueNamespace();+ Service service = createService(privateDnsNamespace(namespace), "valkey");+ registerInstance(service.getId(), "task-1", "172.31.0.6");++ assertEquals(List.of("172.31.0.6"),+ cloudMapService.resolveDnsName("VALKEY." + namespace.toUpperCase() + "."));+ }++ @Test+ void resolvesAPublicDnsNamespaceToo() {+ String namespace = uniqueNamespace();+ Operation operation = cloudMapService.createPublicDnsNamespace(+ namespace, null, null, Map.of(), REGION);+ Service service = createService(operation.getTargets().get("NAMESPACE"), "edge");+ registerInstance(service.getId(), "task-1", "172.31.0.9");++ assertEquals(List.of("172.31.0.9"), cloudMapService.resolveDnsName("edge." + namespace));+ }++ @Test+ void ignoresAnInstanceWhoseAddressIsNotIpv4() {+ // AWS rejects a non-IPv4 AWS_INSTANCE_IPV4; Floci stores it, and a value the DNS+ // server cannot put in an A record must not take the answer down with it.+ String namespace = uniqueNamespace();+ Service service = createService(privateDnsNamespace(namespace), "mixed");+ registerInstance(service.getId(), "task-bad", "not-an-address");+ registerInstance(service.getId(), "task-good", "172.31.0.12");++ assertEquals(List.of("172.31.0.12"), cloudMapService.resolveDnsName("mixed." + namespace));+ }++ @Test+ void doesNotResolveAnHttpNamespace() {+ // An HTTP namespace is reachable through DiscoverInstances and has no DNS records on AWS.+ String namespace = uniqueNamespace();+ Operation operation = cloudMapService.createHttpNamespace(namespace, null, null, Map.of(), REGION);+ Service service = createService(operation.getTargets().get("NAMESPACE"), "internal");+ registerInstance(service.getId(), "task-1", "172.31.0.8");++ assertTrue(cloudMapService.resolveDnsName("internal." + namespace).isEmpty());+ }++ @Test+ void doesNotResolveAServiceWithNoRegisteredInstance() {+ String namespace = uniqueNamespace();+ createService(privateDnsNamespace(namespace), "empty");++ assertTrue(cloudMapService.resolveDnsName("empty." + namespace).isEmpty());+ assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned("empty." + namespace).orElseThrow());+ }++ @Test+ void doesNotResolveANameOutsideAnyNamespace() {+ assertTrue(cloudMapService.resolveDnsName("example.com").isEmpty());+ assertTrue(cloudMapService.resolveDnsNameIfOwned("example.com").isEmpty());+ assertTrue(cloudMapService.resolveDnsName("").isEmpty());+ assertTrue(cloudMapService.resolveDnsName(null).isEmpty());+ }++ @Test+ void doesNotResolveTheNamespaceNameOnItsOwn() {+ String namespace = uniqueNamespace();+ Service service = createService(privateDnsNamespace(namespace), "valkey");+ registerInstance(service.getId(), "task-1", "172.31.0.6");++ assertTrue(cloudMapService.resolveDnsName(namespace).isEmpty());+ assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned(namespace).orElseThrow());+ }++ @Test+ void nestedNamespaceApexDoesNotResolveThroughTheParentNamespace() {+ String parentName = uniqueNamespace();+ String childName = "nested." + parentName;+ String parentId = privateDnsNamespace(parentName);+ privateDnsNamespace(childName);+ Service parentService = createService(parentId, "nested");+ registerInstance(parentService.getId(), "task-1", "172.31.0.6");++ assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned(childName).orElseThrow());+ assertTrue(cloudMapService.resolveDnsName(childName).isEmpty());+ }++ private String privateDnsNamespace(String name) {+ return cloudMapService.createPrivateDnsNamespace(name, "vpc-dns", null, null, Map.of(), REGION)+ .getTargets().get("NAMESPACE");+ }++ private Service createService(String namespaceId, String serviceName) {+ return cloudMapService.createService(serviceName, namespaceId, null, null,+ null, null, null, null, Map.of(), REGION);+ }++ private void registerInstance(String serviceId, String instanceId, String ipv4) {+ cloudMapService.registerInstance(serviceId, instanceId, null,+ Map.of("AWS_INSTANCE_IPV4", ipv4), REGION);+ }++ private static String uniqueNamespace() {+ return "dnsres" + UUID.randomUUID().toString().substring(0, 8) + ".internal";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryDockerIntegrationTest.javanew file mode 100644index 0000000000..a483b756cb--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryDockerIntegrationTest.java@@ -0,0 +1,192 @@+package io.github.hectorvent.floci.services.ecs;++import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.services.cloudmap.CloudMapService;+import io.github.hectorvent.floci.services.cloudmap.model.Operation;+import io.github.hectorvent.floci.services.cloudmap.model.Service;+import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;+import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;+import io.github.hectorvent.floci.services.ecs.model.CreateServiceRequest;+import io.github.hectorvent.floci.services.ecs.model.EcsTask;+import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;+import io.github.hectorvent.floci.services.ecs.model.NetworkMode;+import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;+import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Pins the ECS to Cloud Map wiring in docker mode, which is the only mode that registers+ * anything: {@link EcsServiceDiscoveryRegistrarTest} drives the registrar directly, so on its+ * own it stays green even if {@link EcsService} never calls it.+ *+ * <p>Nothing here touches the registrar. A service that declares {@code serviceRegistries} has a+ * real container launched for it, and the assertions are that the Cloud Map name resolves to the+ * task's address while it runs and stops resolving once the task does.+ */+@QuarkusTest+@TestProfile(EcsServiceDiscoveryDockerIntegrationTest.DockerEcsProfile.class)+class EcsServiceDiscoveryDockerIntegrationTest {++ private static final String REGION = "us-east-1";+ private static final String SUBNET = "subnet-default-us-east-1-a";+ private static final String BUSYBOX_IMAGE = "public.ecr.aws/docker/library/busybox:latest";+ private static final String CONTAINER_NAME = "app";+ private static final String CLOUD_MAP_SERVICE_NAME = "cache";+ private static final String ECS_SERVICE_NAME = "cache-svc";++ /**+ * The registration hooks only run for a task with a container behind it, so ECS runs+ * unmocked. Security-group enforcement goes back to its shipped default of off: the test+ * suite turns it on, and its helper needs rootful Docker, which is a requirement of security+ * groups rather than of service discovery.+ */+ public static final class DockerEcsProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.ecs.mock", "false",+ "floci.network.security-group-enforcement.enabled", "false");+ }+ }++ @Inject+ EcsService ecsService;++ @Inject+ CloudMapService cloudMapService;++ @Inject+ DockerClient dockerClient;++ @BeforeEach+ void requireDocker() {+ Assumptions.assumeTrue(isDockerAvailable(),+ "Docker daemon must be available for the ECS service discovery test");+ }++ @Test+ void changingAServiceRegistryLeavesNoStaleDnsRecordWhenItsTaskStops() {+ String namespaceName = unique("ecsdisc") + ".internal";+ String dnsName = CLOUD_MAP_SERVICE_NAME + "." + namespaceName;+ Service cloudMapSvc = createDnsService(namespaceName);+ Service replacementRegistry = cloudMapService.createService("replacement", cloudMapSvc.getNamespaceId(),+ null, null, null, null, null, null, Map.of(), REGION);+ String clusterName = unique("disc-cluster");+ ecsService.createCluster(clusterName, REGION);+ TaskDefinition taskDef = registerTaskDefinition(unique("disc-td"));+ ecsService.createService(createServiceRequest(clusterName, taskDef, cloudMapSvc), REGION);++ String taskArn = null;+ try {+ // The reconciler is what launches a service's tasks. Driving one tick keeps the test+ // off the five second timer rather than polling for the container to show up.+ ecsService.reconcile();++ List<String> taskArns = ecsService.listTasks(clusterName, null, null, null, REGION);+ assertEquals(1, taskArns.size(), "the reconciler must launch the service's task");+ taskArn = taskArns.getFirst();+ EcsTask task = ecsService.describeTasks(clusterName, taskArns, REGION).getFirst();+ assertEquals("RUNNING", task.getLastStatus(), "the container must be up: "+ + task.getStoppedReason());+ assertNotNull(task.getPrivateIpAddress(), "an awsvpc task must carry its ENI address");++ assertEquals(List.of(task.getPrivateIpAddress()), cloudMapService.resolveDnsName(dnsName),+ "starting the task must register it, so the Cloud Map name resolves to it");++ // Updating the registry moves the running task to the replacement. Scaling to zero+ // keeps the reconciler from replacing it between the stop and the final assertions.+ UpdateServiceRequest update = new UpdateServiceRequest();+ update.setCluster(clusterName);+ update.setService(ECS_SERVICE_NAME);+ update.setDesiredCount(0);+ update.setServiceRegistries(List.of(Map.of(+ "registryArn", replacementRegistry.getArn(),+ "containerName", CONTAINER_NAME,+ "containerPort", 6379)));+ ecsService.updateService(update, REGION);+ assertTrue(cloudMapService.listInstances(cloudMapSvc.getId()).isEmpty(),+ "updating the registry must remove the old Cloud Map instance");+ assertEquals(List.of(task.getPrivateIpAddress()),+ cloudMapService.resolveDnsName("replacement." + namespaceName),+ "updating the registry must register the running task in the new service");+ ecsService.stopTask(clusterName, taskArn, "service discovery test", REGION);+ taskArn = null;++ assertTrue(cloudMapService.listInstances(cloudMapSvc.getId()).isEmpty(),+ "stopping the task must deregister its Cloud Map instance");+ assertTrue(cloudMapService.resolveDnsName(dnsName).isEmpty(),+ "a stopped task must not keep answering DNS");+ assertTrue(cloudMapService.listInstances(replacementRegistry.getId()).isEmpty(),+ "stopping the task must remove its replacement registry instance");+ } finally {+ if (taskArn != null) {+ ecsService.stopTask(clusterName, taskArn, "test teardown", REGION);+ }+ ecsService.deleteService(clusterName, ECS_SERVICE_NAME, true, REGION);+ }+ }++ private CreateServiceRequest createServiceRequest(String clusterName, TaskDefinition taskDef,+ Service cloudMapSvc) {+ AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();+ awsvpc.setSubnets(List.of(SUBNET));+ NetworkConfiguration networkConfiguration = new NetworkConfiguration();+ networkConfiguration.setAwsvpcConfiguration(awsvpc);++ CreateServiceRequest request = new CreateServiceRequest();+ request.setCluster(clusterName);+ request.setServiceName(ECS_SERVICE_NAME);+ request.setTaskDefinition(taskDef.getTaskDefinitionArn());+ request.setDesiredCount(1);+ request.setNetworkConfiguration(networkConfiguration);+ request.setServiceRegistries(List.of(Map.of(+ "registryArn", cloudMapSvc.getArn(),+ "containerName", CONTAINER_NAME,+ "containerPort", 6379)));+ return request;+ }++ /** awsvpc, which is the mode AWS answers service discovery with A records for. */+ private TaskDefinition registerTaskDefinition(String family) {+ ContainerDefinition app = new ContainerDefinition();+ app.setName(CONTAINER_NAME);+ app.setImage(BUSYBOX_IMAGE);+ app.setCommand(List.of("sleep", "120"));+ return ecsService.registerTaskDefinition(family, List.of(app), NetworkMode.awsvpc,+ null, null, null, null, null, REGION);+ }++ private Service createDnsService(String namespaceName) {+ Operation operation = cloudMapService.createPrivateDnsNamespace(+ namespaceName, "vpc-ecsdisc", null, null, Map.of(), REGION);+ String namespaceId = operation.getTargets().get("NAMESPACE");+ return cloudMapService.createService(CLOUD_MAP_SERVICE_NAME, namespaceId, null, null,+ null, null, null, null, Map.of(), REGION);+ }++ private static String unique(String prefix) {+ return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);+ }++ private boolean isDockerAvailable() {+ try {+ dockerClient.pingCmd().exec();+ return true;+ } catch (RuntimeException e) {+ return false;+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryRegistrarTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryRegistrarTest.javanew file mode 100644index 0000000000..9d6d391802--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDiscoveryRegistrarTest.java@@ -0,0 +1,174 @@+package io.github.hectorvent.floci.services.ecs;++import io.github.hectorvent.floci.services.cloudmap.CloudMapService;+import io.github.hectorvent.floci.services.cloudmap.model.Instance;+import io.github.hectorvent.floci.services.cloudmap.model.Operation;+import io.github.hectorvent.floci.services.cloudmap.model.Service;+import io.github.hectorvent.floci.services.ecs.model.Container;+import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;+import io.github.hectorvent.floci.services.ecs.model.EcsTask;+import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Component test for {@link EcsServiceDiscoveryRegistrar}: drives register/deregister directly+ * with a synthetic task against a real {@link CloudMapService}, mirroring+ * {@link EcsLoadBalancerRegistrarTest}. Also asserts the point of the whole exercise, that a+ * registered task is what makes {@code <service>.<namespace>} resolve.+ */+@QuarkusTest+class EcsServiceDiscoveryRegistrarTest {++ private static final String REGION = "us-east-1";++ @Inject+ EcsServiceDiscoveryRegistrar registrar;++ @Inject+ CloudMapService cloudMapService;++ @Test+ void registerTaskMakesTheServiceNameResolve() {+ String namespace = uniqueName("svcdisc") + ".internal";+ Service cloudMapSvc = createDnsService(namespace, "valkey");+ EcsTask task = task("172.31.0.6", "valkey", 6379, 6379);+ EcsServiceModel svc = serviceWithRegistry(cloudMapSvc.getArn(), "valkey", 6379);++ registrar.registerTask(task, svc, REGION);++ List<Instance> instances = cloudMapService.listInstances(cloudMapSvc.getId());+ assertEquals(1, instances.size());+ assertEquals("172.31.0.6", instances.getFirst().getAttributes().get("AWS_INSTANCE_IPV4"));+ assertEquals("6379", instances.getFirst().getAttributes().get("AWS_INSTANCE_PORT"));+ assertEquals(List.of("172.31.0.6"), cloudMapService.resolveDnsName("valkey." + namespace));+ }++ @Test+ void deregisterTaskStopsTheServiceNameResolving() {+ String namespace = uniqueName("svcdisc") + ".internal";+ Service cloudMapSvc = createDnsService(namespace, "auth");+ EcsTask task = task("172.31.0.7", "auth", 8080, 8080);+ EcsServiceModel svc = serviceWithRegistry(cloudMapSvc.getArn(), "auth", 8080);+ registrar.registerTask(task, svc, REGION);++ registrar.deregisterTask(task, REGION);++ assertTrue(cloudMapService.listInstances(cloudMapSvc.getId()).isEmpty());+ assertTrue(cloudMapService.resolveDnsName("auth." + namespace).isEmpty());+ }++ @Test+ void deregisterTaskUsesItsRegisteredServiceAfterTheEcsServiceChanges() {+ String namespace = uniqueName("svcdisc") + ".internal";+ Service original = createDnsService(namespace, "original");+ Service replacement = cloudMapService.createService("replacement", original.getNamespaceId(),+ null, null, null, null, null, null, Map.of(), REGION);+ EcsTask task = task("172.31.0.7", "app", 8080, 8080);+ EcsServiceModel svc = serviceWithRegistry(original.getArn(), "app", 8080);+ registrar.registerTask(task, svc, REGION);+ assertEquals(List.of(original.getId()), task.getServiceDiscoveryServiceIds());++ svc.setServiceRegistries(List.of(Map.of("registryArn", replacement.getArn())));+ registrar.deregisterTask(task, REGION);++ assertTrue(cloudMapService.listInstances(original.getId()).isEmpty());+ assertTrue(cloudMapService.listInstances(replacement.getId()).isEmpty());+ assertTrue(task.getServiceDiscoveryServiceIds().isEmpty());+ }++ @Test+ void registerTaskAdvertisesThePublishedHostPortInBridgeMode() {+ String namespace = uniqueName("svcdisc") + ".internal";+ Service cloudMapSvc = createDnsService(namespace, "api");+ // No task-level ENI address: a bridge-mode task is reached on its published host port.+ EcsTask task = task(null, "api", 8080, 32768);+ EcsServiceModel svc = serviceWithRegistry(cloudMapSvc.getArn(), "api", 8080);++ registrar.registerTask(task, svc, REGION);++ Instance instance = cloudMapService.listInstances(cloudMapSvc.getId()).getFirst();+ assertEquals("32768", instance.getAttributes().get("AWS_INSTANCE_PORT"));+ }++ @Test+ void registerTaskRecordsTheMetadataAttributesAwsAdds() {+ String namespace = uniqueName("svcdisc") + ".internal";+ Service cloudMapSvc = createDnsService(namespace, "billing");+ EcsTask task = task("172.31.0.10", "billing", 9090, 9090);+ task.setAvailabilityZone("us-east-1a");+ task.setClusterArn("arn:aws:ecs:" + REGION + ":000000000000:cluster/payments");+ task.setTaskDefinitionArn("arn:aws:ecs:" + REGION + ":000000000000:task-definition/billing-td:7");+ EcsServiceModel svc = serviceWithRegistry(cloudMapSvc.getArn(), "billing", 9090);+ svc.setServiceName("billing-svc");++ registrar.registerTask(task, svc, REGION);++ Map<String, String> attributes = cloudMapService.listInstances(cloudMapSvc.getId())+ .getFirst().getAttributes();+ assertEquals("us-east-1a", attributes.get("AVAILABILITY_ZONE"));+ assertEquals(REGION, attributes.get("REGION"));+ assertEquals("billing-svc", attributes.get("ECS_SERVICE_NAME"));+ assertEquals("payments", attributes.get("ECS_CLUSTER_NAME"));+ assertEquals("billing-td", attributes.get("ECS_TASK_DEFINITION_FAMILY"));+ }++ @Test+ void registryWithAnUnusableArnIsIgnored() {+ EcsTask task = task("172.31.0.8", "orphan", 80, 80);+ EcsServiceModel svc = serviceWithRegistry("not-an-arn", "orphan", 80);++ registrar.registerTask(task, svc, REGION);+ registrar.deregisterTask(task, REGION);+ }++ @Test+ void hasRegistriesIsFalseForAServiceThatDeclaredNone() {+ EcsServiceModel svc = new EcsServiceModel();+ assertTrue(!registrar.hasRegistries(svc));++ svc.setServiceRegistries(List.of());+ assertTrue(!registrar.hasRegistries(svc));+ }++ private Service createDnsService(String namespaceName, String serviceName) {+ Operation operation = cloudMapService.createPrivateDnsNamespace(+ namespaceName, "vpc-svcdisc", null, null, Map.of(), REGION);+ String namespaceId = operation.getTargets().get("NAMESPACE");+ return cloudMapService.createService(serviceName, namespaceId, null, null,+ null, null, null, null, Map.of(), REGION);+ }++ private EcsServiceModel serviceWithRegistry(String registryArn, String containerName, int containerPort) {+ EcsServiceModel svc = new EcsServiceModel();+ svc.setServiceRegistries(List.of(Map.of(+ "registryArn", registryArn,+ "containerName", containerName,+ "containerPort", containerPort)));+ return svc;+ }++ private EcsTask task(String privateIpAddress, String containerName, int containerPort, int hostPort) {+ Container container = new Container();+ container.setName(containerName);+ container.setNetworkBindings(List.of(+ new NetworkBinding("0.0.0.0", containerPort, hostPort, "tcp")));+ EcsTask task = new EcsTask();+ task.setTaskArn("arn:aws:ecs:" + REGION + ":000000000000:task/c/" + uniqueName("task"));+ task.setPrivateIpAddress(privateIpAddress);+ task.setContainers(List.of(container));+ return task;+ }++ private static String uniqueName(String prefix) {+ return prefix + UUID.randomUUID().toString().substring(0, 8);+ }+}