fix(eks): resolve pod names through Floci's embedded DNS (#8924)

Pods resolve through CoreDNS, which forwards to the resolver file k3s
hands them. k3s takes the node's /etc/resolv.conf, and on a user-defined
Docker network that names only Docker's loopback 127.0.0.11, which k3s
refuses; it then writes a file naming a public resolver. So Route 53
private zones, Cloud Map names and the other names only Floci answers
never resolved from a pod.

When embedded DNS is on and running, and the cluster's Docker network
can reach it, Floci now copies a resolver file naming only its DNS
server into the cluster container before it starts, and passes it to
k3s with --resolv-conf. With Floci in a container that means the
cluster is on Floci's own network: Docker isolates user-defined
networks, and pods given only an unreachable resolver would lose the
public one too. The public fallback resolvers
stay out of it, because CoreDNS picks among its upstreams at random. A
cluster that sets the kubelet's resolv-conf through its tags keeps its
own file. A file that cannot be copied fails the start, as a container
that cannot start does, since k3s would hand its pods a missing file.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 19:51:14 -04:00
1 parent 545006249b
commit 1d8499e837
9 files changed
+407 -21

No files matched your search

@@ -273,6 +273,33 @@ class ContainerBuilderTest {
assertEquals(List.of(), spec.dnsServers());
}
@Test
void embeddedDnsServerIpReachableOnIsTheResolverWithEmbeddedDnsHandsFirst() {
TestFixture fixture = new TestFixture();
assertEquals(Optional.empty(), fixture.builder.embeddedDnsServerIpReachableOn(Optional.empty()));
when(fixture.embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.17.0.1"));
ContainerSpec spec = fixture.builder.newContainer("alpine")
.withEmbeddedDns()
.build();
// Floci running natively listens on the Docker bridge, which every network routes to.
assertEquals(Optional.of(spec.dnsServers().getFirst()),
fixture.builder.embeddedDnsServerIpReachableOn(Optional.of("app-network")));
}
@Test
void embeddedDnsServerIpReachableOnNeedsFlocisOwnNetworkWhenFlociRunsInAContainer() {
TestFixture fixture = new TestFixture();
when(fixture.embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.4"));
when(fixture.currentContainerNetworkResolver.resolveNetworkName()).thenReturn(Optional.of("floci-net"));
assertEquals(Optional.of("172.18.0.4"), fixture.builder.embeddedDnsServerIpReachableOn(Optional.empty()));
assertEquals(Optional.of("172.18.0.4"),
fixture.builder.embeddedDnsServerIpReachableOn(Optional.of("floci-net")));
assertEquals(Optional.empty(), fixture.builder.embeddedDnsServerIpReachableOn(Optional.of("app-network")));
}
@Test
void withEmbeddedDns_preservesExplicitResolversWithoutAddingFallbacks() {
TestFixture fixture = new TestFixture();
@@ -2,12 +2,14 @@ package io.floci.aws.services.eks;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -224,4 +226,25 @@ class EksClusterArgsTest {
List<String> args = EksClusterArgs.parseAndValidateClusterArgs(tags, "demo");
assertEquals(List.of("--kubelet-arg=max-pods=250"), args);
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"floci:kubelet-arg:resolv-conf|/etc/own-resolv.conf",
"floci:kubelet-arg|--resolv-conf=/etc/own-resolv.conf",
"floci:kubelet-args|[\"max-pods=250\", \"resolv-conf=/etc/own-resolv.conf\"]"})
void aKubeletResolvConfTagSetsThePodsResolverFile(String key, String value) {
List<String> args = EksClusterArgs.parseAndValidateClusterArgs(Map.of(key, value), "demo");
assertTrue(EksClusterArgs.setsKubeletResolvConf(args), args.toString());
}
@Test
void otherArgumentsLeaveThePodsResolverFileToFloci() {
assertFalse(EksClusterArgs.setsKubeletResolvConf(null));
assertFalse(EksClusterArgs.setsKubeletResolvConf(List.of()));
assertFalse(EksClusterArgs.setsKubeletResolvConf(List.of(
"--kubelet-arg=max-pods=250",
"--kubelet-arg=resolv-conf-extra=x",
"--kube-apiserver-arg=resolv-conf=/etc/own-resolv.conf")));
}
}
@@ -0,0 +1,204 @@
package io.floci.aws.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.DockerHostResolver;
import io.floci.aws.core.common.docker.PortAllocator;
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
import io.floci.aws.services.eks.model.Cluster;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The resolver file a cluster's k3s node hands its pods: Floci's embedded DNS server alone, so CoreDNS
* forwards to Floci rather than to the public resolver k3s picks when the node's own resolv.conf names
* only Docker's loopback resolver.
*/
class EksClusterPodResolvConfTest {
private static final String FLOCI_DNS = "172.18.0.2";
private static final String RESOLV_CONF_ARG = "--resolv-conf=" + EksClusterManager.POD_RESOLV_CONF_PATH;
private EmulatorConfig config;
private ContainerBuilder containerBuilder;
private ContainerBuilder.Builder builder;
private ContainerLifecycleManager lifecycleManager;
private CopyArchiveToContainerCmd copyCmd;
private EksClusterManager manager;
/** Each file copied into the container, by its path there, and the ones copied after it started. */
private final Map<String, String> copiedFiles = new LinkedHashMap<>();
private final Set<String> copiedAfterStart = new HashSet<>();
private String remotePath;
private String copiedEntry;
private boolean started;
@BeforeEach
void setUp() {
config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
when(config.services().eks().defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
when(config.services().eks().embeddedDns()).thenReturn(true);
containerBuilder = Mockito.mock(ContainerBuilder.class);
builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
when(containerBuilder.embeddedDnsServerIpReachableOn(any())).thenReturn(Optional.of(FLOCI_DNS));
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
DockerClient dockerClient = Mockito.mock(DockerClient.class);
copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(lifecycleManager.create(any())).thenReturn("container-id");
when(lifecycleManager.startCreated(any(), any())).thenAnswer(invocation -> {
started = true;
return new ContainerInfo("container-id", Map.of());
});
when(dockerClient.copyArchiveToContainerCmd(anyString())).thenAnswer(invocation -> {
remotePath = null;
copiedEntry = null;
return copyCmd;
});
when(copyCmd.withRemotePath(anyString())).thenAnswer(invocation -> {
remotePath = invocation.getArgument(0);
return copyCmd;
});
when(copyCmd.withTarInputStream(any())).thenAnswer(invocation -> {
recordFiles(invocation.getArgument(0));
return copyCmd;
});
manager = new EksClusterManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
config, new RegionResolver("us-east-1", "000000000000"), null, null, null, null, null, 0L);
}
@Test
void podsGetAResolverFileNamingOnlyFlocisDnsServer() {
manager.startCluster(cluster(Map.of()));
assertTrue(serverArgs().contains(RESOLV_CONF_ARG), serverArgs().toString());
assertEquals("nameserver " + FLOCI_DNS + "\n", copiedFiles.get(EksClusterManager.POD_RESOLV_CONF_PATH));
assertFalse(copiedAfterStart.contains(EksClusterManager.POD_RESOLV_CONF_PATH),
"k3s reads the file as it starts, so it must be there first");
}
@Test
void podsKeepK3sResolverWhenEmbeddedDnsIsNotRunning() {
when(containerBuilder.embeddedDnsServerIpReachableOn(any())).thenReturn(Optional.empty());
manager.startCluster(cluster(Map.of()));
assertNoResolverFile();
}
@Test
void podsKeepK3sResolverWhenTheClustersNetworkCannotReachFlocisDns() {
// A pod given only a resolver it cannot reach would lose the public one k3s picks as well.
when(config.services().eks().dockerNetwork()).thenReturn(Optional.of("cluster-net"));
when(containerBuilder.embeddedDnsServerIpReachableOn(Optional.of("cluster-net"))).thenReturn(Optional.empty());
manager.startCluster(cluster(Map.of()));
assertNoResolverFile();
}
@Test
void podsKeepK3sResolverWhenEmbeddedDnsIsOff() {
when(config.services().eks().embeddedDns()).thenReturn(false);
manager.startCluster(cluster(Map.of()));
verify(builder, never()).withEmbeddedDns();
assertNoResolverFile();
}
@Test
void aClusterThatSetsTheKubeletsResolverFileKeepsItsOwn() {
manager.startCluster(cluster(Map.of("floci:kubelet-arg:resolv-conf", "/etc/own-resolv.conf")));
assertTrue(serverArgs().contains("--kubelet-arg=resolv-conf=/etc/own-resolv.conf"), serverArgs().toString());
assertNoResolverFile();
}
@Test
void aResolverFileThatCannotBeCopiedFailsTheStartAndRemovesTheContainer() {
when(copyCmd.exec()).thenAnswer(invocation -> {
if (EksClusterManager.POD_RESOLV_CONF_TAR_ENTRY.equals(copiedEntry)) {
throw new IllegalStateException("copy refused");
}
return null;
});
Cluster cluster = cluster(Map.of());
assertThrows(RuntimeException.class, () -> manager.startCluster(cluster));
verify(lifecycleManager, never()).startCreated(any(), any());
verify(lifecycleManager).removeIfExistsStrict(cluster.getDockerName(), true);
}
private void assertNoResolverFile() {
assertFalse(serverArgs().stream().anyMatch(arg -> arg.startsWith("--resolv-conf")), serverArgs().toString());
assertFalse(copiedFiles.containsKey(EksClusterManager.POD_RESOLV_CONF_PATH), copiedFiles.keySet().toString());
}
private List<String> serverArgs() {
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> cmd = ArgumentCaptor.forClass(List.class);
verify(builder).withCmd(cmd.capture());
return cmd.getValue();
}
private void recordFiles(InputStream archive) throws Exception {
try (TarArchiveInputStream tar = new TarArchiveInputStream(archive)) {
for (TarArchiveEntry entry = tar.getNextEntry(); entry != null; entry = tar.getNextEntry()) {
copiedEntry = entry.getName();
if (entry.isFile()) {
String path = remotePath + "/" + entry.getName();
copiedFiles.put(path, new String(tar.readAllBytes(), StandardCharsets.UTF_8));
if (started) {
copiedAfterStart.add(path);
}
}
}
}
}
private static Cluster cluster(Map<String, String> tags) {
Cluster cluster = new Cluster();
cluster.setName("my-cluster");
cluster.setTags(tags);
return cluster;
}
}
@@ -6,10 +6,12 @@ import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.route53.Route53Service;
import io.floci.aws.services.route53.model.ResourceRecord;
import io.floci.aws.services.route53.model.ResourceRecordSet;
import io.floci.aws.services.route53.model.VpcAssociation;
import io.floci.aws.testing.EksTestNode;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -18,12 +20,14 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -31,13 +35,16 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* Enables embedded DNS on the container it starts itself, so it needs no profile and runs on the
* default one alongside the other EKS Docker classes. It needs Docker and a bound embedded DNS
* server, and that server only binds when Floci itself runs in a container, so anywhere else the
* class skips.
* class skips. The pod check starts a cluster through {@link EksClusterManager}, which runs a k3s
* container whether or not EKS is mocked, and its pods resolve through CoreDNS.
*/
@QuarkusTest
class EksRoute53DnsDockerIntegrationTest {
private static final Logger LOG = Logger.getLogger(EksRoute53DnsDockerIntegrationTest.class);
private static final String TEST_IMAGE = "alpine:3.21";
private static final String ACCOUNT = "000000000000";
private static final String POD = "dns-lookup-pod";
@Inject
DockerClient dockerClient;
@@ -54,8 +61,12 @@ class EksRoute53DnsDockerIntegrationTest {
@Inject
Route53Service route53Service;
@Inject
EksClusterManager eksClusterManager;
private String containerId;
private String zoneId;
private Cluster cluster;
@BeforeEach
void requireDockerAndEmbeddedDns() {
@@ -74,6 +85,13 @@ class EksRoute53DnsDockerIntegrationTest {
@AfterEach
void tearDown() {
if (cluster != null) {
try {
eksClusterManager.stopCluster(cluster);
} catch (Exception e) {
LOG.warnv("Failed to stop test cluster: {0}", e.getMessage());
}
}
if (containerId != null) {
try {
lifecycleManager.stopAndRemove(containerId, null);
@@ -99,19 +117,7 @@ class EksRoute53DnsDockerIntegrationTest {
@Test
void clusterContainerResolvesRoute53PrivateHostedZoneRecords() throws Exception {
String testDomain = "corp-it-" + UUID.randomUUID().toString().substring(0, 8) + ".internal.";
zoneId = route53Service.createHostedZone(
testDomain,
UUID.randomUUID().toString(),
"EKS IT private zone",
new VpcAssociation("vpc-12345", "us-east-1")).zone().getId();
ResourceRecordSet aRrs = new ResourceRecordSet();
aRrs.setName("db." + testDomain);
aRrs.setType("A");
aRrs.setTtl(60L);
aRrs.setRecords(List.of(new ResourceRecord("10.0.1.200")));
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", aRrs)), null);
String testDomain = privateZoneWithRecord("10.0.1.200");
ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)
.withName("floci-eks-dns-test-" + UUID.randomUUID().toString().substring(0, 8))
@@ -135,6 +141,57 @@ class EksRoute53DnsDockerIntegrationTest {
assertTrue(output.contains("10.0.1.200"), "Lookup output must contain record IP: " + output);
}
@Test
void podsResolveRoute53PrivateHostedZoneRecordsThroughCoreDns() {
String testDomain = privateZoneWithRecord("10.0.1.201");
cluster = EksTestNode.cluster(ACCOUNT, "dns-pod-" + UUID.randomUUID().toString().substring(0, 8));
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
// On a user-defined Docker network the node's own resolv.conf names only 127.0.0.11; without the
// resolver file Floci hands k3s, CoreDNS would forward to a public resolver instead of to Floci.
assertTrue(node.execOutput("cat", EksClusterManager.POD_RESOLV_CONF_PATH)
.contains(embeddedDnsServer.getServerIp().orElseThrow()),
"the pods' resolver file must name Floci's DNS server");
await("CoreDNS rolled out").atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(2))
.until(() -> node.kubectl("rollout", "status", "deployment/coredns", "-n", "kube-system",
"--timeout=10s").exitCode() == 0);
node.apply("""
apiVersion: v1
kind: Pod
metadata:
name: %s
namespace: default
spec:
containers:
- name: lookup
image: %s
command: ["sleep", "3600"]
""".formatted(POD, TEST_IMAGE));
node.awaitPodRunning(POD, Duration.ofSeconds(90));
String name = "db." + testDomain.substring(0, testDomain.length() - 1);
String answer = node.kubectlOutput("exec", POD, "--", "nslookup", name);
assertTrue(answer.contains("10.0.1.201"), "a pod must resolve the private record through CoreDNS: " + answer);
}
/** Creates a private hosted zone with an A record {@code db.<zone>} answering {@code address}; returns the zone. */
private String privateZoneWithRecord(String address) {
String testDomain = "corp-it-" + UUID.randomUUID().toString().substring(0, 8) + ".internal.";
zoneId = route53Service.createHostedZone(
testDomain,
UUID.randomUUID().toString(),
"EKS IT private zone",
new VpcAssociation("vpc-12345", "us-east-1")).zone().getId();
ResourceRecordSet aRrs = new ResourceRecordSet();
aRrs.setName("db." + testDomain);
aRrs.setType("A");
aRrs.setTtl(60L);
aRrs.setRecords(List.of(new ResourceRecord(address)));
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", aRrs)), null);
return testDomain;
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();