mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudmap): resolve DNS namespaces and register ECS tasks in them (#4122)
* feat(cloudmap): resolve DNS namespaces and register ECS tasks in them Cloud Map's control plane already accepted namespaces, services and instances and read them back correctly, but nothing answered DNS for <service>.<namespace>. A container that registered successfully still failed to resolve its peers, and the gap only surfaced at application runtime because every API call looked right. The embedded DNS server now consults DnsRecordSource implementations before forwarding a query upstream, and Cloud Map provides one: a DNS namespace resolves to the AWS_INSTANCE_IPV4 of the instances registered under it, one A record each. The SPI keeps the direction right, since core must not import a service. Which instances answer follows Route 53: the healthy ones while any instance is healthy, all of them when none is, and at most eight records either way. HTTP namespaces do not resolve, matching AWS, where they are reachable only through DiscoverInstances. An ECS service that declares serviceRegistries now registers each running task as an instance of the named Cloud Map service, and deregisters it when the task stops, mirroring EcsLoadBalancerRegistrar. The address is the task's ENI address on an awsvpc task and the container's Docker network address otherwise, which is the one a peer container can reach. Alongside it the instance carries the metadata attributes the ECS service discovery documentation lists: AVAILABILITY_ZONE, REGION, ECS_SERVICE_NAME, ECS_CLUSTER_NAME and ECS_TASK_DEFINITION_FAMILY. serviceRegistries stays raw: registryArn, containerName and containerPort are the only members anything acts on. * test(ecs): pin the Cloud Map registration hooks with a docker mode test EcsServiceDiscoveryRegistrarTest drives the registrar directly, so removing EcsService's calls to it left every ECS test green. The registration only runs in docker mode, which the suite mocks out, so nothing covered the wiring. The new test runs ECS unmocked under a profile, creates a service that declares serviceRegistries, and drives one reconciler tick to launch a real container. It asserts the Cloud Map name resolves to the task's ENI address while it runs, and that stopping the task removes the instance and the answer. Commenting out either hook fails it: the register hook on the resolve assertion, the deregister hook on the instance one. Security-group enforcement goes back to its shipped default of off for the profile. The suite turns it on and its helper needs rootful Docker, which is a requirement of security groups rather than of service discovery. Also corrects the health status deviation note. An instance registered without AWS_INIT_HEALTH_STATUS starts HEALTHY on AWS too, so the deviation is not the initial status but that Floci never moves it: AWS registers an ECS task UNHEALTHY and promotes it once the container health check passes, for a service that declares HealthCheckCustomConfig. * fix(cloudmap): retain DNS ownership and ECS registry targets * fix(cloudmap): keep namespace apex queries authoritative * style(dns): remove em dash from test heading
This commit is contained in:
1 parent
294f368814
commit
04878b8c57
14 files changed
+1246
-42
No files matched your search
+102
-5
@@ -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 {
|
||||
@Test
|
||||
void 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 {
|
||||
@Test
|
||||
void 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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 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 {
|
||||
@Test
|
||||
void 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 + 24
|
||||
int questionLength = query.length - 12;
|
||||
ByteBuffer resp = ByteBuffer.wrap(response);
|
||||
|
||||
+164
@@ -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";
|
||||
}
|
||||
}
|
||||
+192
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+174
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user